Esempio n. 1
0
 def is_end_of_function_definition(self, text, line_number):
     """Return True if text is the end of the function definition."""
     text_without_whitespace = "".join(text.split())
     if (text_without_whitespace.endswith("):")
             or text_without_whitespace.endswith("]:")
             or (text_without_whitespace.endswith(":")
                 and "->" in text_without_whitespace)):
         return True
     elif text_without_whitespace.endswith(":") and line_number > 1:
         complete_text = text_without_whitespace
         document = self.code_editor.document()
         cursor = QTextCursor(
             document.findBlockByNumber(line_number - 2))  # previous line
         for i in range(line_number - 2, -1, -1):
             txt = "".join(str(cursor.block().text()).split())
             if txt.endswith("\\") or is_in_scope_backward(complete_text):
                 if txt.endswith("\\"):
                     txt = txt[:-1]
                 complete_text = txt + complete_text
             else:
                 break
             if i != 0:
                 cursor.movePosition(QTextCursor.PreviousBlock)
         if is_start_of_function(complete_text):
             return (complete_text.endswith("):")
                     or complete_text.endswith("]:")
                     or (complete_text.endswith(":")
                         and "->" in complete_text))
         else:
             return False
     else:
         return False
Esempio n. 2
0
 def _get_line(self, editor_cursor, lines=1):
     """Return the line at cursor position."""
     try:
         cursor = QTextCursor(editor_cursor)
     except TypeError:
         print("ERROR: editor_cursor must be an instance of QTextCursor")
     else:
         cursor.movePosition(QTextCursor.StartOfLine)
         cursor.movePosition(QTextCursor.Down, QTextCursor.KeepAnchor,
                             n=lines)
         line = cursor.selectedText()
         return line
Esempio n. 3
0
    def draw_snippets(self):
        document = self.editor.document()
        for snippet_number in self.snippets_map:
            snippet_nodes = self.snippets_map[snippet_number]
            for node in snippet_nodes:
                cursor = QTextCursor(self.editor.textCursor())
                position = node.position
                if isinstance(node.position, tuple):
                    position = [list(node.position)]
                for path in position:
                    start_line, start_column = path[0]
                    end_line, end_column = path[-1]
                    if path[0] == path[-1]:
                        end_column += 1
                    start_block = document.findBlockByNumber(start_line)
                    cursor.setPosition(start_block.position())
                    cursor.movePosition(QTextCursor.StartOfBlock)
                    cursor.movePosition(
                        QTextCursor.NextCharacter, n=start_column)
                    end_block = document.findBlockByNumber(end_line)
                    cursor.setPosition(
                        end_block.position(), QTextCursor.KeepAnchor)
                    cursor.movePosition(
                        QTextCursor.StartOfBlock, mode=QTextCursor.KeepAnchor)
                    cursor.movePosition(
                        QTextCursor.NextCharacter, n=end_column,
                        mode=QTextCursor.KeepAnchor)

                    color = QColor(self.editor.comment_color)
                    self.editor.highlight_selection('code_snippets',
                                                    QTextCursor(cursor),
                                                    outline_color=color)
                    self.editor.update_extra_selections()
Esempio n. 4
0
    def search(self, txt):
        """Search regular expressions key inside document(from spyder_vim)."""
        editor = self.get_editor()
        cursor = QTextCursor(editor.document())
        cursor.movePosition(QTextCursor.Start)

        # Apply the option for search
        is_ignorecase = CONF.get(CONF_SECTION, 'ignorecase')
        is_smartcase = CONF.get(CONF_SECTION, 'smartcase')

        if is_ignorecase is True:
            option = None
            self.vim_status.search.ignorecase = True

            if is_smartcase and txt.lower() != txt:
                option = QTextDocument.FindCaseSensitively
                self.vim_status.search.ignorecase = False
        else:
            option = QTextDocument.FindCaseSensitively
            self.vim_status.search.ignorecase = False

        # Find key in document forward
        search_stack = []
        if option:
            cursor = editor.document().find(QRegularExpression(txt),
                                            options=option)
        else:
            cursor = editor.document().find(QRegularExpression(txt))

        back = self.vim_status.search.color_bg
        fore = self.vim_status.search.color_fg
        while not cursor.isNull():
            selection = QTextEdit.ExtraSelection()
            selection.format.setBackground(back)
            selection.format.setForeground(fore)
            selection.cursor = cursor
            search_stack.append(selection)
            if option:
                cursor = editor.document().find(QRegularExpression(txt),
                                                cursor,
                                                options=option)
            else:
                cursor = editor.document().find(QRegularExpression(txt),
                                                cursor)
        self.vim_status.cursor.set_extra_selections('vim_search',
                                                    [i for i in search_stack])
        editor.update_extra_selections()

        self.vim_status.search.selection_list = search_stack
        self.vim_status.search.txt_searched = txt
