Examples

If you downloaded a source archive or cloned pyQode from github, you will find a series of examples in the examples directory, at the root of the archive.

All examples requires pyqode.core to be installed.

Note

All examples are bindings independent so that every user can run them without being required to install an unwanted qt binding.

Basic example

This is the most basic example. It starts and configures a very simple editor with only a few modes and panels.

Frontend:

 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A simple example that shows how to setup CodeEdit.

In this example, we install a syntax highlighter mode (based on pygments), a
mode that highlights the current line and a _search and replace_ panel.

There are many other modes and panels, feel free to use this example as a
starting point to experiment.

"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys
from pyqode.core import api
from pyqode.core import modes
from pyqode.core import panels
from pyqode.qt import QtWidgets


def main():
    app = QtWidgets.QApplication(sys.argv)

    # create editor and window
    window = QtWidgets.QMainWindow()
    editor = api.CodeEdit()
    window.setCentralWidget(editor)

    # start the backend as soon as possible
    editor.backend.start('server.py')

    # append some modes and panels
    editor.modes.append(modes.CodeCompletionMode())
    editor.modes.append(modes.CaretLineHighlighterMode())
    editor.modes.append(modes.PygmentsSyntaxHighlighter(editor.document()))
    editor.panels.append(panels.SearchAndReplacePanel(),
                      api.Panel.Position.BOTTOM)

    # open a file
    editor.file.open(__file__)

    # run
    window.show()
    app.exec_()
    editor.file.close()


if __name__ == "__main__":
    main()

Backend:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Simple server which adds a DocumentWordsProvider to the CodeCompletion worker.

"""
from pyqode.core import backend

if __name__ == '__main__':
    backend.CodeCompletionWorker.providers.append(
        backend.DocumentWordsProvider())
    backend.serve_forever()

Custom actions

This example show you how to modify default actions, here we modify the shortcut and the text of the duplicate lines actions.

Note

This example shares the backend script with the Basic example.

 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This example show you how to change default action properties.

Here we change the duplicate line action to use Ctrl+Shift+Down instead of
Ctrl+D, we also chnage the text to upper case.

"""
import sys
from pyqode.qt import QtWidgets

from pyqode.core import api
from pyqode.core import modes
from pyqode.core import panels


def main():
    app = QtWidgets.QApplication(sys.argv)
    window = QtWidgets.QMainWindow()

    # configure editor (see examples/simple/basic.py)
    editor = api.CodeEdit()
    editor.file.open(__file__)
    editor.modes.append(modes.CaretLineHighlighterMode())
    editor.modes.append(modes.PygmentsSyntaxHighlighter(editor.document()))
    editor.panels.append(panels.SearchAndReplacePanel(),
                      api.Panel.Position.TOP)
    window.setCentralWidget(editor)
    window.show()

    # Change action properties
    editor.action_duplicate_line.setShortcut('Ctrl+Shift+Down')
    editor.action_duplicate_line.setText('DUPLICATE LINE')

    app.exec_()
    editor.file.close()
    del editor
    del window
    del app


if __name__ == "__main__":
    main()

Change editor properties

This example show you how to change some editor properties. Here we modify the pygments color scheme.

Note

This example shares the backend script with the Basic example.

 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
In this example, we are going to make a dark code editor widget and make it show visual
whitespaces.

"""
import sys
from pyqode.qt import QtWidgets, QtGui
from pyqode.core import api
from pyqode.core import modes
from pyqode.core import panels


def main():
    app = QtWidgets.QApplication(sys.argv)
    window = QtWidgets.QMainWindow()

    # code from the simple example
    editor = api.CodeEdit()
    editor.file.open(__file__)
    editor.modes.append(modes.CaretLineHighlighterMode())
    sh = modes.PygmentsSyntaxHighlighter(editor.document())
    editor.modes.append(sh)
    editor.panels.append(panels.SearchAndReplacePanel(),
                      api.Panel.Position.TOP)
    # make the code edit show whitespaces in dark gray
    editor.show_white_spaces = True
    editor.whitespaces_foreground = QtGui.QColor('#606020')

    # make a dark editor using the monokai theme
    sh.pygments_style = 'monokai'

    window.setCentralWidget(editor)
    window.show()

    app.exec_()

    editor.file.close()
    del editor
    del window
    del app


if __name__ == "__main__":
    main()

Modes

Auto complete

 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
"""
Minimal example showing the use of the AutoCompleteMode.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.backend import server
from pyqode.core.modes import AutoCompleteMode


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    print(editor.modes.append(AutoCompleteMode()))
    editor.appendPlainText(
        'Press one of these keys to test auto completion: ", \', (, {, [\n')
    editor.show()
    app.exec_()
    editor.close()
    del editor
    del app

