pyqode.core.api

This package contains the bases classes of pyqode and some utility functions.

class pyqode.core.api.CodeEdit(parent=None, create_default_actions=True)

Bases: pyqode.qt.QtWidgets.QPlainTextEdit

Base class for any pyQode source code editor widget.

Extends QPlainTextEdit by adding an extension system ( modes and panels) and by adding a series of additional signal and methods.

To interact with the editor content, you may use the Qt Text API ( QTextCursor, ...) or use high level API functions defined in pyqode.core.api.TextHelper

Note

setPlainText has been overridden to force you to define a mime type and an encoding.

actions()

Returns the list of actions/sepqrators of the context menu.

add_action(action)

Adds an action to the editor’s context menu.

Parameters:action – QtWidgets.QAction
add_menu(menu)

Adds a menu to the editor context menu.

Menu are put at the bottom of the context menu.

Note

to add a menu in the middle of the context menu, you can always add its menuAction().

Parameters:menu – menu to add
add_separator()

Adds a sepqrator to the editor’s context menu.

Returns:The sepator that has been added.
Return type:QtWidgets.QAction
delete()

Deletes the selected text

duplicate_line()

Duplicates the line under the cursor. If multiple lines are selected, only the last one is duplicated.

focusInEvent(event)

Overrides focusInEvent to emits the focused_in signal

Parameters:event – QFocusEvent
focusOutEvent(event)

Saves content if save_on_focus_out is True.

get_context_menu()

Gets the editor context menu.

Returns:QMenu
goto_line()

Shows goto line dialog and go to the selected line.

indent()

Indents the text cursor or the selection.

Emits the pyqode.core.api.CodeEdit.indent_requested signal, the pyqode.core.modes.IndenterMode will perform the actual indentation.

keyPressEvent(event)

Overrides the keyPressEvent to emit the key_pressed signal.

Also takes care of indenting and handling smarter home key.

Parameters:event – QKeyEvent
keyReleaseEvent(event)

Overrides keyReleaseEvent to emit the key_released signal.

Parameters:event – QKeyEvent
mouseMoveEvent(event)

Overrides mouseMovedEvent to display any decoration tooltip and emits the mouse_moved event.

mousePressEvent(event)

Overrides mousePressEvent to emits mouse_pressed signal

Parameters:event – QMouseEvent
mouseReleaseEvent(event)

Emits mouse_released signal.

Parameters:event – QMouseEvent
paintEvent(e)

Overrides paint event to update the list of visible blocks and emit the painted event.

Parameters:e – paint event
rehighlight()

Calls rehighlight on the installed syntax highlighter mode.

remove_action(action)

Removes an action/separator from the editor’s context menu.

Parameters:action – Action/seprator to remove.
reset_zoom()

Resets the zoom value.

resizeEvent(e)

Overrides resize event to resize the editor’s panels.

Parameters:e – resize event
setPlainText(txt, mime_type, encoding)

Extends setPlainText to force the user to set an encoding and a mime type.

Emits the new_text_set signal.

Parameters:
  • txt – The new text to set.
  • mime_type – Associated mimetype. Setting the mime will update the pygments lexer.
  • encoding – text encoding
set_mouse_cursor(cursor)

Changes the viewport’s cursor

Parameters:cursor (QtWidgets.QCursor) – the mouse cursor to set.
showEvent(event)

Overrides showEvent to update the viewport margins

show_tooltip(pos, tooltip, _sender_deco=None)

Show a tool tip at the specified position

Parameters:
  • pos – Tooltip position
  • tooltip – Tooltip text
  • _sender_deco – TextDecoration which is the sender of the show tooltip request. (for internal use only).
un_indent()

Un-indents the text cursor or the selection.

Emits the pyqode.core.api.CodeEdit.unindent_requested signal, the pyqode.core.modes.IndenterMode will perform the actual un-indentation.

wheelEvent(event)

Emits the mouse_wheel_activated signal.

Parameters:event – QMouseEvent
zoom_in(increment=1)

Zooms in the editor.

The effect is achieved by increasing the editor font size by the increment value.

Panels that needs to be resized depending on the font size need to implement onStyleChanged.

zoom_out(increment=1)

Zooms out the editor.

The effect is achieved by decreasing the editor font size by the increment value.

