-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhighlighter.cpp
77 lines (60 loc) · 2.46 KB
/
highlighter.cpp
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
#include "highlighter.h"
#include "mysql_keywords.cpp"
#include <QDebug>
Highlighter::Highlighter(QTextDocument *parent)
: QSyntaxHighlighter(parent)
{
HighlightingRule rule;
keywordFormat.setForeground(Qt::darkBlue);
keywordFormat.setFontWeight(QFont::Bold);
QStringList keywordPatterns;
foreach (const QString &pattern, keywords) {
rule.pattern = QRegularExpression("\\b" + pattern + "\\b", QRegularExpression::CaseInsensitiveOption);
rule.format = keywordFormat;
highlightingRules.append(rule);
}
singleLineCommentFormat.setForeground(Qt::gray);
singleLineCommentFormat.setFontItalic(true);
rule.pattern = QRegularExpression("#[^\n]*");
rule.format = singleLineCommentFormat;
highlightingRules.append(rule);
identifierFormat.setForeground(Qt::darkYellow);
rule.pattern = QRegularExpression("`[A-Za-z_]+`");
rule.format = identifierFormat;
highlightingRules.append(rule);
quotationFormat.setForeground(Qt::darkGreen);
rule.pattern = QRegularExpression("\".*\"|\'.*\'");
rule.format = quotationFormat;
highlightingRules.append(rule);
multiLineCommentFormat.setForeground(Qt::gray);
multiLineCommentFormat.setFontItalic(true);
commentStartExpression = QRegularExpression("/\\*");
commentEndExpression = QRegularExpression("\\*/");
}
void Highlighter::highlightBlock(const QString &text)
{
foreach (const HighlightingRule &rule, highlightingRules) {
QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text);
while (matchIterator.hasNext()) {
QRegularExpressionMatch match = matchIterator.next();
setFormat(match.capturedStart(), match.capturedLength(), rule.format);
}
}
setCurrentBlockState(0);
int startIndex = 0;
if (previousBlockState() != 1)
startIndex = text.indexOf(commentStartExpression);
while (startIndex >= 0) {
QRegularExpressionMatch match = commentEndExpression.match(text, startIndex);
int endIndex = match.capturedStart();
int commentLength = 0;
if (endIndex == -1) {
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
} else {
commentLength = endIndex - startIndex + match.capturedLength();
}
setFormat(startIndex, commentLength, multiLineCommentFormat);
startIndex = text.indexOf(commentStartExpression, startIndex + commentLength);
}
}