Auto indent

 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
"""
Minimal example showing the use of the AutoCompleteMode.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.backend import server
from pyqode.core.modes import AutoCompleteMode


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    print(editor.modes.append(AutoCompleteMode()))
    editor.appendPlainText(
        'Press one of these keys to test auto completion: ", \', (, {, [\n')
    editor.show()
    app.exec_()
    editor.close()
    del editor
    del app

Caret line highlighter

 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
"""
This example will show you that the caret line color is automatically set
by the syntax highlighter mode.

See how the color is different from the color obtained in
``caret_line_highligter.py``
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.backend import server
from pyqode.core.modes import CaretLineHighlighterMode
from pyqode.core.modes import PygmentsSyntaxHighlighter


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    print(editor.modes.append(CaretLineHighlighterMode()))
    print(editor.modes.append(PygmentsSyntaxHighlighter(editor.document())))
    editor.show()
    editor.appendPlainText('\n' * 10)
    app.exec_()
    editor.close()
    del editor
    del app
 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
"""
Minimal example showing the use of the CaretLineHighlighterMode.

This example editor does not have a SyntaxHighlighterMode, the caret line color
is simply derived from the background color (darker for white background,
lighter for dark background)
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.backend import server
from pyqode.core.modes import CaretLineHighlighterMode


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    print(editor.modes.append(CaretLineHighlighterMode()))
    editor.show()
    editor.appendPlainText('\n' * 10)
    app.exec_()
    editor.close()
    del editor
    del app

Case converter

 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
"""
Minimal example showing the use of the CaseConverterMode.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.backend import server
from pyqode.core.modes import CaseConverterMode


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    print(editor.modes.append(CaseConverterMode()))
    editor.show()
    editor.setPlainText(
        'Press Ctrl+Shift+U to convert selected text to upper  case\n'
        'and Ctrl+U to convert the text to lower case.', '', '')
    editor.selectAll()
    app.exec_()
    editor.close()
    del editor
    del app

Checker (linter)

 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
56
"""
Minimal example showing the use of the CheckerMode (to implement a linter)

"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.modes import CheckerMode, CheckerMessages

# use server from this directory so that checker.py is in sys.path
import server


def check(request):
    """
    Worker function that performs the analysis. Here this is a dumb checker
    that always return 3 messages:
        - 1 info message on line 1
        - 1 warning message on line 2
        - 1 error message on line 3

    :param request:  request data (dict).
    :return: True, list of messages
    """
    return [
        ('An information message', CheckerMessages.INFO, 0),
        ('A warning message', CheckerMessages.WARNING, 1),
        ('An error message', CheckerMessages.ERROR, 2),
    ]


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    # use a string instead of the function directly (otherwise we
    # get __main__.check instead of checker.check)
    # print(editor.modes.append(CheckerMode(check)))  # does not work if
                                                      # function is in main
                                                      # module
    print(editor.modes.append(CheckerMode('checker.check')))

    # we could also use the pyqode.python.backend like this (uncomment the next
    # two lines if you have pyqode.python)
    # from pyqode.python.backend import run_pep8
    # print(editor.modes.append(CheckerMode(run_pep8)))
    editor.show()
    editor.appendPlainText('AAA\n' * 4)
    app.exec_()
    editor.close()
    del editor
    del app

Code completion

 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
"""
This example show you how to setup a code completion provider on the backend

(the provider will be automatically used when the user request a code
completion).
"""
from pyqode.core import backend


class CustomCodeCompletionProvider:
    def complete(self, code, *args):
        """
        Provides a static code completion list

        :param code: code to complete
        :param args: additional (unused) arguments.
        """
        return [
            {'name': 'Code'},
            {'name': 'completion'},
            {'name': 'example'}
        ]

if __name__ == '__main__':
    backend.CodeCompletionWorker.providers.append(
        CustomCodeCompletionProvider())
    backend.serve_forever()
 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
"""
This example show you how to setup a code completion mode on the frontend

This example uses the code_completion_backend.py example as a backend server.