Panels that needs to be resized depending on the font size need to implement onStyleChanged and trigger an update.

backend

BackendManager used to control the backend process

background

The editor background color.

decorations

TextDecorationManager: manage the list of text decorations

dirty

Gets/sets the dirty flag.

Type:bool
file

FileManager used to open/save file on the editor

font_name

The editor font family name.

font_size

The editor current font size.

foreground

The editor foreground color.

min_indent_column

Minimum indent column.

Some languages such as cobol starts coding at column 7.

modes

ModesManager used to append modes to the editor

panels

PanelsManager used to append panels to the editor

save_on_focus_out

Automatically saves editor content on focus out.

Default is False.

selection_background

The editor selection’s background color.

selection_foreground

The editor selection’s foreground color.

show_whitespaces

Shows/Hides white spaces highlighting.

tab_length

Tab length, number of spaces.

use_spaces_instead_of_tabs

Use spaces instead of tabulations. Default is True.

visible_blocks

Returns the list of visible blocks.

Each element in the list is a tuple made up of the line top position, the line number and the QTextBlock itself.

Returns:A list of tuple(top_position, line_number, block)
Return type:List of tuple(int, int, QtWidgets.QTextBlock)
whitespaces_foreground

The editor white spaces’ foreground color. White spaces are highlighted by the syntax highlighter. You should call rehighlight to update their color. This is not done automatically to prevent multiple, useless call to rehighlight which can take some time on big files.

word_separators

The list of word separators used by the code completion mode and the word clicked mode.

zoom_level

Gets/Sets the editor zoom level.

The zoom level is a value that is added to the current editor font size. Negative values are used to zoom out the editor, positive values are used to zoom in the editor.

class pyqode.core.api.ColorScheme(style)

Bases: builtins.object

Translates a pygments style into a dictionary of colors assoociated with a style key.

See pyqode.core.api.syntax_highligter.COLOR_SCHEM_KEYS for the available keys.

class pyqode.core.api.DelayJobRunner(delay=500)

Bases: builtins.object

Utility class for running job after a certain delay. If a new request is made during this delay, the previous request is dropped and the timer is restarted for the new request.

We use this to implement a cooldown effect that prevents jobs from being executed while the IDE is not idle.

A job is a simple callable.

cancel_requests()

Cancels pending requests.

request_job(job, *args, **kwargs)

Request a job execution. The job will be executed after the delay specified in the DelayJobRunner contructor elapsed if no other job is requested until then.

Parameters:
  • job (callable) – job.
  • force (bool) – Specify if we must force the job execution by stopping the job that is currently running (if any).
  • args – args
  • kwargs – kwargs
class pyqode.core.api.FoldDetector

Bases: builtins.object

Base class for fold detectors.

A fold detector takes care of detecting the text blocks fold levels that are used by the FoldingPanel to render the document outline.

To use a FoldDetector, simply set it on a syntax_highlighter:

editor.syntax_highlighter.fold_detector = my_fold_detector
detect_fold_level(prev_block, block)

Detects the block fold level.

The default implementation is based on the block indentation.

Note

Blocks fold level must be contiguous, there cannot be a difference greater than 1 between two successive block fold levels.

Parameters:
  • prev_block – first previous non-blank block or None if this is the first line of the document
  • block – The block to process.
Returns:

Fold level

process_block(current_block, previous_block, text)

Processes a block and sets up its folding infos.

This method call detect_fold_level and handles most of the tricky corner cases so that all you have to do is focus on getting the proper fold level foreach meaningfull block, skipping the blank ones

Parameters:
  • current_block – current block to process
  • previous_block – previous block
  • text – current block text
class pyqode.core.api.IndentFoldDetector

Bases: pyqode.core.api.folding.FoldDetector

Simple fold detector based on the line indentation level

class pyqode.core.api.FoldScope(block)

Bases: builtins.object

Utility class for manipulating foldable code scope (fold/unfold, get range, child and parent scopes and so on).

A scope is built from a fold trigger (QTextBlock).

blocks(ignore_blank_lines=True)

This generator generates the list of blocks directly under the fold region. This list does not contain blocks from child regions.

child_regions()

This generator generates the list of direct child regions.

fold()

Folds the region.

Parameters:recursively – Fold all sub regions.
get_range(ignore_blank_lines=True)

Get the fold region range (start and end line).

Note

