File: cursortools.py

package info (click to toggle)
frescobaldi 3.0.0~git20161001.0.eec60717%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 19,792 kB
  • ctags: 5,843
  • sloc: python: 37,853; sh: 180; makefile: 69
file content (242 lines) | stat: -rw-r--r-- 7,395 bytes parent folder | download | duplicates (2)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# cursortools.py -- QTextCursor utility functions
#
# Copyright (c) 2008 - 2014 by Wilbert Berendsen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
# See http://www.gnu.org/licenses/ for more information.

"""
Functions manipulating QTextCursors and their selections.
"""


import contextlib
import operator

from PyQt5.QtGui import QTextBlock, QTextBlockUserData, QTextCursor


def block(cursor):
    """Returns the cursor's block.
    
    If the cursor has a selection, returns the block the selection starts in
    (regardless of the cursor's position()).
    
    """
    if cursor.hasSelection():
        return cursor.document().findBlock(cursor.selectionStart())
    return cursor.block()

    
def blocks(cursor):
    """Yields the block(s) containing the cursor or selection."""
    d = cursor.document()
    block = d.findBlock(cursor.selectionStart())
    end = d.findBlock(cursor.selectionEnd())
    while True:
        yield block
        if block == end:
            break
        block = block.next()
     

def contains(c1, c2):
    """Returns True if cursor2's selection falls inside cursor1's."""
    return (c1.selectionStart() <= c2.selectionStart()
            and c1.selectionEnd() >= c2.selectionEnd())


def forwards(block, until=QTextBlock()):
    """Yields the block and all following blocks.
    
    If until is a valid block, yields the blocks until the specified block.
    
    """
    if until.isValid():
        while block.isValid() and block <= until:
            yield block
            block = block.next()
    else:
        while block.isValid():
            yield block
            block = block.next()


def backwards(block, until=QTextBlock()):
    """Yields the block and all preceding blocks.
    
    If until is a valid block, yields the blocks until the specified block.
    
    """
    if until.isValid():
        while block.isValid() and block >= until:
            yield block
            block = block.previous()
    else:
        while block.isValid():
            yield block
            block = block.previous()

    
def all_blocks(document):
    """Yields all blocks of the document."""
    return forwards(document.firstBlock())


def partition(cursor):
    """Returns a three-tuple of strings (before, selection, after).
    
    'before' is the text before the cursor's position or selection start,
    'after' is the text after the cursor's position or selection end,
    'selection' is the selected text.
    
    before and after never contain a newline.
    
    """
    start = cursor.document().findBlock(cursor.selectionStart())
    end = cursor.document().findBlock(cursor.selectionEnd())
    before = start.text()[:cursor.selectionStart() - start.position()]
    selection = cursor.selection().toPlainText()
    after = end.text()[cursor.selectionEnd() - end.position():]
    return before, selection, after


@contextlib.contextmanager
def compress_undo(cursor, join_previous = False):
    """Returns a context manager to perform operations on cursor as a single undo-item."""
    cursor.joinPreviousEditBlock() if join_previous else cursor.beginEditBlock()
    try:
        yield
    finally:
        cursor.endEditBlock()


@contextlib.contextmanager
def keep_selection(cursor, edit=None):
    """Performs operations inside the selection and restore the selection afterwards.
    
    If edit is given, call setTextCursor(cursor) on the Q(Plain)TextEdit afterwards.
    
    """
    start, end, pos = cursor.selectionStart(), cursor.selectionEnd(), cursor.position()
    cur2 = QTextCursor(cursor)
    cur2.setPosition(end)
    
    try:
        yield
    finally:
        if pos == start:
            cursor.setPosition(cur2.position())
            cursor.setPosition(start, QTextCursor.KeepAnchor)
        else:
            cursor.setPosition(start)
            cursor.setPosition(cur2.position(), QTextCursor.KeepAnchor)
        if edit:
            edit.setTextCursor(cursor)


def strip_selection(cursor, chars=None):
    """Adjusts the selection of the cursor just like Python's strip().
    
    If there is no selection or the selection would vanish completely,
    nothing is done.
    
    """
    if not cursor.hasSelection():
        return
    text = cursor.selection().toPlainText()
    if not text.strip(chars):
        return
    l = len(text) - len(text.lstrip(chars))
    r = len(text) - len(text.rstrip(chars))
    s = cursor.selectionStart() + l
    e = cursor.selectionEnd() - r
    if cursor.position() < cursor.anchor():
        s, e = e, s
    cursor.setPosition(s)
    cursor.setPosition(e, QTextCursor.KeepAnchor)


def strip_indent(cursor):
    """Moves the cursor in its block to the first non-space character."""
    text = cursor.block().text()
    pos = len(text) - len(text.lstrip())
    cursor.setPosition(cursor.block().position() + pos)


def insert_select(cursor, text):
    """Inserts text and then selects all inserted text in the cursor."""
    pos = cursor.selectionStart()
    cursor.insertText(text)
    new = cursor.position()
    cursor.setPosition(pos)
    cursor.setPosition(new, QTextCursor.KeepAnchor)


def isblank(block):
    """Returns True if the block is an empty or blank line."""
    text = block.text()
    return not text or text.isspace()


def isblank_before(cursor):
    """Returns True if there's no text on the current line before the cursor."""
    if cursor.atBlockStart():
        return True
    text = cursor.block().text()[:cursor.position() - cursor.block().position()]
    return not text or text.isspace()


def isblank_after(cursor):
    """Returns True if there's no text on the current line after the cursor."""
    if cursor.atBlockEnd():
        return True
    text = cursor.block().text()[cursor.position() - cursor.block().position():]
    return not text or text.isspace()


def next_blank(block):
    """Returns the next block that is the first block of one or more blank blocks."""
    bb = forwards(block)
    for b in bb:
        if not isblank(b):
            for b in bb:
                if isblank(b):
                    return b


def previous_blank(block):
    """Returns the previous block that is the first block of one or more blank blocks."""
    bb = backwards(block)
    for b in bb:
        if not isblank(b):
            for b in bb:
                if isblank(b):
                    for b in bb:
                        if not isblank(b):
                            b = b.next()
                            break
                    return b


def data(block):
    """Get the block's QTextBlockUserData, creating it if necessary.""" 
    data = block.userData()
    if not data:
        data = QTextBlockUserData()
        block.setUserData(data)
    return data