cutter/src/common/Highlighter.cpp

65 lines
2.2 KiB
C++
Raw Normal View History

2017-10-01 19:09:42 +00:00
#include "Highlighter.h"
#include "core/MainWindow.h"
#include <QtGui>
2021-01-24 14:50:13 +00:00
Highlighter::Highlighter(QTextDocument *parent) : QSyntaxHighlighter(parent)
{
HighlightingRule rule;
2018-04-12 06:33:30 +00:00
core = Core();
2017-10-09 18:08:35 +00:00
2017-04-09 19:55:06 +00:00
regFormat.setForeground(QColor(236, 100, 75));
for (const QString &pattern : this->core->regs) {
rule.pattern.setPattern("\\b" + pattern + "\\b");
rule.pattern.setPatternOptions(QRegularExpression::CaseInsensitiveOption);
rule.format = regFormat;
highlightingRules.append(rule);
}
singleLineCommentFormat.setFontWeight(QFont::Bold);
singleLineCommentFormat.setForeground(QColor(63, 195, 128));
rule.pattern.setPattern(";[^\n]*");
rule.format = singleLineCommentFormat;
highlightingRules.append(rule);
commentStartRegularExpression.setPattern("/\\*");
commentEndRegularExpression.setPattern("\\*/");
}
void Highlighter::highlightBlock(const QString &text)
{
for (const HighlightingRule &rule : highlightingRules) {
QRegularExpression expression(rule.pattern);
int index = expression.match(text).capturedStart();
2018-03-21 20:32:32 +00:00
while (index >= 0) {
int length = expression.match(text).capturedLength();
setFormat(index, length, rule.format);
index = expression.match(text.mid(index + length)).capturedStart();
}
}
setCurrentBlockState(0);
int startIndex = 0;
if (previousBlockState() != 1)
startIndex = QRegularExpression(commentStartRegularExpression).match(text).capturedStart();
2018-03-21 20:32:32 +00:00
while (startIndex >= 0) {
2021-01-24 14:50:13 +00:00
QRegularExpressionMatch commentEndMatch =
QRegularExpression(commentEndRegularExpression).match(text.mid(startIndex));
int endIndex = commentEndMatch.capturedStart();
int commentLength;
2018-03-21 20:32:32 +00:00
if (endIndex == -1) {
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
2018-03-21 20:32:32 +00:00
} else {
2021-01-24 14:50:13 +00:00
commentLength = endIndex - startIndex + commentEndMatch.capturedLength();
}
setFormat(startIndex, commentLength, multiLineCommentFormat);
2021-01-24 14:50:13 +00:00
startIndex = QRegularExpression(commentStartRegularExpression)
.match(text.mid(startIndex + commentLength))
.capturedStart();
}
}