Start line do no encompass the trigger line.

parent()

Return the parent scope.

Returns:FoldScope or None
text(max_lines=9223372036854775807)

Get the scope text, with a possible maximum number of lines.

Returns:str
unfold()

Unfolds the region.

collapsed

Whether the scope is collasped.

scope_level

Returns the fold level of the first block of the foldable scope ( just after the trigger)

Returns:
trigger_level

Returns the fold level of the block trigger :return:

class pyqode.core.api.Manager(editor)

Bases: builtins.object

A manager manages a specific aspect of a CodeEdit instance:
  • backend management (start/stop server, request work,...)
  • modes management
  • panels management and drawing
  • file manager

Managers are typically created internally when you create a CodeEdit. You interact with them later, e.g. when you start the backend process, install a mode or a panel:

editor = CodeEdit()

# use the backend manager to start the backend server
editor.backend.start(...)
editor.backend.send_request(...)

# use the panels controller to install a panel
editor.panels.install(MyPanel(), MyPanel.Position.Right)
my_panel = editor.panels.get(MyPanel)

# and so on
editor

Return a reference to the parent code edit widget.

class pyqode.core.api.Mode

Bases: builtins.object

Base class for editor extensions. An extension is a “thing” that can be installed on an editor to add new behaviours or to modify the appearance.

A mode is added to an editor by using the ModesManager/PanelsManager:

  • pyqode.core.api.CodeEdit.modes.append() or
  • pyqode.core.api.CodeEdit.panels.append()

Subclasses may/should override the following methods:

The mode will be identified by its class name, this means that there cannot be two modes of the same type on a editor!

on_install(editor)

Installs the extension on the editor.

Parameters:editor (pyqode.core.api.code_edit.CodeEdit) – editor widget instance

Note

This method is called by editor when you install a Mode. You should never call it yourself, even in a subclasss.

Warning

Don’t forget to call super when subclassing

on_state_changed(state)

Called when the enable state changed.

This method does not do anything, you may override it if you need to connect/disconnect to the editor’s signals (connect when state is true and disconnect when it is false).

Parameters:state (bool) – True = enabled, False = disabled
on_uninstall()

Uninstall the mode

editor

Provides easy access to the parent editor widget (weakref)

READ ONLY

Return type:pyqode.core.api.code_edit.CodeEdit
enabled

Tell if the mode is enabled, pyqode.core.api.Mode.on_state_changed() is called when the state changed.

Type:bool
class pyqode.core.api.Panel

Bases: pyqode.qt.QtWidgets.QWidget, pyqode.core.api.mode.Mode

Base class for editor panels.

A panel is a mode and a QWidget.

Note

Use enabled to disable panel actions and setVisible to change the visiblity of the panel.

class Position

Bases: builtins.object

Enumerates the possible panel positions

classmethod iterable()

Returns possible positions as an iterable (list)

Panel.on_install(editor)

Extends pyqode.core.api.Mode.on_install() method to set the editor instance as the parent widget.

Warning

Don’t forget to call super if you override this method!

Parameters:editor (pyqode.core.api.CodeEdit) – editor instance
Panel.paintEvent(event)

Fills the panel background.

Panel.setVisible(visible)

Shows/Hides the panel

Automatically call CodeEdit.refresh_panels.

Panel.scrollable

A scrollable panel will follow the editor’s scroll-bars. Left and right panels follow the vertical scrollbar. Top and bottom panels follow the horizontal scrollbar.

Type:bool
class pyqode.core.api.SyntaxHighlighter(parent, color_scheme=None)

Bases: pyqode.qt.QtGui.QSyntaxHighlighter, pyqode.core.api.mode.Mode

Abstract base class for syntax highlighter modes.

It fills up the document with our custom block data (fold levels, triggers,...).

It does not do any syntax highlighting, this task is left to sublasses such as pyqode.core.modes.PygmentsSyntaxHighlighter.

Subclasses must override the pyqode.core.api.SyntaxHighlighter.highlight_block() method to apply custom highlighting.

Note

Since version 2.1 and for performance reasons, we store all our data in the block user state as a bit-mask. You should always use pyqode.core.api.TextBlockHelper to retrieve or modify those data.

highlightBlock(text)

Highlights a block of text.

highlight_block(text, block)

Abstract method. Override this to apply syntax highlighting.