Esempio n. 5
0
    def get_function_definition_from_first_line(self):
        """Get func def when the cursor is located on the first def line."""
        document = self.code_editor.document()
        cursor = QTextCursor(
            document.findBlockByNumber(self.line_number_cursor - 1))

        func_text = ''
        func_indent = ''

        is_first_line = True
        line_number = cursor.blockNumber() + 1

        number_of_lines = self.code_editor.blockCount()
        remain_lines = number_of_lines - line_number + 1
        number_of_lines_of_function = 0

        for __ in range(min(remain_lines, 20)):
            cur_text = to_text_string(cursor.block().text()).rstrip()

            if is_first_line:
                if not is_start_of_function(cur_text):
                    return None

                func_indent = get_indent(cur_text)
                is_first_line = False
            else:
                cur_indent = get_indent(cur_text)
                if cur_indent <= func_indent and cur_text.strip() != '':
                    return None
                if is_start_of_function(cur_text):
                    return None
                if (cur_text.strip() == ''
                        and not is_in_scope_forward(func_text)):
                    return None

            if len(cur_text) > 0 and cur_text[-1] == '\\':
                cur_text = cur_text[:-1]

            func_text += cur_text
            number_of_lines_of_function += 1

            if self.is_end_of_function_definition(
                    cur_text, line_number + number_of_lines_of_function - 1):
                return func_text, number_of_lines_of_function

            cursor.movePosition(QTextCursor.NextBlock)

        return None
Esempio n. 6
0
    def get_function_definition_from_first_line(self):
        """Get func def when the cursor is located on the first def line."""
        document = self.code_editor.document()
        cursor = QTextCursor(
            document.findBlockByLineNumber(self.line_number_cursor - 1))

        func_text = ''
        func_indent = ''

        is_first_line = True
        line_number = cursor.blockNumber() + 1

        number_of_lines = self.code_editor.blockCount()
        remain_lines = number_of_lines - line_number + 1
        number_of_lines_of_function = 0

        for __ in range(min(remain_lines, 20)):
            cur_text = to_text_string(cursor.block().text()).rstrip()

            if is_first_line:
                if not is_start_of_function(cur_text):
                    return None

                func_indent = get_indent(cur_text)
                is_first_line = False
            else:
                cur_indent = get_indent(cur_text)
                if cur_indent <= func_indent:
                    return None
                if is_start_of_function(cur_text):
                    return None
                if cur_text.strip == '':
                    return None

            if cur_text[-1] == '\\':
                cur_text = cur_text[:-1]

            func_text += cur_text
            number_of_lines_of_function += 1

            if cur_text.endswith(':'):
                return func_text, number_of_lines_of_function

            cursor.movePosition(QTextCursor.NextBlock)

        return None
Esempio n. 7
0
    def set_editor_cursor(self, editor, cursor):
        """Set the cursor of an editor."""
        pos = cursor.position()
        anchor = cursor.anchor()

        new_cursor = QTextCursor()
        if pos == anchor:
            new_cursor.movePosition(pos)
        else:
            new_cursor.movePosition(anchor)
            new_cursor.movePosition(pos, QTextCursor.KeepAnchor)
        editor.setTextCursor(cursor)
