code_editor_cm.py

open in new tab
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
This example demonstrates a code editor widget based on CodeMirror.
"""

# todo: Maybe this should be a widget in the library (flexx.ui.CodeMirror) ?

from flexx import ui, app, event
from flexx.pyscript import window

# Associate CodeMirror's assets with this module so that Flexx will load
# them when (things from) this module is used.
base_url = 'https://cdnjs.cloudflare.com/ajax/libs/codemirror/'
app.assets.associate_asset(__name__, base_url + '5.21.0/codemirror.min.css')
app.assets.associate_asset(__name__, base_url + '5.21.0/codemirror.min.js')
app.assets.associate_asset(__name__, base_url + '5.21.0/mode/python/python.js')
app.assets.associate_asset(__name__, base_url + '5.21.0/theme/solarized.css')
app.assets.associate_asset(__name__, base_url + '5.21.0/addon/selection/active-line.js')
app.assets.associate_asset(__name__, base_url + '5.21.0/addon/edit/matchbrackets.js')

class CodeEditor(ui.Widget):
    """ A CodeEditor widget based on CodeMirror.
    """

    CSS = """
    .flx-CodeEditor > .CodeMirror {
        width: 100%;
        height: 100%;
    }
    """

    class JS:
        def init(self):
            # https://codemirror.net/doc/manual.html
            options = dict(value='import os\n\ndirs = os.walk',
                           mode='python',
                           theme='solarized dark',
                           autofocus=True,
                           styleActiveLine=True,
                           matchBrackets=True,
                           indentUnit=4,
                           smartIndent=True,
                           lineWrapping=True,
                           lineNumbers=True,
                           firstLineNumber=1,
                           readOnly=False,
                           )
            self.cm = window.CodeMirror(self.node, options)

        @event.connect('size')
        def __on_size(self, *events):
            self.cm.refresh()

if __name__ == '__main__':
    app.launch(CodeEditor, 'app')
    app.run()