Parameters:
  • text – Line of text to highlight.
  • block – current block
rehighlight()

Rehighlight the entire document, may be slow.

class pyqode.core.api.TextBlockUserData

Bases: pyqode.qt.QtGui.QTextBlockUserData

Custom text block user data, mainly used to store block checker messages and markers.

class pyqode.core.api.TextDecoration(cursor_or_bloc_or_doc, start_pos=None, end_pos=None, start_line=None, end_line=None, draw_order=0, tooltip=None, full_width=False)

Bases: pyqode.qt.QtWidgets.Foo

Helper class to quickly create a text decoration. The text decoration is an utility class that adds a few utility methods over Qt’s ExtraSelection.

In addition to the helper methods, a tooltip can be added to a decoration. (useful for errors marks and so on...)

Text decoration expose 1 clicked signal stored in a separate QObject:
pyqode.core.api.TextDecoration.signals
deco = TextDecoration()
deco.signals.clicked.connect(a_slot)

def a_slot(decoration):
    print(decoration)
contains_cursor(cursor)

Checks if the textCursor is in the decoration

Parameters:cursor (QtGui.QTextCursor) – The text cursor to test
select_line()

Select the entire line but starts at the first non whitespace character and stops at the non-whitespace character. :return:

set_as_bold()

Uses bold text

set_as_error(color=None)

Highlights text as a syntax error.

Parameters:color (QtGui.QColor) – Underline color
set_as_spell_check(color=None)

Underlines text as a spellcheck error.

Parameters:color (QtGui.QColor) – Underline color
set_as_underlined(color=None)

Underlines the text

set_as_warning(color=<pyqode.qt.QtGui.QColor object at 0x7fc32ed4dc50>)

Highlights text as a syntax warning

Parameters:color (QtGui.QColor) – Underline color
set_background(brush)

Sets the background brush.

Parameters:brush (QtGui.QBrush) – Brush
set_foreground(color)

Sets the foreground color. :param color: Color :type color: QtGui.QColor

set_full_width(flag=True, clear=True)

Enables FullWidthSelection (the selection does not stops at after the character instead it goes up to the right side of the widget).

Parameters:
  • flag (bool) – True to use full width selection.
  • clear (bool) – True to clear any previous selection. Default is True.
set_outline(color)

Uses an outline rectangle.

Parameters:color (QtGui.QColor) – Color of the outline rect
class pyqode.core.api.TextHelper(editor)

Bases: builtins.object

Text helper helps you manipulate the content of CodeEdit and extends the Qt text api for an easier usage.

clean_document()

Removes trailing whitespaces and ensure one single blank line at the end of the QTextDocument.

clear_selection()

Clears text cursor selection

current_column_nbr()

Returns the text cursor’s column number.

Returns:Column number
current_line_nbr()

Returns the text cursor’s line number.

Returns:Line number
current_line_text()

Returns the text of the current line.

Returns:Text of the current line
cursor_position()

Returns the QTextCursor position. The position is a tuple made up of the line number (0 based) and the column number (0 based).

Returns:tuple(line, column)
get_right_character(cursor=None)

Gets the character that is on the right of the text cursor.

get_right_word(cursor=None)

Gets the character on the right of the text cursor.

Returns:The word that is on the right of the text cursor.
goto_line(line, column=0, move=True)

Moves the text cursor to the specified line (and column).

Parameters:
  • line – Number of the line to go to (0 based)
  • column – Optional column number. Default start of line.
  • move – True to move the cursor. False will return the cursor without setting it on the editor.
Returns:

The new text cursor

Return type:

QtGui.QTextCursor

insert_text(text, keep_position=True)

Inserts text at the cursor position.

Parameters:
  • text – text to insert
  • keep_position – Flag that specifies if the cursor position must be kept. Pass False for a regular insert (the cursor will be at the end of the inserted text).
line_count()

Returns the line count of the specified editor

Returns:number of lines in the document.
line_indent(line_nbr=None)

Returns the indent level of the specified line

Parameters:line_nbr – Number of the line to get indentation (1 base). Pass None to use the current line number. Note that you can also pass a QTextBlock instance instead of an int.
Returns:Number of spaces that makes the indentation level of the current line
line_nbr_from_position(y_pos)

Returns the line number from the y_pos

