forked from adrianpueyo/KnobScripter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpythonhighlighter.py
319 lines (263 loc) · 12.1 KB
/
pythonhighlighter.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
# -*- coding: utf-8 -*-
""" Python Higlighter: KnobScripter's QSyntaxHighlighter adapted for python code.
Adapted from an original version by Wouter Gilsing. His comments:
Modified, simplified version of some code found I found when researching:
wiki.python.org/moin/PyQt/Python%20syntax%20highlighting
They did an awesome job, so credits to them. I only needed to make some modifications to make it fit my needs.
adrianpueyo.com
"""
import nuke
try:
if nuke.NUKE_VERSION_MAJOR < 11:
from PySide import QtCore, QtGui, QtGui as QtWidgets
from PySide.QtCore import Qt
else:
from PySide2 import QtWidgets, QtGui, QtCore
from PySide2.QtCore import Qt
except ImportError:
from Qt import QtCore, QtGui, QtWidgets
class KSPythonHighlighter(QtGui.QSyntaxHighlighter):
"""
Adapted from an original version by Wouter Gilsing. His comments:
Modified, simplified version of some code found I found when researching:
wiki.python.org/moin/PyQt/Python%20syntax%20highlighting
They did an awesome job, so credits to them. I only needed to make some
modifications to make it fit my needs for KS.
"""
def __init__(self, document, style="monokai"):
self.selected_text = ""
self.selected_text_prev = ""
self.blocked = False
self.styles = self.loadStyles() # Holds a dict for each style
self._style = style # Can be set via setStyle
self.setStyle(self._style) # Set default style
# self.updateStyle() # Load ks color scheme
super(KSPythonHighlighter, self).__init__(document)
def loadStyles(self):
""" Loads the different sets of rules """
styles = dict()
# LOAD ANY STYLE
default_styles_list = [
{
"title": "nuke",
"styles": {
'base': self.format([255, 255, 255]),
'keyword': self.format([238, 117, 181], 'bold'),
'operator': self.format([238, 117, 181], 'bold'),
'number': self.format([174, 129, 255]),
'singleton': self.format([174, 129, 255]),
'string': self.format([242, 136, 135]),
'comment': self.format([143, 221, 144]),
},
"keywords": {},
},
{
"title": "monokai",
"styles": {
'base': self.format([255, 255, 255]),
'keyword': self.format([237, 36, 110]),
'operator': self.format([237, 36, 110]),
'string': self.format([237, 229, 122]),
'comment': self.format([125, 125, 125]),
'number': self.format([165, 120, 255]),
'singleton': self.format([165, 120, 255]),
'function': self.format([184, 237, 54]),
'argument': self.format([255, 170, 10], 'italic'),
'class': self.format([184, 237, 54]),
'callable': self.format([130, 226, 255]),
'error': self.format([130, 226, 255], 'italic'),
'underline': self.format([240, 240, 240], 'underline'),
'selected': self.format([255, 255, 255], 'bold underline'),
'custom': self.format([200, 200, 200], 'italic'),
'blue': self.format([130, 226, 255], 'italic'),
'self': self.format([255, 170, 10], 'italic'),
},
"keywords": {
'custom': ['nuke'],
'blue': ['def', 'class', 'int', 'str', 'float',
'bool', 'list', 'dict', 'set', ],
'base': [],
'self': ['self'],
},
}
]
# TODO separate the format before the loadstyle thing. should be done here before looping.
for style_dict in default_styles_list:
if all(k in style_dict.keys() for k in ["title", "styles"]):
styles[style_dict["title"]] = self.loadStyle(style_dict)
return styles
def loadStyle(self, style_dict):
"""
Given a dictionary of styles and keywords, returns the style as a dict
"""
styles = style_dict["styles"].copy()
# 1. Base settings
if "base" in styles:
base_format = styles["base"]
else:
base_format = self.format([255, 255, 255])
main_keywords = [
'and', 'assert', 'break', 'continue',
'del', 'elif', 'else', 'except', 'exec', 'finally',
'for', 'from', 'global', 'if', 'import', 'in',
'is', 'lambda', 'not', 'or', 'pass', 'print',
'raise', 'return', 'try', 'while', 'yield', 'with', 'as'
]
error_keywords = ['AssertionError', 'AttributeError', 'EOFError', 'FloatingPointError',
'FloatingPointError', 'GeneratorExit', 'ImportError', 'IndexError',
'KeyError', 'KeyboardInterrupt', 'MemoryError', 'NameError',
'NotImplementedError', 'OSError', 'OverflowError', 'ReferenceError',
'RuntimeError', 'StopIteration', 'SyntaxError', 'IndentationError',
'TabError', 'SystemError', 'SystemExit', 'TypeError', 'UnboundLocalError',
'UnicodeError', 'UnicodeEncodeError', 'UnicodeDecodeError', 'UnicodeTranslateError',
'ValueError', 'ZeroDivisionError',
]
base_keywords = [',']
operator_keywords = [
'=', '==', '!=', '<', '<=', '>', '>=',
'\+', '-', '\*', '/', '//', '\%', '\*\*',
'\+=', '-=', '\*=', '/=', '\%=',
'\^', '\|', '\&', '\~', '>>', '<<'
]
singletons = ['True', 'False', 'None']
if 'comment' in styles:
tri_single = (QtCore.QRegExp("'''"), 1, styles['comment'])
tri_double = (QtCore.QRegExp('"""'), 2, styles['comment'])
else:
tri_single = (QtCore.QRegExp("'''"), 1, base_format)
tri_double = (QtCore.QRegExp('"""'), 2, base_format)
# 2. Rules
rules = []
if "argument" in styles:
# Everything inside parentheses
rules += [(r"def [\w]+[\s]*\((.*)\)", 1, styles['argument'])]
# Now restore unwanted stuff...
rules += [(i, 0, base_format) for i in base_keywords]
rules += [(r"[^\(\w),.][\s]*[\w]+", 0, base_format)]
if "callable" in styles:
rules += [(r"\b([\w]+)[\s]*[(]", 1, styles['callable'])]
if "keyword" in styles:
rules += [(r'\b%s\b' % i, 0, styles['keyword']) for i in main_keywords]
if "error" in styles:
rules += [(r'\b%s\b' % i, 0, styles['error']) for i in error_keywords]
if "operator" in styles:
rules += [(i, 0, styles['operator']) for i in operator_keywords]
if "singleton" in styles:
rules += [(r'\b%s\b' % i, 0, styles['singleton']) for i in singletons]
if "number" in styles:
rules += [(r'\b[0-9]+\b', 0, styles['number'])]
# Function definitions
if "function" in styles:
rules += [(r"def[\s]+([\w\.]+)", 1, styles['function'])]
# Class definitions
if "class" in styles:
rules += [(r"class[\s]+([\w\.]+)", 1, styles['class'])]
# Class argument (which is also a class so must be same color)
rules += [(r"class[\s]+[\w\.]+[\s]*\((.*)\)", 1, styles['class'])]
# Function arguments
if "argument" in styles:
rules += [(r"def[\s]+[\w]+[\s]*\(([\w]+)", 1, styles['argument'])]
# Custom keywords
if "keywords" in style_dict.keys():
keywords = style_dict["keywords"]
for k in keywords.keys():
if k in styles:
rules += [(r'\b%s\b' % i, 0, styles[k]) for i in keywords[k]]
if "string" in styles:
# Double-quoted string, possibly containing escape sequences
rules += [(r'"[^"\\]*(\\.[^"\\]*)*"', 0, styles['string'])]
# Single-quoted string, possibly containing escape sequences
rules += [(r"'[^'\\]*(\\.[^'\\]*)*'", 0, styles['string'])]
# Comments from '#' until a newline
if "comment" in styles:
rules += [(r'#[^\n]*', 0, styles['comment'])]
# 3. Resulting dictionary
result = {
"rules": [(QtCore.QRegExp(pat), index, fmt) for (pat, index, fmt) in rules],
# Build a QRegExp for each pattern
"tri_single": tri_single,
"tri_double": tri_double,
}
return result
@staticmethod
def format(rgb, style=''):
"""
Return a QtWidgets.QTextCharFormat with the given attributes.
"""
color = QtGui.QColor(*rgb)
text_format = QtGui.QTextCharFormat()
text_format.setForeground(color)
if 'bold' in style:
text_format.setFontWeight(QtGui.QFont.Bold)
if 'italic' in style:
text_format.setFontItalic(True)
if 'underline' in style:
text_format.setUnderlineStyle(QtGui.QTextCharFormat.SingleUnderline)
return text_format
def highlightBlock(self, text):
"""
Apply syntax highlighting to the given block of text.
"""
for expression, nth, text_format in self.styles[self._style]["rules"]:
index = expression.indexIn(text, 0)
while index >= 0:
# We actually want the index of the nth match
index = expression.pos(nth)
length = len(expression.cap(nth))
try:
self.setFormat(index, length, text_format)
except:
return False
index = expression.indexIn(text, index + length)
self.setCurrentBlockState(0)
# Multi-line strings etc. based on selected scheme
in_multiline = self.match_multiline(text, *self.styles[self._style]["tri_single"])
if not in_multiline:
in_multiline = self.match_multiline(text, *self.styles[self._style]["tri_double"])
# TODO if there's a selection, highlight same occurrences in the full document.
# If no selection but something highlighted, unhighlight full document. (do it thru regex or sth)
def setStyle(self, style_name="nuke"):
if style_name in self.styles.keys():
self._style = style_name
else:
raise Exception("Style {} not found.".format(str(style_name)))
def match_multiline(self, text, delimiter, in_state, style):
"""
Check whether highlighting requires multiple lines.
"""
# If inside triple-single quotes, start at 0
if self.previousBlockState() == in_state:
start = 0
add = 0
# Otherwise, look for the delimiter on this line
else:
start = delimiter.indexIn(text)
# Move past this match
add = delimiter.matchedLength()
# As long as there's a delimiter match on this line...
while start >= 0:
# Look for the ending delimiter
end = delimiter.indexIn(text, start + add)
# Ending delimiter on this line?
if end >= add:
length = end - start + add + delimiter.matchedLength()
self.setCurrentBlockState(0)
# No; multi-line string
else:
self.setCurrentBlockState(in_state)
length = len(text) - start + add
# Apply formatting
self.setFormat(start, length, style)
# Look for the next match
start = delimiter.indexIn(text, start + length)
# Return True if still inside a multi-line string, False otherwise
if self.currentBlockState() == in_state:
return True
else:
return False
@property
def style(self):
return self._style
@style.setter
def style(self, style_name="nuke"):
self.setStyle(style_name)