-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathPythonHighlighter.py
165 lines (144 loc) · 6.75 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
import sys
from PyQt5 import QtCore
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class PythonHighlighter(QSyntaxHighlighter):
Rules = []
Formats = {}
def __init__(self, parent=None):
super(PythonHighlighter, self).__init__(parent)
self.initializeFormats()
KEYWORDS = ["and", "as", "assert", "break", "class",
"continue", "def", "del", "elif", "else", "except",
"exec", "finally", "for", "from", "global", "if",
"import", "in", "is", "lambda", "not", "or", "pass",
"print", "raise", "return", "try", "while", "with",
"yield"]
BUILTINS = ["abs", "all", "any", "basestring", "bool",
"callable", "chr", "classmethod", "cmp", "compile",
"complex", "delattr", "dict", "dir", "divmod",
"enumerate", "eval", "execfile", "exit", "file",
"filter", "float", "frozenset", "getattr", "globals",
"hasattr", "hex", "id", "int", "isinstance",
"issubclass", "iter", "len", "list", "locals", "map",
"max", "min", "object", "oct", "open", "ord", "pow",
"property", "range", "reduce", "repr", "reversed",
"round", "set", "setattr", "slice", "sorted",
"staticmethod", "str", "sum", "super", "tuple", "type",
"vars", "zip"]
CONSTANTS = ["False", "True", "None", "NotImplemented",
"Ellipsis"]
PythonHighlighter.Rules.append((QRegExp(
"|".join([r"\b%s\b" % keyword for keyword in KEYWORDS])),
"keyword"))
PythonHighlighter.Rules.append((QRegExp(
"|".join([r"\b%s\b" % builtin for builtin in BUILTINS])),
"builtin"))
PythonHighlighter.Rules.append((QRegExp(
"|".join([r"\b%s\b" % constant
for constant in CONSTANTS])), "constant"))
PythonHighlighter.Rules.append((QRegExp(
r"\b[+-]?[0-9]+[lL]?\b"
r"|\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b"
r"|\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b"),
"number"))
PythonHighlighter.Rules.append((QRegExp(
r"\bPyQt5\b|\bQt?[A-Z][a-z]\w+\b"), "pyqt"))
PythonHighlighter.Rules.append((QRegExp(r"\b@\w+\b"),
"decorator"))
stringRe = QRegExp(r"""(?:'[^']*'|"[^"]*")""")
stringRe.setMinimal(True)
PythonHighlighter.Rules.append((stringRe, "string"))
self.stringRe = QRegExp(r"""(:?"["]".*"["]"|'''.*''')""")
self.stringRe.setMinimal(True)
PythonHighlighter.Rules.append((self.stringRe, "string"))
self.tripleSingleRe = QRegExp(r"""'''(?!")""")
self.tripleDoubleRe = QRegExp(r'''"""(?!')''')
@staticmethod
def initializeFormats():
baseFormat = QTextCharFormat()
baseFormat.setFontFamily("courier")
#字体大小
# baseFormat.setFontPointSize(12)
for name, color in (("normal", QtCore.Qt.black),
("keyword", QtCore.Qt.darkBlue), ("builtin", QtCore.Qt.darkRed),
("constant", QtCore.Qt.darkGreen),
("decorator", QtCore.Qt.darkBlue), ("comment", QtCore.Qt.darkGreen),
("string", QtCore.Qt.darkYellow), ("number", QtCore.Qt.darkMagenta),
("error", QtCore.Qt.darkRed), ("pyqt", QtCore.Qt.darkCyan)):
format = QTextCharFormat(baseFormat)
format.setForeground(QColor(color))
if name in ("keyword", "decorator"):
format.setFontWeight(QFont.Bold)
# if name == "comment":
#设置斜体
# format.setFontItalic(True)
PythonHighlighter.Formats[name] = format
def highlightBlock(self, text):
NORMAL, TRIPLESINGLE, TRIPLEDOUBLE, ERROR = range(4)
textLength = len(text)
prevState = self.previousBlockState()
self.setFormat(0, textLength,
PythonHighlighter.Formats["normal"])
if text.startswith("Traceback") or text.startswith("Error: "):
self.setCurrentBlockState(ERROR)
self.setFormat(0, textLength,
PythonHighlighter.Formats["error"])
return
if (prevState == ERROR and
not (text.startswith(sys.ps1) or text.startswith("#"))):
self.setCurrentBlockState(ERROR)
self.setFormat(0, textLength,
PythonHighlighter.Formats["error"])
return
for regex, format in PythonHighlighter.Rules:
i = regex.indexIn(text)
while i >= 0:
length = regex.matchedLength()
self.setFormat(i, length,
PythonHighlighter.Formats[format])
i = regex.indexIn(text, i + length)
# Slow but good quality highlighting for comments. For more
# speed, comment this out and add the following to __init__:
# PythonHighlighter.Rules.append((QRegExp(r"#.*"), "comment"))
if not text:
pass
elif text[0] == "#":
self.setFormat(0, len(text),
PythonHighlighter.Formats["comment"])
else:
stack = []
for i, c in enumerate(text):
if c in ('"', "'"):
if stack and stack[-1] == c:
stack.pop()
else:
stack.append(c)
elif c == "#" and len(stack) == 0:
self.setFormat(i, len(text),
PythonHighlighter.Formats["comment"])
break
self.setCurrentBlockState(NORMAL)
if self.stringRe.indexIn(text) != -1:
return
# This is fooled by triple quotes inside single quoted strings
for i, state in ((self.tripleSingleRe.indexIn(text),
TRIPLESINGLE),
(self.tripleDoubleRe.indexIn(text),
TRIPLEDOUBLE)):
if self.previousBlockState() == state:
if i == -1:
i = len(text)
self.setCurrentBlockState(state)
self.setFormat(0, i + 3,
PythonHighlighter.Formats["string"])
elif i > -1:
self.setCurrentBlockState(state)
self.setFormat(i, len(text),
PythonHighlighter.Formats["string"])
def rehighlight(self):
QApplication.setOverrideCursor(QCursor(
QtCore.Qt.WaitCursor))
QSyntaxHighlighter.rehighlight(self)
QApplication.restoreOverrideCursor()