pyqode.core.api

This package contains the base classes of the API:

  • CodeEdit
  • Mode
  • Panel
  • Manager
  • TextDecoration
  • SyntaxHighlighter
  • TextBlockUserData
class pyqode.core.api.CodeEdit(parent=None, create_default_actions=True)

Bases: pyqode.core.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 the more high level 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_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.

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)

Show a tool tip at the specified position

Parameters:
  • pos – Tooltip position
  • tooltip – Tooltip text
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 font size.

foreground

The editor foreground color.

min_indent_column

Minimum indent colum.

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

Automtically 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 (already 1 based), 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.

word_separators

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

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.Manager(editor)

Bases: builtins.object

A manager manages a specific aspect of CodeEdit:
  • 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.core.qt.QtWidgets.QWidget, pyqode.core.api.mode.Mode

Base class for editor panels.

A panel is a mode and a QWidget.

Note

A disabled panel will be hidden automatically.

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.on_state_changed(state)

Shows/Hides the Panel

Warning

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

Parameters:state (bool) – True = enabled, False = disabled
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)

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

Abstract Base class for syntax highlighter modes.

It fills up the document with our custom user data, setup the parenthesis infos and run the FoldDetector on every text block. It does not do any syntax highlighting, this task is left to the sublasses such as pyqode.core.modes.PygmentsSyntaxHighlighter.

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

signals:
  • pyqode.core.api.SyntaxHighlighter.block_highlight_started
  • pyqode.core.api.SyntaxHighlighter.block_highlight_finished

Warning

You should always inherit from this class to create a new syntax highlighter mode.

Never inherit directly from QSyntaxHighlighter.

class ParenthesisInfo(pos, char)

Bases: builtins.object

Stores information about a parenthesis in a line of code.

SyntaxHighlighter.highlightBlock(text)

Highlights a block of text.

SyntaxHighlighter.highlight_block(text)

Abstract method. Override this to apply syntax highlighting.

Parameters:text – Line of text to highlight.
SyntaxHighlighter.set_mime_type(mime_type)

Sets the associated mime type and update the internal lexer

class pyqode.core.api.TextBlockUserData

Bases: pyqode.core.qt.QtGui.QTextBlockUserData

Custom text block data. pyQode use text block data for many purposes:
  • folding detection
  • symbols matching
  • mar

You can also add your own data.

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)

Bases: pyqode.core.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
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.core.qt.QtGui.QColor object at 0x7f6013f76c50>)

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)

Sets full width selection.

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 (1 based) and the column number (0 based).

Returns:tuple(line, column)
get_right_character()

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

get_right_word()

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 (1 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.
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 (1 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

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=1, 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 (1 based)
  • end – End line number (1 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.TextStyle(style=None)

Bases: builtins.object

Helper class to define a text format. This class has methods to set the text style from a string and to easily be created from a string, making serialisation extremely easy.

A text style is made up of a text color and a series of text attributes:

  • bold/nbold
  • italic/nitalic
  • underlined/nunderlined.

Example of usage:

style = TextStyle('#808000 nbold nitalic nunderlined')
print(style)  #should print '#808000 nbold nitalic nunderlined'