C++编辑器-3
2026-02-15 14:26:02
发布于:浙江
该代码并不完整,点此进入代码框架页面
class CppHighlighter(QSyntaxHighlighter):
"""C++语法高亮器(括号深灰色,其他颜色按需调整)"""
def __init__(self, document):
super().__init__(document)
self.highlighting_rules = []
# ========== 关键字(红色) ==========
keywords = [
'alignas', 'alignof', 'and', 'and_eq', 'asm', 'auto', 'bitand', 'bitor',
'bool', 'break', 'case', 'catch', 'class', 'compl', 'concept', 'const',
'consteval', 'constexpr', 'const_cast', 'continue', 'co_await', 'co_return',
'co_yield', 'decltype', 'default', 'delete', 'do', 'dynamic_cast', 'else',
'enum', 'explicit', 'export', 'extern', 'false', 'for', 'friend', 'goto',
'if', 'inline', 'import', 'mutable', 'namespace', 'new', 'noexcept',
'not', 'not_eq', 'nullptr', 'operator', 'or', 'or_eq', 'private',
'protected', 'public', 'register', 'reinterpret_cast', 'requires',
'return', 'sizeof', 'static', 'static_assert', 'static_cast',
'struct', 'switch', 'template', 'this', 'thread_local', 'throw',
'true', 'try', 'typedef', 'typeid', 'typename', 'union',
'using', 'virtual', 'volatile', 'while', 'xor', 'xor_eq'
]
control_flow_keywords = [
'if', 'else', 'for', 'while', 'do', 'switch', 'case', 'break',
'continue', 'return', 'goto'
]
all_keywords = list(set(keywords + control_flow_keywords))
keyword_format = QTextCharFormat()
keyword_format.setForeground(QColor("#FF0000")) # 红色
keyword_format.setFontWeight(QFont.Bold)
for word in all_keywords:
pattern = r'\b' + word + r'\b'
self.highlighting_rules.append((QRegExp(pattern), keyword_format))
# ========== 数据类型(深蓝色 #4169E1) ==========
data_types = [
'int', 'float', 'double', 'char', 'void', 'bool', 'short', 'long',
'signed', 'unsigned', 'string', 'wstring', 'size_t', 'int8_t',
'int16_t', 'int32_t', 'int64_t', 'uint8_t', 'uint16_t', 'uint32_t',
'uint64_t'
]
data_type_format = QTextCharFormat()
data_type_format.setForeground(QColor("#4169E1")) # RoyalBlue
data_type_format.setFontWeight(QFont.Bold)
for word in data_types:
pattern = r'\b' + word + r'\b'
self.highlighting_rules.append((QRegExp(pattern), data_type_format))
# 存储所有关键字(用于函数高亮判断)
self.all_keywords = set(all_keywords + data_types + control_flow_keywords)
# ========== 其他运算符(蓝绿色 #20B2AA) ==========
operator_format = QTextCharFormat()
operator_format.setForeground(QColor("#20B2AA")) # 蓝绿色
arithmetic_operators = [r'\+', r'-', r'\*', r'/', r'%', r'\+\+', r'--']
relational_operators = [r'==', r'!=', r'>=', r'<=', r'>', r'<']
logical_operators = [r'&&', r'\|\|', r'!']
bitwise_operators = [r'&', r'\|', r'\^', r'~', r'<<', r'>>']
assignment_operators = [r'=', r'\+=', r'-=', r'\*=', r'/=', r'%=', r'&=', r'\|=', r'\^=', r'<<=', r'>>=']
member_operators = [r'->', r'\.', r'::']
conditional_operators = [r'\?', r':']
all_other_operators = (arithmetic_operators + relational_operators +
logical_operators + bitwise_operators +
assignment_operators + member_operators +
conditional_operators)
for op in all_other_operators:
self.highlighting_rules.append((QRegExp(op), operator_format))
# ========== 单行注释(灰色 #808080) ==========
single_line_comment_format = QTextCharFormat()
single_line_comment_format.setForeground(QColor("#808080"))
self.highlighting_rules.append((QRegExp(r'//[^\n]*'), single_line_comment_format))
# 多行注释(由状态机处理)
self.comment_start_expression = QRegExp(r'/\*')
self.comment_end_expression = QRegExp(r'\*/')
self.multi_line_comment_format = QTextCharFormat()
self.multi_line_comment_format.setForeground(QColor("#808080"))
# ========== 数字(浅紫色 #9370DB) ==========
number_format = QTextCharFormat()
number_format.setForeground(QColor("#9370DB")) # MediumPurple
self.highlighting_rules.append((QRegExp(r'\b\d+\b'), number_format))
self.highlighting_rules.append((QRegExp(r'\b\d*\.\d+\b'), number_format))
self.highlighting_rules.append((QRegExp(r'\b\d+\.\d*\b'), number_format))
self.highlighting_rules.append((QRegExp(r'\b\d+[eE][+-]?\d+\b'), number_format))
self.highlighting_rules.append((QRegExp(r'\b\d*\.\d+[eE][+-]?\d+\b'), number_format))
# ========== 括号(深灰色 #404040) ==========
bracket_format = QTextCharFormat()
bracket_format.setForeground(QColor("#303030")) # 深灰色
bracket_symbols = [r'\(', r'\)', r'\[', r'\]', r'\{', r'\}']
for sym in bracket_symbols:
self.highlighting_rules.append((QRegExp(sym), bracket_format))
# ========== 字符串(蓝色 #0000FF) ==========
self.string_format = QTextCharFormat()
self.string_format.setForeground(QColor("#0000FF"))
# 双引号字符串(支持转义)
self.highlighting_rules.append((QRegExp(r'"(?:\\.|[^"\\])*"'), self.string_format))
# 单引号字符(支持转义)
self.highlighting_rules.append((QRegExp(r"'(?:\\.|[^'\\])*'"), self.string_format))
# ========== 头文件(尖括号内容,蓝色) ==========
header_format = QTextCharFormat()
header_format.setForeground(QColor("#0000FF"))
self.highlighting_rules.append((QRegExp(r'<[^>]+>'), header_format))
# ========== 函数(橙黄色) ==========
self.function_format = QTextCharFormat()
self.function_format.setForeground(QColor("#FF8C00"))
self.function_format.setFontWeight(QFont.Bold)
self.defined_functions = set()
def highlightBlock(self, text):
"""应用语法高亮"""
# 首先处理多行注释
self.setCurrentBlockState(0)
start_index = 0
if self.previousBlockState() != 1:
start_index = self.comment_start_expression.indexIn(text)
while start_index >= 0:
end_index = self.comment_end_expression.indexIn(text, start_index)
if end_index == -1:
self.setCurrentBlockState(1)
comment_length = len(text) - start_index
self.setFormat(start_index, comment_length, self.multi_line_comment_format)
break
else:
comment_length = end_index - start_index + self.comment_end_expression.matchedLength()
self.setFormat(start_index, comment_length, self.multi_line_comment_format)
start_index = self.comment_start_expression.indexIn(text, start_index + comment_length)
# 应用普通规则,跳过已格式化为多行注释的区域
for pattern, format in self.highlighting_rules:
if pattern.pattern() in (r'/\*', r'\*/'):
continue
expression = QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
if self.format(index).foreground().color() == self.multi_line_comment_format.foreground().color():
index = expression.indexIn(text, index + 1)
continue
# 跳过单行注释内的内容(除了单行注释规则本身)
if pattern.pattern() != r'//[^\n]*':
text_before = text[:index]
last_comment = text_before.rfind("//")
if last_comment != -1:
newline_after = text_before.find("\n", last_comment)
if newline_after == -1 or newline_after < last_comment:
index = expression.indexIn(text, index + 1)
continue
length = expression.matchedLength()
self.setFormat(index, length, format)
index = expression.indexIn(text, index + length)
# 单独处理函数高亮
self.highlight_functions(text)
def highlight_functions(self, text):
"""高亮函数调用"""
function_pattern = QRegExp(r'\b([A-Za-z_][A-Za-z0-9_]*)\s*(?=\()')
index = function_pattern.indexIn(text)
while index >= 0:
matched_text = function_pattern.cap(1)
# 跳过注释和字符串
if self.format(index).foreground().color() in (self.multi_line_comment_format.foreground().color(), self.string_format.foreground().color()):
index = function_pattern.indexIn(text, index + 1)
continue
# 跳过单行注释
text_before = text[:index]
last_comment = text_before.rfind("//")
if last_comment != -1:
newline_after = text_before.find("\n", last_comment)
if newline_after == -1 or newline_after < last_comment:
index = function_pattern.indexIn(text, index + 1)
continue
# 跳过关键字
if matched_text in self.all_keywords:
index = function_pattern.indexIn(text, index + 1)
continue
length = function_pattern.matchedLength()
self.setFormat(index, len(matched_text), self.function_format)
index = function_pattern.indexIn(text, index + length)
def update_defined_functions(self, text):
"""更新已定义的函数列表"""
doc = self.document()
self.defined_functions.clear()
func_def_pattern = QRegExp(r'\b([A-Za-z_][A-Za-z0-9_]*)\s*\([^)]*\)\s*(?:\{|;)')
for i in range(doc.blockCount()):
block = doc.findBlockByNumber(i)
block_text = block.text()
index = func_def_pattern.indexIn(block_text)
while index >= 0:
func_name = func_def_pattern.cap(1)
if func_name not in self.all_keywords:
self.defined_functions.add(func_name)
index = func_def_pattern.indexIn(block_text, index + 1)
这里空空如也





















有帮助,赞一个