The custom code completion provider will provides the following completions:
    - Code
    - completion
    - example
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.modes import CodeCompletionMode


# use a custom server that show how to create a custom code completion provider
import code_completion_backend


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(code_completion_backend.__file__)
    editor.resize(800, 600)
    print(editor.modes.append(CodeCompletionMode()))
    editor.show()
    app.exec_()
    editor.close()
    del editor
    del app

Extended selection

 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
"""
Minimal example showing the use of the ExtendedSelectionMode.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.backend import server
from pyqode.core.modes import ExtendedSelectionMode


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    print(editor.modes.append(ExtendedSelectionMode()))
    editor.file.open(__file__)
    editor.show()
    app.exec_()
    editor.close()
    del editor
    del app

File watcher

 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
"""
Minimal example showing the use of the FileWatcherMode.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtCore, QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.backend import server
from pyqode.core.modes import FileWatcherMode


def simulate_external_modifcations():
    with open('test_file.txt', 'w') as f:
        f.write('test file modified!')


def print_reloaded_event():
    print('File reloaded')


if __name__ == '__main__':
    with open('test_file.txt', 'w') as f:
        f.write('test file')

    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    print(editor.modes.append(FileWatcherMode()))
    editor.file.open('test_file.txt')
    editor.modes.get(FileWatcherMode).file_reloaded.connect(print_reloaded_event)
    editor.modes.get(FileWatcherMode).auto_reload = False
    editor.show()
    QtCore.QTimer.singleShot(1000, simulate_external_modifcations)
    app.exec_()
    editor.close()
    del editor
    del app

Indenter

 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
"""
Minimal example showing the use of the AutoIndentMode.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.backend import server
from pyqode.core.modes import IndenterMode


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    print(editor.modes.append(IndenterMode()))
    editor.show()
    editor.appendPlainText(
        '    Press TAB then Shift+Tab')
    app.exec_()
    editor.close()
    del editor
    del app

Occurences highlighter

 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
"""
Minimal example showing the use of the OccurrencesHighlighterMode.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.backend import server
from pyqode.core.modes import OccurrencesHighlighterMode


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    print(editor.modes.append(OccurrencesHighlighterMode()))
    editor.setPlainText(
        'mode\nmode\nmodes\npanel\nmode', '', '')
    editor.show()
    app.exec_()
    editor.close()
    del editor
    del app

Pygments syntax highligher

 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
"""
Minimal example showing the use of the AutoCompleteMode.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit, ColorScheme
from pyqode.core.backend import server
from pyqode.core.modes import PygmentsSH


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    sh = editor.modes.append(PygmentsSH(editor.document()))
    sh.color_scheme = ColorScheme('monokai')
    editor.file.open(__file__)
    editor.show()
    app.exec_()
    editor.close()
    del editor
    del app

Righ margin

 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
"""
Minimal example showing the use of the AutoCompleteMode.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.backend import server
from pyqode.core.modes import RightMarginMode


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    margin = editor.modes.append(RightMarginMode())
    margin.position = 4
    editor.file.open(__file__)
    editor.show()
    app.exec_()
    editor.close()
    del editor
    del app

Smart backspace

 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
"""
Minimal example showing the use of the SmartBackSpaceMode.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit, TextHelper
from pyqode.core.backend import server
from pyqode.core.modes import SmartBackSpaceMode


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    print(editor.modes.append(SmartBackSpaceMode()))
    editor.show()
    editor.appendPlainText(
        '    Please press "BACKSPACE"; the 4 whitespaces should be deleted '
        'with a single key press')
    TextHelper(editor).goto_line(0, 4)
    app.exec_()
    editor.close()
    del editor
    del app

Symbol matcher

 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
"""
Minimal example showing the use of the SymbolMatcherMode.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.backend import server
from pyqode.core.modes import SymbolMatcherMode


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    print(editor.modes.append(SymbolMatcherMode()))
    editor.appendPlainText(
        '(----(j\njj)\n)')
    editor.show()
    app.exec_()
    editor.close()
    del editor
    del app

Zoom

 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
