File: backspace.py

package info (click to toggle)
turing 0.11-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,340 kB
  • sloc: python: 106,582; xml: 101; makefile: 53; sh: 29
file content (51 lines) | stat: -rw-r--r-- 1,897 bytes parent folder | download | duplicates (5)
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
"""
This module contains the smart backspace mode
"""
from pyqode.qt import QtCore, QtGui
from pyqode.core.api import Mode


class SmartBackSpaceMode(Mode):
    """ Improves backspace behaviour.

    When you press backspace and there are spaces on the left of the cursor,
    those spaces will be deleted (at most tab_len spaces).

    Basically this turns backspace into Shitf+Tab
    """
    def on_state_changed(self, state):
        if state:
            self.editor.key_pressed.connect(self._on_key_pressed)
        else:
            self.editor.key_pressed.disconnect(self._on_key_pressed)

    def _on_key_pressed(self, event):
        no_modifiers = int(event.modifiers()) == QtCore.Qt.NoModifier
        if event.key() == QtCore.Qt.Key_Backspace and no_modifiers:
            if self.editor.textCursor().atBlockStart():
                return
            tab_len = self.editor.tab_length
            tab_len = self.editor.textCursor().positionInBlock() % tab_len
            if tab_len == 0:
                tab_len = self.editor.tab_length
            # count the number of spaces deletable, stop at tab len
            spaces = 0
            cursor = QtGui.QTextCursor(self.editor.textCursor())
            while spaces < tab_len or cursor.atBlockStart():
                pos = cursor.position()
                cursor.movePosition(cursor.Left, cursor.KeepAnchor)
                char = cursor.selectedText()
                if char == " ":
                    spaces += 1
                else:
                    break
                cursor.setPosition(pos - 1)
            cursor = self.editor.textCursor()
            if spaces == 0:
                return
            cursor.beginEditBlock()
            for _ in range(spaces):
                cursor.deletePreviousChar()
            cursor.endEditBlock()
            self.editor.setTextCursor(cursor)
            event.accept()