SILICON
Loading...
Searching...
No Matches
codeSyntaxHighlighter.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
19
20#include <algorithm>
21#include <initializer_list>
22#include <stdexcept>
23
24#include <QPalette>
25#include <QStringList>
26#include <QTextDocument>
27
28#include <ui/shell/theme.hpp>
29
30namespace SILICON::ui {
31namespace {
32
33 [[nodiscard]] QRegularExpression compileExpression(const std::string_view pattern)
34 {
35 QRegularExpression expression(
36 QString::fromUtf8(pattern.data(), static_cast<qsizetype>(pattern.size())));
37 if (!expression.isValid())
38 throw std::invalid_argument(QString("Invalid code-syntax expression '%1': %2")
39 .arg(expression.pattern(), expression.errorString())
40 .toStdString());
41 return expression;
42 }
43
44 [[nodiscard]] QTextCharFormat colored(const QColor& color)
45 {
46 QTextCharFormat format;
47 format.setForeground(color);
48 return format;
49 }
50
51} // namespace
52
54 : QSyntaxHighlighter(document)
55{
56}
57
59{
60 syntax = newSyntax;
61 keywordGroups.clear();
62 matchRules.clear();
63 regionRules.clear();
64
65 if (syntax) {
66 for (const auto& group : syntax->keywordGroups) {
67 QStringList escapedWords;
68 escapedWords.reserve(static_cast<qsizetype>(group.words.size()));
69 for (const auto word : group.words) {
70 escapedWords.append(QRegularExpression::escape(
71 QString::fromUtf8(word.data(), static_cast<qsizetype>(word.size()))));
72 }
73 const QString extra = QRegularExpression::escape(
74 QString::fromUtf8(syntax->extraWordCharacters.data(),
75 static_cast<qsizetype>(syntax->extraWordCharacters.size())));
76 keywordGroups.push_back({.style = group.style,
77 .expression = compileExpression(
78 QString("(?<![A-Za-z0-9_%1])(?:%2)(?![A-Za-z0-9_%1])")
79 .arg(extra, escapedWords.join('|'))
80 .toStdString())});
81 }
82
83 for (const auto& rule : syntax->matchRules) {
84 CompiledMatchRule compiled{.style = rule.style,
85 .expression = compileExpression(rule.pattern),
86 .containedRules = {}};
87 for (const auto& contained : rule.containedRules) {
88 compiled.containedRules.push_back(
89 {.style = contained.style,
90 .expression = compileExpression(contained.pattern)});
91 }
92 matchRules.push_back(std::move(compiled));
93 }
94
95 for (const auto& region : syntax->regionRules) {
96 CompiledRegionRule compiled{
97 .style = region.style,
98 .startExpression = compileExpression(region.startPattern),
99 .endExpression = compileExpression(region.endPattern),
100 .skipExpression = region.skipPattern.empty()
101 ? QRegularExpression{}
102 : compileExpression(region.skipPattern),
103 .containedRules = {},
104 .multiline = region.multiline,
105 };
106 for (const auto& contained : region.containedRules) {
107 compiled.containedRules.push_back(
108 {.style = contained.style,
109 .expression = compileExpression(contained.pattern)});
110 }
111 regionRules.push_back(std::move(compiled));
112 }
113 }
114
115 rehighlight();
116}
117
118void CodeSyntaxHighlighter::setPalette(const QPalette& palette)
119{
120 const bool dark = palette.color(QPalette::Base).lightness()
121 < palette.color(QPalette::Text).lightness();
122 // Use the editor's palette so previews can differ from the application theme.
123 const auto& colors = (dark ? theme::dark() : theme::light()).colors;
124 const auto set = [&](theme::ColorToken token,
125 std::initializer_list<CodeSyntaxStyle> styles) {
126 for (const auto style : styles)
127 formats[static_cast<std::size_t>(style)] = colored(colors[token]);
128 };
129 using enum CodeSyntaxStyle;
134 QColor stringColor = colors[theme::ColorToken::Green];
135 if (!dark)
136 stringColor = stringColor.darker(180);
137 formats[static_cast<std::size_t>(String)] = colored(stringColor);
138
139 formats[static_cast<std::size_t>(CodeSyntaxStyle::Statement)].setFontWeight(
140 QFont::DemiBold);
141 formats[static_cast<std::size_t>(CodeSyntaxStyle::Conditional)].setFontWeight(
142 QFont::DemiBold);
143 formats[static_cast<std::size_t>(CodeSyntaxStyle::Repeat)].setFontWeight(
144 QFont::DemiBold);
145 formats[static_cast<std::size_t>(CodeSyntaxStyle::Todo)].setFontWeight(QFont::Bold);
146 formats[static_cast<std::size_t>(CodeSyntaxStyle::Global)].setFontWeight(
147 QFont::DemiBold);
148 formats[static_cast<std::size_t>(CodeSyntaxStyle::Comment)].setFontItalic(true);
149 formats[static_cast<std::size_t>(CodeSyntaxStyle::Directive)].setFontItalic(true);
150 rehighlight();
151}
152
153const QTextCharFormat& CodeSyntaxHighlighter::format(const CodeSyntaxStyle style) const
154{
155 return formats[static_cast<std::size_t>(style)];
156}
157
159CodeSyntaxHighlighter::findRegionEnd(const QString& text, const qsizetype from,
160 const CompiledRegionRule& region)
161{
162 qsizetype searchFrom = from;
163 while (searchFrom <= text.size()) {
164 const auto end = region.endExpression.match(text, searchFrom);
165 if (!end.hasMatch())
166 return {-1, -1};
167
168 if (region.skipExpression.isValid() && !region.skipExpression.pattern().isEmpty()) {
169 const auto skip = region.skipExpression.match(text, searchFrom);
170 if (skip.hasMatch() && skip.capturedStart() <= end.capturedStart()) {
171 const qsizetype next = skip.capturedEnd();
172 searchFrom = next > searchFrom ? next : searchFrom + 1;
173 continue;
174 }
175 }
176 return {end.capturedStart(), end.capturedEnd()};
177 }
178 return {-1, -1};
179}
180
182 const QString& text, const qsizetype start, const qsizetype end,
183 const std::vector<CompiledContainedRule>& rules)
184{
185 for (const auto& rule : rules) {
186 auto iterator = rule.expression.globalMatch(text, start);
187 while (iterator.hasNext()) {
188 const auto match = iterator.next();
189 if (match.capturedStart() >= end)
190 break;
191 const qsizetype matchEnd = std::min(match.capturedEnd(), end);
192 setFormat(match.capturedStart(), matchEnd - match.capturedStart(),
193 format(rule.style));
194 }
195 }
196}
197
199{
200 setCurrentBlockState(-1);
201 if (!syntax)
202 return;
203
204 for (const auto& group : keywordGroups) {
205 auto iterator = group.expression.globalMatch(text);
206 while (iterator.hasNext()) {
207 const auto match = iterator.next();
208 setFormat(match.capturedStart(), match.capturedLength(), format(group.style));
209 }
210 }
211 for (const auto& rule : matchRules) {
212 auto iterator = rule.expression.globalMatch(text);
213 while (iterator.hasNext()) {
214 const auto match = iterator.next();
215 setFormat(match.capturedStart(), match.capturedLength(), format(rule.style));
216 applyContainedRules(text, match.capturedStart(), match.capturedEnd(),
217 rule.containedRules);
218 }
219 }
220
221 qsizetype scanFrom = 0;
222 if (previousBlockState() > 0) {
223 const std::size_t index = static_cast<std::size_t>(previousBlockState() - 1);
224 if (index < regionRules.size()) {
225 const auto& region = regionRules[index];
226 const auto end = findRegionEnd(text, 0, region);
227 const qsizetype regionEnd = end.end < 0 ? text.size() : end.end;
228 setFormat(0, regionEnd, format(region.style));
229 applyContainedRules(text, 0, regionEnd, region.containedRules);
230 if (end.end < 0) {
231 setCurrentBlockState(previousBlockState());
232 return;
233 }
234 scanFrom = regionEnd;
235 }
236 }
237
238 while (scanFrom < text.size()) {
239 std::size_t selectedIndex = regionRules.size();
240 qsizetype selectedStart = text.size();
241 qsizetype selectedEnd = -1;
242 for (std::size_t index = 0; index < regionRules.size(); ++index) {
243 const auto match = regionRules[index].startExpression.match(text, scanFrom);
244 if (match.hasMatch() && match.capturedStart() < selectedStart) {
245 selectedIndex = index;
246 selectedStart = match.capturedStart();
247 selectedEnd = match.capturedEnd();
248 }
249 }
250 if (selectedIndex == regionRules.size())
251 break;
252
253 const auto& region = regionRules[selectedIndex];
254 const auto end = findRegionEnd(text, selectedEnd, region);
255 const qsizetype regionEnd = end.end < 0 ? text.size() : end.end;
256 setFormat(selectedStart, regionEnd - selectedStart, format(region.style));
257 applyContainedRules(text, selectedStart, regionEnd, region.containedRules);
258
259 if (end.end < 0 && region.multiline) {
260 setCurrentBlockState(static_cast<int>(selectedIndex + 1));
261 return;
262 }
263 if (regionEnd <= scanFrom)
264 ++scanFrom;
265 else
266 scanFrom = regionEnd;
267 }
268}
269
270} // namespace SILICON::ui
const QTextCharFormat & format(CodeSyntaxStyle style) const
void highlightBlock(const QString &text) override
static RegionEnd findRegionEnd(const QString &text, qsizetype from, const CompiledRegionRule &region)
std::array< QTextCharFormat, STYLE_COUNT > formats
void applyContainedRules(const QString &text, qsizetype start, qsizetype end, const std::vector< CompiledContainedRule > &rules)
std::vector< CompiledMatchRule > matchRules
std::vector< CompiledRegionRule > regionRules
CodeSyntaxHighlighter(QTextDocument *document)
void setSyntax(const CodeSyntax *syntax)
std::vector< CompiledKeywordGroup > keywordGroups
void setPalette(const QPalette &palette)
const Theme & dark()
Definition theme.cpp:137
const Theme & light()
Definition theme.cpp:133