"""
Minimal example showing the use of the ZoomMode.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.backend import server
from pyqode.core.modes import ZoomMode


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    print(editor.modes.append(ZoomMode()))
    editor.appendPlainText(
        'Use Ctrl+Mouse wheel to zoom in/out\n'
        'Ctrl++ and Ctrl+- can also be used\n'
        'Ctrl+0 resets the editor zoom level to 0')
    editor.show()
    app.exec_()
    editor.close()
    del editor
    del app

Panels

Checker (linter)

 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
56
57
58
"""
Extends the checker mode example with a checker panel.

"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.panels import CheckerPanel
from pyqode.core.modes import CheckerMode, CheckerMessages

# use server from this directory so that checker.py is in sys.path
import server


def check(request):
    """
    Worker function that performs the analysis. Here this is a dumb checker
    that always return 3 messages:
        - 1 info message on line 1
        - 1 warning message on line 2
        - 1 error message on line 3

    :param request:  request data (dict).
    :return: True, list of messages
    """
    return [
        ('An information message', CheckerMessages.INFO, 0),
        ('A warning message', CheckerMessages.WARNING, 1),
        ('An error message', CheckerMessages.ERROR, 2),
    ]


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    # use a string instead of the function directly (otherwise we
    # get __main__.check instead of checker.check)
    # print(editor.modes.append(CheckerMode(check)))  # does not work if
                                                      # function is in main
                                                      # module
    print(editor.modes.append(CheckerMode('checker.check')))
    print(editor.panels.append(CheckerPanel()))

    # we could also use the pyqode.python.backend like this (uncomment the next
    # two lines if you have pyqode.python)
    # from pyqode.python.backend import run_pep8
    # print(editor.modes.append(CheckerMode(run_pep8)))
    editor.show()
    editor.appendPlainText('AAA\n' * 4)
    app.exec_()
    editor.close()
    del editor
    del app

Code folding

 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
"""
Minimal example showing the use of the FoldingPanel.

"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit, IndentFoldDetector
from pyqode.core.backend import server
from pyqode.core.modes import PygmentsSH
from pyqode.core.panels import FoldingPanel


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.file.open(__file__)
    editor.resize(800, 600)
    # code folding panel will fetch data from the text block user state. That
    # state is set by a FoldDetector at highlight time. That means that to use
    # the folding panel, we must first set a syntax highlighter on CodeEdit and
    # set a FoldDetector on the installed syntax highlighter.
    sh = editor.modes.append(PygmentsSH(editor.document()))
    sh.fold_detector = IndentFoldDetector()
    # now we can add our folding panel
    editor.panels.append(FoldingPanel())
    editor.show()
    app.exec_()
    editor.close()
    del editor
    del app

Global checker

 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
56
57
58
59
60
"""
Extends the checker mode example with a global checker panel (that shows all
the error found in the document).
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.panels import GlobalCheckerPanel
from pyqode.core.modes import CheckerMode, CheckerMessages

# use server from this directory so that checker.py is in sys.path
import server


def check(request):
    """
    Worker function that performs the analysis. Here this is a dumb checker
    that always return 3 messages:
        - 1 info message on line 1
        - 1 warning message on line 2
        - 1 error message on line 3

    :param request:  request data (dict).
    :return: True, list of messages
    """
    return [
        ('An information message', CheckerMessages.INFO, 0),
        ('A warning message', CheckerMessages.WARNING, 100),
        ('An error message', CheckerMessages.ERROR, 200),
    ]


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    editor.setCenterOnScroll(False)
    # use a string instead of the function directly (otherwise we
    # get __main__.check instead of checker.check)
    # print(editor.modes.append(CheckerMode(check)))  # does not work if
                                                      # function is in main
                                                      # module
    print(editor.modes.append(CheckerMode('global_checker.check')))
    print(editor.panels.append(GlobalCheckerPanel(),
                               GlobalCheckerPanel.Position.RIGHT))

    # we could also use the pyqode.python.backend like this (uncomment the next
    # two lines if you have pyqode.python)
    # from pyqode.python.backend import run_pep8
    # print(editor.modes.append(CheckerMode(run_pep8)))
    editor.show()
    editor.setPlainText('AAA\n' * 500, '', '')
    app.exec_()
    editor.close()
    del editor
    del app

Line numbers

 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
"""
Minimal example showing the use of the LineNumberPanel.
"""
import logging
logging.basicConfig(level=logging.DEBUG)
import sys