Esempio n. 8
0
    def list_symbols(editor, block, character):
        """
        Retuns  a list of symbols found in the block text

        :param editor: code editor instance
        :param block: block to parse
        :param character: character to look for.
        """
        text = block.text()
        symbols = []
        cursor = QTextCursor(block)
        cursor.movePosition(cursor.StartOfBlock)
        pos = text.find(character, 0)
        cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos)

        while pos != -1:
            if not TextHelper(editor).is_comment_or_string(cursor):
                # skips symbols in string literal or comment
                info = ParenthesisInfo(pos, character)
                symbols.append(info)
            pos = text.find(character, pos + 1)
            cursor.movePosition(cursor.StartOfBlock)
            cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos)
        return symbols
Esempio n. 9
0
    def list_symbols(editor, block, character):
        """
        Retuns  a list of symbols found in the block text

        :param editor: code editor instance
        :param block: block to parse
        :param character: character to look for.
        """
        text = block.text()
        symbols = []
        cursor = QTextCursor(block)
        cursor.movePosition(cursor.StartOfBlock)
        pos = text.find(character, 0)
        cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos)

        while pos != -1:
            if not TextHelper(editor).is_comment_or_string(cursor):
                # skips symbols in string literal or comment
                info = ParenthesisInfo(pos, character)
                symbols.append(info)
            pos = text.find(character, pos + 1)
            cursor.movePosition(cursor.StartOfBlock)
            cursor.movePosition(cursor.Right, cursor.MoveAnchor, pos)
        return symbols
