-
Notifications
You must be signed in to change notification settings - Fork 2
/
textbuf.py
100 lines (75 loc) · 2.93 KB
/
textbuf.py
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
# coding: utf-8
from difflib import SequenceMatcher
def generate_edit_keys(a, b, position=None):
if position is None:
position = len(a)
length = 0
edits = []
for tag, i1, i2, j1, j2 in SequenceMatcher(None, a, b).get_opcodes():
if tag == 'equal':
continue
if not edits and i1 < position:
edits.append(('key', 'Left', position - i1))
if tag in {'delete', 'replace'}:
edits.append(('key', 'Delete', i2 - i1))
length -= i2 - i1
if tag in {'insert', 'replace'}:
edits.append(b[j1:j2])
length += j2 - j1
return edits, length
class Text(object):
def __init__(self, text='', position=None, length=0):
self.text = text
self.position = position if position is not None else len(text)
self.selection_length = length
self.selection = text[self.position:self.position + length]
def _replace_selection(self, text):
prefix, postfix = self.text[:self.position], \
self.text[self.position + self.selection_length:]
return ''.join((prefix, text, postfix))
def expand_selection(self, position, length):
delta = length - self.selection_length
if delta < 0:
diff = [('key', 's-Left', abs(delta))]
else:
diff = [('key', 's-Right', delta)]
return Text(self.text, position, length), diff
def set_selection(self, position, length):
diff = []
if self.selection_length:
if self.position == position:
return self.expand_selection(position, length)
else:
diff.append(('key', 'Left', 1))
delta = self.position - position
if delta < 0:
diff.append(('key', 'Right', abs(delta)))
elif delta > 0:
diff.append(('key', 'Left', delta))
if length:
diff.append(('key', 's-Right', length))
return Text(self.text, position, length), diff
def set_text(self, text):
if self.selection:
if text:
i = self.position
length = self.selection_length + len(text) - len(self.text)
text = text[i:i + length]
diff = text
if not text:
text = ''
diff = ('key', 'BackSpace', 1)
length = 0
new_text = self._replace_selection(text)
return Text(new_text, position=self.position + length), [diff]
else:
edits, length = generate_edit_keys(self.text, text, self.position)
position = self.position + length
return Text(text, position=position), edits
def __repr__(self):
return u'<{text}, [{position}:{length}]->"{selected_text}">'.format(
text=self.text,
position=self.position,
length=self.selection_length,
selected_text=self.selection,
)