Parameters:y_pos – Y pos in the editor
Returns:Line number (0 based)
line_pos_from_number(line_number)

Computes line position on Y-Axis (at the center of the line) from line number.

Parameters:line_number – The line number for which we want to know the position in pixels.
Returns:The center position of the line.
line_text(line_nbr)

Gets the text of the specified line

Parameters:line_nbr – The line number of the text to get
Returns:Entire line’s text
Return type:str
mark_whole_doc_dirty()

Marks the whole document as dirty to force a full refresh. SLOW

match_select(ignored_symbols=None)

Selects text between matching quotes or parentheses.

move_right(keep_anchor=False, nb_chars=1)

Moves the cursor on the right.

Parameters:
  • keep_anchor – True to keep anchor (to select text) or False to move the anchor (no selection)
  • nb_chars – Number of characters to move.
remove_last_line()

Removes the last line of the document.

search_text(text_cursor, search_txt, search_flags)

Searches a text in a text document.

Parameters:
  • text_cursor – Current text cursor
  • search_txt – Text to search
  • search_flags – QTextDocument.FindFlags
Returns:

the list of occurrences, the current occurrence index

Return type:

tuple([], int)

select_lines(start=0, end=-1, apply_selection=True)

Selects entire lines between start and end line numbers.

This functions apply the selection and returns the text cursor that contains the selection.

Optionally it is possible to prevent the selection from being applied on the code editor widget by setting apply_selection to False.

Parameters:
  • start – Start line number (0 based)
  • end – End line number (0 based). Use -1 to select up to the end of the document
  • apply_selection – True to apply the selection before returning the QTextCursor.
Returns:

A QTextCursor that holds the requested selection

selected_text()

Returns the selected text.

selected_text_to_lower()

Replaces the selected text by its lower version

Parameters:editor – CodeEdit instance
selected_text_to_upper()

Replaces the selected text by its upper version

selection_range()

Returns the selected lines boundaries (start line, end line)

Returns:tuple(int, int)
set_line_text(line_nbr, new_text)

Replace an entire line with new_text.

Parameters:
  • editor – editor instance
  • new_text – The replacement text.
word_under_cursor(select_whole_word=False, text_cursor=None)

Gets the word under cursor using the separators defined by pyqode.core.api.CodeEdit.word_separators.

Parameters:
  • select_whole_word – If set to true the whole word is selected, else the selection stops at the cursor position.
  • text_cursor – Optional custom text cursor (e.g. from a QTextDocument clone)
Returns:

The QTextCursor that contains the selected word.

word_under_mouse_cursor()

Selects the word under the mouse cursor.

Returns:A QTextCursor with the word under mouse cursor selected.
class pyqode.core.api.TextBlockHelper

Bases: builtins.object

Helps retrieving the various part of the user state bitmask.

This helper should be used to replace calls to QTextBlock.setUserState/QTextBlock.getUserState as well as QSyntaxHighlighter.setCurrentBlockState/ QSyntaxHighlighter.currentBlockState and QSyntaxHighlighter.previousBlockState.

The bitmask is made up of the following fields:

  • bit0 -> bit26: User state (for syntax highlighting)
  • bit26: fold trigger state
  • bit27-bit29: fold level (8 level max)
  • bit30: fold trigger flag
static get_fold_lvl(block)

Gets the block fold level

Parameters:block – block to access.
Returns:The block fold level
static get_fold_trigger_state(block)

Gets the fold trigger state. :return: False for an open trigger, True for for closed trigger

static get_state(block)

Gets the user state, generally used for syntax highlighting. :param block: block to access :return: The block state

static is_fold_trigger(block)

Checks if the block is a fold trigger.

Parameters:block – block to check
Returns:True if the block is a fold trigger (represented as a node in the fold panel)
static set_fold_lvl(block, val)

Sets the block fold level.

Parameters:
  • block – block to modify
  • val – The new fold level [0-7]
static set_fold_trigger_state(block, val)

Sets the fold trigger state.

Parameters:
  • block – The block to modify
  • val – The new trigger state (False = open, True = closed)
static set_state(block, state)

Sets the user state, generally used for syntax highlighting.

Parameters:
  • block – block to modify
  • state – new state value.
Returns:

pyqode.core.api.get_block_symbol_data(editor, block)

Gets the list of ParenthesisInfo for specific text block.