Esempio n. 10
0
class TextDecoration(QTextEdit.ExtraSelection):
    """
    Helper class to quickly create a text decoration.

    The text decoration is an utility class that adds a few utility methods to
    QTextEdit.ExtraSelection.

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

    Text decoration expose a **clicked** signal stored in a separate QObject:
        :attr:`pyqode.core.api.TextDecoration.Signals`

    .. code-block:: python

        deco = TextDecoration()
        deco.signals.clicked.connect(a_slot)

        def a_slot(decoration):
            print(decoration)  # spyder: test-skip
    """
    class Signals(QObject):
        """
        Holds the signals for a TextDecoration (since we cannot make it a
        QObject, we need to store its signals in an external QObject).
        """
        #: Signal emitted when a TextDecoration has been clicked.
        clicked = Signal(object)

    def __init__(self, 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):
        """
        Creates a text decoration.

        .. note:: start_pos/end_pos and start_line/end_line pairs let you
            easily specify the selected text. You should use one pair or the
            other or they will conflict between each others. If you don't
            specify any values, the selection will be based on the cursor.

        :param cursor_or_bloc_or_doc: Reference to a valid
            QTextCursor/QTextBlock/QTextDocument
        :param start_pos: Selection start position
        :param end_pos: Selection end position
        :param start_line: Selection start line.
        :param end_line: Selection end line.
        :param draw_order: The draw order of the selection, highest values will
            appear on top of the lowest values.
        :param tooltip: An optional tooltips that will be automatically shown
            when the mouse cursor hover the decoration.
        :param full_width: True to select the full line width.

        .. note:: Use the cursor selection if startPos and endPos are none.
        """
        super(TextDecoration, self).__init__()
        self.signals = self.Signals()
        self.draw_order = draw_order
        self.tooltip = tooltip
        self.cursor = QTextCursor(cursor_or_bloc_or_doc)
        if full_width:
            self.set_full_width(full_width)
        if start_pos is not None:
            self.cursor.setPosition(start_pos)
        if end_pos is not None:
            self.cursor.setPosition(end_pos, QTextCursor.KeepAnchor)
        if start_line is not None:
            self.cursor.movePosition(self.cursor.Start, self.cursor.MoveAnchor)
            self.cursor.movePosition(self.cursor.Down, self.cursor.MoveAnchor,
                                     start_line)
        if end_line is not None:
            self.cursor.movePosition(self.cursor.Down, self.cursor.KeepAnchor,
                                     end_line - start_line)

    def contains_cursor(self, cursor):
        """
        Checks if the textCursor is in the decoration.

        :param cursor: The text cursor to test
        :type cursor: QtGui.QTextCursor

        :returns: True if the cursor is over the selection
        """
        start = self.cursor.selectionStart()
        end = self.cursor.selectionEnd()
        if cursor.atBlockEnd():
            end -= 1
        return start <= cursor.position() <= end

    def set_as_bold(self):
        """Uses bold text."""
        self.format.setFontWeight(QFont.Bold)

    def set_foreground(self, color):
        """Sets the foreground color.
        :param color: Color
        :type color: QtGui.QColor
        """
        self.format.setForeground(color)

    def set_background(self, brush):
        """
        Sets the background brush.

        :param brush: Brush
        :type brush: QtGui.QBrush
        """
        self.format.setBackground(brush)

    def set_outline(self, color):
        """
        Uses an outline rectangle.

        :param color: Color of the outline rect
        :type color: QtGui.QColor
        """
        self.format.setProperty(QTextFormat.OutlinePen,
                                QPen(color))

    def select_line(self):
        """
        Select the entire line but starts at the first non whitespace character
        and stops at the non-whitespace character.
        :return:
        """
        self.cursor.movePosition(self.cursor.StartOfBlock)
        text = self.cursor.block().text()
        lindent = len(text) - len(text.lstrip())
        self.cursor.setPosition(self.cursor.block().position() + lindent)
        self.cursor.movePosition(self.cursor.EndOfBlock,
                                 self.cursor.KeepAnchor)

    def set_full_width(self, 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).

        :param flag: True to use full width selection.
        :type flag: bool

        :param clear: True to clear any previous selection. Default is True.
        :type clear: bool
        """
        if clear:
            self.cursor.clearSelection()
        self.format.setProperty(QTextFormat.FullWidthSelection, flag)

    def set_as_underlined(self, color=Qt.blue):
        """
        Underlines the text.

        :param color: underline color.
        """
        self.format.setUnderlineStyle(
            QTextCharFormat.SingleUnderline)
        self.format.setUnderlineColor(color)

    def set_as_spell_check(self, color=Qt.blue):
        """
        Underlines text as a spellcheck error.

        :param color: Underline color
        :type color: QtGui.QColor
        """
        self.format.setUnderlineStyle(
            QTextCharFormat.SpellCheckUnderline)
        self.format.setUnderlineColor(color)

    def set_as_error(self, color=Qt.red):
        """
        Highlights text as a syntax error.

        :param color: Underline color
        :type color: QtGui.QColor
        """
        self.format.setUnderlineStyle(
            QTextCharFormat.WaveUnderline)
        self.format.setUnderlineColor(color)

    def set_as_warning(self, color=QColor("orange")):
        """
        Highlights text as a syntax warning.

        :param color: Underline color
        :type color: QtGui.QColor
        """
        self.format.setUnderlineStyle(
            QTextCharFormat.WaveUnderline)
        self.format.setUnderlineColor(color)
Esempio n. 11
0
class TextDecoration(QTextEdit.ExtraSelection):
    """
    Helper class to quickly create a text decoration.

    The text decoration is an utility class that adds a few utility methods to
    QTextEdit.ExtraSelection.

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

    Text decoration expose a **clicked** signal stored in a separate QObject:
        :attr:`pyqode.core.api.TextDecoration.Signals`

    .. code-block:: python

        deco = TextDecoration()
        deco.signals.clicked.connect(a_slot)

        def a_slot(decoration):
            print(decoration)  # spyder: test-skip
    """
    class Signals(QObject):
        """
        Holds the signals for a TextDecoration (since we cannot make it a
        QObject, we need to store its signals in an external QObject).
        """
        #: Signal emitted when a TextDecoration has been clicked.
        clicked = Signal(object)

    def __init__(self,
                 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,
                 font=None,
                 kind=None):
        """
        Creates a text decoration.

        .. note:: start_pos/end_pos and start_line/end_line pairs let you
            easily specify the selected text. You should use one pair or the
            other or they will conflict between each others. If you don't
            specify any values, the selection will be based on the cursor.

        :param cursor_or_bloc_or_doc: Reference to a valid
            QTextCursor/QTextBlock/QTextDocument
        :param start_pos: Selection start position
        :param end_pos: Selection end position
        :param start_line: Selection start line.
        :param end_line: Selection end line.
        :param draw_order: The draw order of the selection, highest values will
            appear on top of the lowest values.
        :param tooltip: An optional tooltips that will be automatically shown
            when the mouse cursor hover the decoration.
        :param full_width: True to select the full line width.
        :param font: Decoration font.
        :param kind: Decoration kind, e.g. 'current_cell'.

        .. note:: Use the cursor selection if startPos and endPos are none.
        """
        super(TextDecoration, self).__init__()
        self.signals = self.Signals()
        self.draw_order = draw_order
        self.tooltip = tooltip
        self.cursor = QTextCursor(cursor_or_bloc_or_doc)
        self.kind = kind

        if full_width:
            self.set_full_width(full_width)
        if start_pos is not None:
            self.cursor.setPosition(start_pos)
        if end_pos is not None:
            self.cursor.setPosition(end_pos, QTextCursor.KeepAnchor)
        if start_line is not None:
            self.cursor.movePosition(self.cursor.Start, self.cursor.MoveAnchor)
            self.cursor.movePosition(self.cursor.Down, self.cursor.MoveAnchor,
                                     start_line)
        if end_line is not None:
            self.cursor.movePosition(self.cursor.Down, self.cursor.KeepAnchor,
                                     end_line - start_line)
        if font is not None:
            self.format.setFont(font)

    def contains_cursor(self, cursor):
        """
        Checks if the textCursor is in the decoration.

        :param cursor: The text cursor to test
        :type cursor: QtGui.QTextCursor

        :returns: True if the cursor is over the selection
        """
        start = self.cursor.selectionStart()
        end = self.cursor.selectionEnd()
        if cursor.atBlockEnd():
            end -= 1
        return start <= cursor.position() <= end

    def set_as_bold(self):
        """Uses bold text."""
        self.format.setFontWeight(QFont.Bold)

    def set_foreground(self, color):
        """Sets the foreground color.
        :param color: Color
        :type color: QtGui.QColor
        """
        self.format.setForeground(color)

    def set_background(self, brush):
        """
        Sets the background brush.

        :param brush: Brush
        :type brush: QtGui.QBrush
        """
        self.format.setBackground(brush)

    def set_outline(self, color):
        """
        Uses an outline rectangle.

        :param color: Color of the outline rect
        :type color: QtGui.QColor
        """
        self.format.setProperty(QTextFormat.OutlinePen, QPen(color))

    def select_line(self):
        """
        Select the entire line but starts at the first non whitespace character
        and stops at the non-whitespace character.
        :return:
        """
        self.cursor.movePosition(self.cursor.StartOfBlock)
        text = self.cursor.block().text()
        lindent = len(text) - len(text.lstrip())
        self.cursor.setPosition(self.cursor.block().position() + lindent)
        self.cursor.movePosition(self.cursor.EndOfBlock,
                                 self.cursor.KeepAnchor)

    def set_full_width(self, 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).

        :param flag: True to use full width selection.
        :type flag: bool

        :param clear: True to clear any previous selection. Default is True.
        :type clear: bool
        """
        if clear:
            self.cursor.clearSelection()
        self.format.setProperty(QTextFormat.FullWidthSelection, flag)

    def set_as_underlined(self, color=Qt.blue):
        """
        Underlines the text.

        :param color: underline color.
        """
        self.format.setUnderlineStyle(QTextCharFormat.SingleUnderline)
        self.format.setUnderlineColor(color)

    def set_as_spell_check(self, color=Qt.blue):
        """
        Underlines text as a spellcheck error.

        :param color: Underline color
        :type color: QtGui.QColor
        """
        self.format.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)
        self.format.setUnderlineColor(color)

    def set_as_error(self, color=Qt.red):
        """
        Highlights text as a syntax error.

        :param color: Underline color
        :type color: QtGui.QColor
        """
        self.format.setUnderlineStyle(QTextCharFormat.WaveUnderline)
        self.format.setUnderlineColor(color)

    def set_as_warning(self, color=QColor("orange")):
        """
        Highlights text as a syntax warning.

        :param color: Underline color
        :type color: QtGui.QColor
        """
        self.format.setUnderlineStyle(QTextCharFormat.WaveUnderline)
        self.format.setUnderlineColor(color)