-
Notifications
You must be signed in to change notification settings - Fork 0
/
codeEditor.py
78 lines (60 loc) · 2.79 KB
/
codeEditor.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
from PyQt5.QtGui import QTextCursor, QTextCharFormat, QSyntaxHighlighter, QFont
from PyQt5.QtWidgets import QPlainTextEdit, QTextEdit, QWidget, QVBoxLayout, QPushButton, QApplication
from PyQt5.QtCore import Qt, QRegExp
class PythonCodeEditor(QPlainTextEdit):
def __init__(self):
super().__init__()
# Set up tab and indentation settings
self.setTabStopWidth(20)
self.setTabChangesFocus(False)
# Create a syntax highlighter
self.highlighter = PythonSyntaxHighlighter(self.document())
self.zoom_level = 5
def textZoomIn(self):
self.zoom_level *= 2
self.zoom_level = min(self.zoom_level, 20)
self.zoomIn(self.zoom_level)
def textZoomOut(self):
self.zoom_level /= 2
self.zoom_level = max(self.zoom_level, 2)
self.zoomOut(self.zoom_level)
def text(self):
return self.toPlainText()
class PythonSyntaxHighlighter(QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
self.highlighting_rules = []
# Create rules for highlighting different elements
keyword_format = QTextCharFormat()
keyword_format.setForeground(Qt.blue)
keyword_format.setFontWeight(QFont.Bold)
keywords = ["False","None","True","and","as","assert","break",
"class","continue","def","del","elif","else","except",
"finally","for","from","global","if","import","in","is",
"lambda","nonlocal","not","or","pass","raise","return",
"try","while","with","yield"] # Add more as needed
for keyword in keywords:
rule = (r'\b' + keyword + r'\b', keyword_format)
self.highlighting_rules.append(rule)
# Create a rule for strings (in double or single quotes)
string_format = QTextCharFormat()
string_format.setForeground(Qt.darkGreen)
self.highlighting_rules.append((r'\".*\"', string_format))
self.highlighting_rules.append((r'\'.*\'', string_format))
self.highlighting_rules.append((r'#.*$', string_format))
triple_double_quoted_format = QTextCharFormat()
triple_double_quoted_format.setForeground(Qt.red)
self.highlighting_rules.append((r'""".*?"""', triple_double_quoted_format))
def highlightBlock(self, text):
for pattern, format in self.highlighting_rules:
expression = QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, format)
index = expression.indexIn(text, index + length)
if __name__ == '__main__':
app = QApplication([])
editor = PythonCodeEditor()
editor.show()
app.exec_()