-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstyled_text_ctrl.py
403 lines (332 loc) · 14.1 KB
/
styled_text_ctrl.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
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import os.path
import string
import random
import re
import wx
import wx.stc
from contextlib import contextmanager
from find_replace_dialog import FindReplaceDetails, FindReplaceDialog
from go_to_line_dialog import GoToLineDialog
from menu_defs import edit_menu
from syntax import syntax_from_filename, syntax_plain
from themes import default_theme
from util import clean_text, clean_strip_text, unique, split_seperators_outside_quotes, get_clipboard_text, natural_order_key
MARKER_FIND = 0
MARKER_ERROR = 1
default_styles = [
(wx.stc.STC_STYLE_DEFAULT, ""),
(wx.stc.STC_STYLE_LINENUMBER, "back:#C0C0C0"),
(wx.stc.STC_STYLE_BRACELIGHT, "fore:#000000,back:#CCCCCC,bold"),
(wx.stc.STC_STYLE_BRACEBAD, "fore:#000000,back:#FFCCCC,bold"),
(wx.stc.STC_STYLE_CONTROLCHAR, ""),
(wx.stc.STC_STYLE_INDENTGUIDE, "fore:#CCCCCC"),
]
brace_chars = "[]{}()"
class StyledTextCtrl(wx.stc.StyledTextCtrl):
name = ""
def __init__(self, parent, env):
wx.stc.StyledTextCtrl.__init__(self, parent, pos=(-1, -1), size=(1, 1), style=wx.BORDER_NONE)
self.env = env
self.UsePopUp(False)
self.SetSyntax(syntax_plain)
self.SetScrollWidth(1)
#self.SetScrollWidthTracking(True)
self.Bind(wx.EVT_KEY_DOWN, self.__OnKeyDown)
self.Bind(wx.EVT_CONTEXT_MENU, self.__OnContextMenu)
self.Bind(wx.stc.EVT_STC_CHANGE, self.__OnChange)
self.Bind(wx.stc.EVT_STC_UPDATEUI, self.__OnUpdateUI)
def ShouldFilterKeyEvent(self, evt):
key = evt.GetKeyCode()
mod = evt.GetModifiers()
return ((mod & wx.MOD_RAW_CONTROL) and unichr(key) in string.ascii_letters) \
or (wx.WXK_F1 <= key <= wx.WXK_F24)
def __OnKeyDown(self, evt):
evt.Skip(not self.ShouldFilterKeyEvent(evt))
def GetDyanmicEditMenuItems(self):
return []
def __OnContextMenu(self, evt):
self.SetFocus()
self.PopupMenu(edit_menu.Create(hooks={"edit": self.GetDyanmicEditMenuItems()}))
def __OnChange(self, evt):
# Assumes that all styles use the same fixed-width font.
max_len = max(self.LineLength(line) for line in xrange(self.GetLineCount()))
self.SetScrollWidth((max_len + 1) * self.TextWidth(wx.stc.STC_STYLE_DEFAULT, "_"))
def __OnUpdateUI(self, evt):
if self.HasSelection():
self.BraceHighlight(-1, -1)
return
pos = self.GetCurrentPos()
if pos > 0 and unichr(self.GetCharAt(pos - 1)) in brace_chars:
pos -= 1
if unichr(self.GetCharAt(pos)) in brace_chars:
matching_pos = self.BraceMatch(pos)
if matching_pos != -1:
self.BraceHighlight(pos, matching_pos)
else:
self.BraceBadLight(pos)
else:
self.BraceHighlight(-1, -1)
def RefreshStyle(self):
font = self.env.editor_font
font_info = (font.PointSize, font.FaceName,
font.Weight == wx.FONTWEIGHT_BOLD,
font.Style in (wx.FONTSTYLE_ITALIC, wx.FONTSTYLE_SLANT), False)
self.ClearDocumentStyle()
self.SetLexer(self.syntax.lexer)
self.SetKeyWords(0, self.syntax.keywords)
self.StyleResetDefault()
self.StyleSetFontAttr(wx.stc.STC_STYLE_DEFAULT, *font_info)
self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, "")
self.StyleClearAll()
self.IndicatorSetStyle(0, wx.stc.STC_INDIC_HIDDEN)
self.IndicatorSetStyle(1, wx.stc.STC_INDIC_HIDDEN)
self.IndicatorSetStyle(2, wx.stc.STC_INDIC_HIDDEN)
self.MarkerDefine(MARKER_FIND, wx.stc.STC_MARK_BACKGROUND, background="#CCCCFF")
self.MarkerDefine(MARKER_ERROR, wx.stc.STC_MARK_BACKGROUND, background="#FFCCCC")
for token_type, style_spec in default_styles:
self.StyleSetSpec(token_type, style_spec)
for token_type, style_spec in self.syntax.get_style_specs(default_theme):
self.StyleSetSpec(token_type, style_spec)
self.SetIndent(self.syntax.indent_width)
self.SetTabWidth(self.syntax.tab_width)
self.SetUseTabs(self.syntax.use_tabs)
self.Colourise(0, -1)
def SetSyntax(self, syntax):
self.syntax = syntax
self.RefreshStyle()
def SetSyntaxFromFilename(self, path):
self.SetSyntax(syntax_from_filename(path))
def ClearHighlight(self, marker_type):
self.MarkerDeleteAll(marker_type)
def SetHighlightedLine(self, line, marker_type):
self.ClearHighlight(marker_type)
self.MarkerAdd(line, marker_type)
def ClearAll(self):
self.ClearHighlight(MARKER_FIND)
self.ClearHighlight(MARKER_ERROR)
wx.stc.StyledTextCtrl.ClearAll(self)
def CanCut(self):
return not self.GetReadOnly() and self.CanCopy()
def CanCopy(self):
return self.HasSelection()
def CanFindNext(self):
return bool(self.env.find_details and self.env.find_details.find)
CanFindPrev = CanFindNext
def Paste(self):
text = get_clipboard_text()
if text:
self.ReplaceSelection(clean_strip_text(text))
def IsEmpty(self):
return self.GetTextLength() == 0
def GetLastVisibleLine(self):
return self.GetFirstVisibleLine() + self.LinesOnScreen() - 1
def CentreLine(self, line):
if not (self.GetFirstVisibleLine() <= line <= self.GetLastVisibleLine()):
self.ScrollToLine(line - (self.LinesOnScreen() // 2))
def SetCurrentLine(self, line):
self.CentreLine(line)
pos = self.PositionFromLine(line)
self.SetSelection(pos, pos)
def SetRangeText(self, start, end, text):
self.SetTargetStart(start)
self.SetTargetEnd(end)
self.ReplaceTarget(text)
def HasSelection(self):
start, end = self.GetSelection()
return start != end
def GetLineSelection(self):
start, end = self.GetSelection()
if start == end:
end += 1
return (self.LineFromPosition(start), self.LineFromPosition(end - 1))
def GetLineSelectionRange(self):
start_line, end_line = self.GetLineSelection()
return xrange(start_line, end_line + 1)
def SetLineSelection(self, start_line, end_line):
self.SetSelection(self.PositionFromLine(start_line), self.GetLineEndPosition(end_line))
def SelectLines(self):
start, end = self.GetSelection()
self.SetLineSelection(self.LineFromPosition(start), self.LineFromPosition(end))
def Indent(self):
self.BeginUndoAction()
for line in self.GetLineSelectionRange():
indent = self.GetLineIndentation(line)
self.SetLineIndentation(line, indent + self.GetIndent())
self.EndUndoAction()
def Unindent(self):
self.BeginUndoAction()
for line in self.GetLineSelectionRange():
indent = self.GetLineIndentation(line)
self.SetLineIndentation(line, indent - self.GetIndent())
self.EndUndoAction()
def GetSelectionIndent(self):
indent = None
for line in self.GetLineSelectionRange():
if self.GetLine(line).strip():
if indent is None:
indent = self.GetLineIndentation(line)
else:
indent = min(indent, self.GetLineIndentation(line))
return indent or 0
def Comment(self):
indent = self.GetSelectionIndent()
self.BeginUndoAction()
for line in self.GetLineSelectionRange():
if not self.GetLine(line).strip():
self.SetLineIndentation(line, indent)
s = self.GetLineRaw(line)[:-1]
pos = self.PositionFromLine(line) + indent
self.SetRangeText(pos, pos, self.syntax.comment_token)
self.EndUndoAction()
def Uncomment(self):
self.BeginUndoAction()
for line in self.GetLineSelectionRange():
s = self.GetLineRaw(line)[:-1]
if s:
offset = len(s) - len(s.lstrip())
if s[offset : offset + len(self.syntax.comment_token)] == self.syntax.comment_token:
pos = self.PositionFromLine(line) + offset
self.SetRangeText(pos, pos + len(self.syntax.comment_token), "")
self.EndUndoAction()
def ReplaceSelectionAndSelect(self, replace):
start = self.GetSelectionStart()
self.ReplaceSelection(replace)
self.SetSelection(start, start + len(replace))
def JoinLines(self):
start = self.GetSelectionStart()
lines = self.GetSelectedText().split("\n")
replace = " ".join(line.strip() for line in lines[1:])
replace = lines[0] + " " + replace if replace else lines[0]
self.ReplaceSelectionAndSelect(replace)
def GetLineIndentText(self, line_num):
line = self.GetLine(line_num)
return line[:len(line) - len(line.lstrip())]
def GetFirstSelectedLineIndent(self):
start = self.GetSelectionStart()
return self.GetLineIndentText(self.LineFromPosition(start))
def SplitLines(self):
indent = self.GetFirstSelectedLineIndent()
lines = self.GetSelectedText().split("\n", 1)
first = lines[0]
rest = lines[1] if len(lines) == 2 else ""
first_parts = first.split()
replace_lines = [first.rsplit(None, len(first_parts) - 1)[0]]
replace_lines.extend(indent + x for x in first_parts[1:])
replace_lines.extend(indent + x for x in rest.split())
replace = "\n".join(replace_lines)
self.ReplaceSelectionAndSelect(replace)
def SortLines(self):
self.SelectLines()
lines = self.GetSelectedText().split("\n")
lines.sort(key=lambda x: x.strip())
self.ReplaceSelectionAndSelect("\n".join(lines))
def SortLinesCaseInsensitive(self):
self.SelectLines()
lines = self.GetSelectedText().split("\n")
lines.sort(key=lambda x: x.strip().lower())
self.ReplaceSelectionAndSelect("\n".join(lines))
def SortLinesNaturalOrder(self):
self.SelectLines()
lines = self.GetSelectedText().split("\n")
lines.sort(key=lambda x: natural_order_key(x.strip()))
self.ReplaceSelectionAndSelect("\n".join(lines))
def UniqueLines(self):
self.SelectLines()
lines = self.GetSelectedText().split("\n")
lines = unique(lines)
self.ReplaceSelectionAndSelect("\n".join(lines))
def ReverseLines(self):
self.SelectLines()
lines = self.GetSelectedText().split("\n")
lines.reverse()
self.ReplaceSelectionAndSelect("\n".join(lines))
def ShuffleLines(self):
self.SelectLines()
lines = self.GetSelectedText().split("\n")
random.shuffle(lines)
self.ReplaceSelectionAndSelect("\n".join(lines))
def AlignColumns(self):
self.SelectLines()
lines = [split_seperators_outside_quotes(line) for line in self.GetSelectedText().split("\n")]
columns = []
for line in lines:
for i, col_text in enumerate(line):
col_width = len(col_text.strip() if i > 0 else col_text) + 1
if i >= len(columns):
columns.append(col_width)
else:
columns[i] = max(columns[i], col_width)
lines = [
line[0].ljust(columns[0]) + "".join(x.strip().ljust(columns[j+1]) for j, x in enumerate(line[1:]))
for i, line in enumerate(lines)
]
replace = "\n".join(line.rstrip() for line in lines)
self.ReplaceSelectionAndSelect(replace)
def RemoveExtraSpace(self):
replace_lines = []
for line in self.GetSelectedText().split("\n"):
indent = line[:len(line) - len(line.lstrip())]
replace_lines.append(indent + " ".join(line.split()))
self.ReplaceSelectionAndSelect("\n".join(replace_lines))
def RemoveTrailingSpace(self):
self.SelectLines()
lines = [line.rstrip() for line in self.GetSelectedText().split("\n")]
self.ReplaceSelectionAndSelect("\n".join(lines))
def RemoveLeadingSpace(self):
self.SelectLines()
lines = [line.lstrip() for line in self.GetSelectedText().split("\n")]
self.ReplaceSelectionAndSelect("\n".join(lines))
def TabsToSpaces(self):
replace = self.GetSelectedText().expandtabs(self.GetTabWidth())
self.ReplaceSelectionAndSelect(replace)
def LowerCase(self):
self.ReplaceSelectionAndSelect(self.GetSelectedText().lower())
def UpperCase(self):
self.ReplaceSelectionAndSelect(self.GetSelectedText().upper())
def TitleCase(self):
self.ReplaceSelectionAndSelect(self.GetSelectedText().title())
def SwapCase(self):
self.ReplaceSelectionAndSelect(self.GetSelectedText().swapcase())
def GetSelectedFirstLine(self):
return self.GetSelectedText().strip().split("\n", 1)[0]
def Find(self):
selected = self.GetSelectedFirstLine()
find_details = self.env.find_details
if selected:
find_details.find = selected
find_details.replace = ""
find_details.case = False
find_details.regexp = False
find_details.reverse = False
dlg = FindReplaceDialog(self, self.name, find_details)
try:
dlg.ShowModal()
find_details = dlg.GetFindDetails()
if find_details:
self.env.find_details = find_details
finally:
dlg.Destroy()
self.SetFocus()
def FindNext(self):
if self.CanFindNext():
self.env.find_details.Find(self)
def FindPrev(self):
if self.CanFindPrev():
self.env.find_details.Find(self, reverse=True)
def GoToLine(self):
dlg = GoToLineDialog(self, self.name, self.GetCurrentLine() + 1)
try:
if dlg.ShowModal() == wx.ID_OK:
self.CentreLine(dlg.GetLineNumber())
self.GotoLine(dlg.GetLineNumber())
finally:
dlg.Destroy()
self.SetFocus()
@contextmanager
def ModifyReadOnly(self):
was_read_only = self.GetReadOnly()
self.SetReadOnly(False)
try:
yield
finally:
self.SetReadOnly(was_read_only)