from pyqode.qt import QtWidgets
from pyqode.core.api import CodeEdit
from pyqode.core.backend import server
from pyqode.core.panels import LineNumberPanel


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = CodeEdit()
    editor.backend.start(server.__file__)
    editor.resize(800, 600)
    editor.panels.append(LineNumberPanel())
    editor.file.open(__file__)
    editor.show()
    app.exec_()
    editor.close()
    del editor
    del app

Widgets

Errors table

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
"""
Show the use of the ErrorsTable widget.
"""
import sys
from pyqode.qt import QtWidgets
from pyqode.core.modes import CheckerMessage, CheckerMessages
from pyqode.core.widgets import ErrorsTable

app = QtWidgets.QApplication(sys.argv)
table = ErrorsTable()
table.add_message(CheckerMessage(
    'A fake error message', CheckerMessages.ERROR, 10, path=__file__))
table.add_message(CheckerMessage(
    'A fake warning message', CheckerMessages.WARNING, 5, path=__file__))
table.show()
app.exec_()

File system tree view

 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
"""
This example show you how to use the FileSystemTreeView (we show the
content of test_dir).
"""
import logging
import os
import sys
from pyqode.core.widgets import FileSystemTreeView, FileSystemContextMenu
from pyqode.qt import QtWidgets


logging.basicConfig(level=logging.DEBUG)


if __name__ == '__main__':
    def _on_tv_activated(index):
        print(tv.filePath(index))
        print(tv.fileInfo(index))

    app = QtWidgets.QApplication(sys.argv)
    tv = FileSystemTreeView()
    tv.set_context_menu(FileSystemContextMenu())
    tv.activated.connect(_on_tv_activated)
    path = os.path.join(os.getcwd(), 'test_dir')
    print('watching: %s' % path)
    tv.set_root_path(path)
    tv.show()
    app.exec_()

Interactive console

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
"""
Simple interactive process used to demonstrate the use of the
InteractiveConsole widget.
"""
import sys
print('running an interactive process')

if sys.version_info[0] == 2:
    value1 = raw_input('Enter value1: ')
    value2 = raw_input('Enter value2: ')
else:
    value1 = input('Enter value1: ')
    value2 = input('Enter value2: ')
print("Result: %d" % (int(value1) + int(value2)))
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
"""
This example show you how to use the InteractiveConsole. To make this example
complete and cross-platform, we created an interactive process which prints some text
and asks for user inputs. That way you can see that the console is actually interactive.
"""
import sys
from pyqode.qt import QtWidgets
from pyqode.core.widgets import InteractiveConsole
app = QtWidgets.QApplication(sys.argv)
console = InteractiveConsole()
console.start_process(sys.executable, ['interactive_process.py'])
console.show()
app.exec_()

Splittable tab widget (generic version)

 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
import os
import sys
from pyqode.qt import QtWidgets
from pyqode.core.widgets import GenericCodeEdit, InteractiveConsole
from pyqode.core.backend import server
from pyqode.core.widgets import SplittableTabWidget


class MyInteractiveConsole(InteractiveConsole):
    def __init__(self, parent=None):
        super(MyInteractiveConsole, self).__init__(parent)
        if sys.platform == 'win32':
            self.start_process('dir')
        else:
            self.start_process('ls', ['-s'])

    def split(self):
        return MyInteractiveConsole()


def print_last_tab_closed():
    print('last tab closed')


def print_current_tab(current):
    print('current tab changed: %r' % current)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    editor = GenericCodeEdit(None, server.__file__)
    editor.file.open(__file__)
    tab_widget = SplittableTabWidget()
    tab_widget.add_tab(editor, title=os.path.split(__file__)[1])
    tab_widget.setMinimumSize(800, 600)
    tab_widget.last_tab_closed.connect(print_last_tab_closed)
    tab_widget.current_changed.connect(print_current_tab)
    mc = MyInteractiveConsole()
    tab_widget.add_tab(mc, 'Console')
    tab_widget.show()
    app.exec_()

Splittable tab widget (CodeEdit specialization)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import os
import sys
from pyqode.qt import QtWidgets
from pyqode.core.widgets import SplittableCodeEditTabWidget


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    tab_widget = SplittableCodeEditTabWidget()
    tab_widget.setMinimumSize(800, 600)
    tab_widget.open_document(__file__)
    tab_widget.open_document(QtWidgets.__file__)
    tab_widget.create_new_document('My New Document', '.pyw')
    tab_widget.create_new_document('My New Document', '.pyw')
    tab_widget.show()
    app.exec_()