我正在做一个代码编辑器,想要语法高亮。我已经完成了所有代码,一旦我添加了太多匹配项,它就会崩溃。
我有一个
python.yaml
正则表达式文件,以及 syntaxHighliter.py
其中包含 higlighter 类。如果有帮助,我将在项目的其余部分使用名为 customtkinter 的 tkinter 修改版本。
python.yaml:
categories:
built-in-constants:
color: '#ec5f66'
matches: ['True', 'False', 'None', 'self']
keywords:
color: '#c695c6'
matches: ['try', 'except', 'if', 'else', 'elif', 'def', 'import']
functions:
color: blue4
matches: [] #[int, str, dict, list, set, float]
numbers:
color: '#f9ae58'
strings:
color: '#99c794'
syntaxHighliter.py:
import tkinter as tk
import yaml
from yaml import CLoader as Loader
class Highlighter:
def __init__(self, text_widget, syntax_file):
self.text_widget = text_widget
self.syntax_file = syntax_file
self.categories = None
self.disallowed_previous_chars = ["_", "-", "."]
self.parse_syntax_file()
self.text_widget.bind('<KeyRelease>', self.on_key_release)
def on_key_release(self, event=None):
self.highlight()
def highlight(self, event=None):
length = tk.IntVar()
for category in self.categories:
matches = self.categories[category]['matches']
print(f"Scanning category: {category}. Matches are: {matches}")
for keyword in matches:
start = 1.0
keyword = keyword + "[^A-Za-z_-]"
idx = self.text_widget.search(keyword, start, stopindex=tk.END, count=length, regexp=1)
while idx:
char_match_found = int(str(idx).split('.')[1])
line_match_found = int(str(idx).split('.')[0])
if char_match_found > 0:
previous_char_index = str(line_match_found) + '.' + str(char_match_found - 1)
previous_char = self.text_widget.get(previous_char_index, previous_char_index + "+1c")
if previous_char.isalnum() or previous_char in self.disallowed_previous_chars:
print(f"There was an illegal character before this word ({category}, idx= {idx}, end= {end}), so nothing was tagged")
end = f"{idx}+{length.get() - 1}c"
start = end
idx = self.text_widget.search(keyword, start, stopindex=tk.END, regexp=1)
else:
end = f"{idx}+{length.get() - 1}c"
self.text_widget.tag_add(category, idx, end)
start = end
idx = self.text_widget.search(keyword, start, stopindex=tk.END, regexp=1)
print(f"Found: {category}, at index: {idx}, to {end}")
start = 1.0
idx = self.text_widget.search(r"(\d)+[.]?(\d)*", start, stopindex=tk.END, regexp=1, count=length)
while idx:
end = f"{idx}+{length.get()}c"
self.text_widget.tag_add(category, idx, end)
start = end
idx = self.text_widget.search(r"(\d)+[.]?(\d)*", start, stopindex=tk.END, regexp=1, count=length)
self.highlight_regex(r"[\'][^\']*[\']", "string")
self.highlight_regex(r"[\"][^\']*[\"]", "string")
def highlight_regex(self, regex, tag):
# Highlights regular expressions, FUNCTION CHECKED AND WORKING (for strings, at least)
length = tk.IntVar()
start = 1.0
idx = self.text_widget.search(regex, start, stopindex=tk.END, regexp=1, count=length)
while idx:
end = f"{idx}+{length.get()}c"
self.text_widget.tag_add(tag, idx, end)
start = end
idx = self.text_widget.search(regex, start, stopindex=tk.END, regexp=1, count=length)
def parse_syntax_file(self):
with open(self.syntax_file, 'r') as stream:
try:
config = yaml.load(stream, Loader=Loader)
except yaml.YAMLError as error:
print(error)
return
self.categories = config['categories']
self.numbers_color = config['numbers']['color']
self.strings_color = config['strings']['color']
self.configure_tags()
def configure_tags(self):
for category in self.categories.keys():
color = self.categories[category]['color']
self.text_widget.tag_configure(category, foreground=color)
self.text_widget.tag_configure("number", foreground=self.numbers_color)
self.text_widget.tag_configure("string", foreground=self.strings_color)
当我取消注释
python.yaml
中的注释行或添加另一个匹配项时,整个应用程序冻结。