-
-
Notifications
You must be signed in to change notification settings - Fork 88
/
markdownhighlighter.cpp
2685 lines (2375 loc) · 96.3 KB
/
markdownhighlighter.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* MIT License
*
* Copyright (c) 2014-2024 Patrizio Bekerle -- <[email protected]>
* Copyright (c) 2019-2021 Waqar Ahmed -- <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* QPlainTextEdit Markdown highlighter
*/
#include "markdownhighlighter.h"
#include <QDebug>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QRegularExpressionMatchIterator>
#include <QTextDocument>
#include <QTimer>
#include <utility>
#include "qownlanguagedata.h"
// We enable QStringView with Qt 5.15.14
// Note: QStringView::mid wasn't working correctly at least with 5.15.2
// and 5.15.3, but 5.15.14 was fine
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 14)
#define MH_SUBSTR(pos, len) text.midRef(pos, len)
#else
#define MH_SUBSTR(pos, len) QStringView(text).mid(pos, len)
#endif
QHash<QString, MarkdownHighlighter::HighlighterState>
MarkdownHighlighter::_langStringToEnum;
QHash<MarkdownHighlighter::HighlighterState, QTextCharFormat>
MarkdownHighlighter::_formats;
QVector<MarkdownHighlighter::HighlightingRule>
MarkdownHighlighter::_highlightingRules;
/**
* Markdown syntax highlighting
* @param parent
* @return
*/
MarkdownHighlighter::MarkdownHighlighter(
QTextDocument *parent, HighlightingOptions highlightingOptions)
: QSyntaxHighlighter(parent), _highlightingOptions(highlightingOptions) {
// _highlightingOptions = highlightingOptions;
_timer = new QTimer(this);
connect(_timer, &QTimer::timeout, this, &MarkdownHighlighter::timerTick);
_timer->start(1000);
// initialize the highlighting rules
initHighlightingRules();
// initialize the text formats
initTextFormats();
// initialize code languages
initCodeLangs();
}
/**
* Does jobs every second
*/
void MarkdownHighlighter::timerTick() {
// re-highlight all dirty blocks
reHighlightDirtyBlocks();
// emit a signal every second if there was some highlighting done
if (_highlightingFinished) {
_highlightingFinished = false;
Q_EMIT highlightingFinished();
}
}
/**
* Re-highlights all dirty blocks
*/
void MarkdownHighlighter::reHighlightDirtyBlocks() {
while (_dirtyTextBlocks.count() > 0) {
QTextBlock block = _dirtyTextBlocks.at(0);
rehighlightBlock(block);
_dirtyTextBlocks.removeFirst();
}
}
/**
* Clears the dirty blocks vector
*/
void MarkdownHighlighter::clearDirtyBlocks() {
_ranges.clear();
_dirtyTextBlocks.clear();
}
/**
* Adds a dirty block to the list if it doesn't already exist
*
* @param block
*/
void MarkdownHighlighter::addDirtyBlock(const QTextBlock &block) {
if (!_dirtyTextBlocks.contains(block)) {
_dirtyTextBlocks.append(block);
}
}
/**
* Initializes the highlighting rules
*
* regexp tester:
* https://regex101.com
*
* other examples:
* /usr/share/kde4/apps/katepart/syntax/markdown.xml
*/
void MarkdownHighlighter::initHighlightingRules() {
// highlight block quotes
{
HighlightingRule rule(HighlighterState::BlockQuote);
rule.pattern = QRegularExpression(
_highlightingOptions.testFlag(
HighlightingOption::FullyHighlightedBlockQuote)
? QStringLiteral("^\\s*(>\\s*.+)")
: QStringLiteral("^\\s*(>\\s*)+"));
rule.shouldContain = QStringLiteral("> ");
_highlightingRules.append(rule);
}
// highlight tables without starting |
// we drop that for now, it's far too messy to deal with
// rule = HighlightingRule();
// rule.pattern = QRegularExpression("^.+? \\| .+? \\| .+$");
// rule.state = HighlighterState::Table;
// _highlightingRulesPre.append(rule);
// highlight trailing spaces
{
HighlightingRule rule(HighlighterState::TrailingSpace);
rule.pattern = QRegularExpression(QStringLiteral("( +)$"));
rule.shouldContain = QStringLiteral(" ");
rule.capturingGroup = 1;
_highlightingRules.append(rule);
}
// highlight inline comments
{
// highlight comments for R Markdown for academic papers
HighlightingRule rule(HighlighterState::Comment);
rule.pattern =
QRegularExpression(QStringLiteral(R"(^\[.+?\]: # \(.+?\)$)"));
rule.shouldContain = QStringLiteral("]: # (");
_highlightingRules.append(rule);
}
// highlight tables with starting |
{
HighlightingRule rule(HighlighterState::Table);
rule.shouldContain = QStringLiteral("|");
// Support up to 3 leading spaces, because md4c seems to support it
// See https://github.com/pbek/QOwnNotes/issues/3137
rule.pattern = QRegularExpression(QStringLiteral("^\\s{0,3}(\\|.+?\\|)$"));
rule.capturingGroup = 1;
_highlightingRules.append(rule);
}
}
/**
* Initializes the text formats
*
* @param defaultFontSize
*/
void MarkdownHighlighter::initTextFormats(int defaultFontSize) {
QTextCharFormat format;
// set character formats for headlines
format = QTextCharFormat();
format.setForeground(QColor(2, 69, 150));
format.setFontWeight(QFont::Bold);
format.setFontPointSize(defaultFontSize * 1.6);
_formats[H1] = format;
format.setFontPointSize(defaultFontSize * 1.5);
_formats[H2] = format;
format.setFontPointSize(defaultFontSize * 1.4);
_formats[H3] = format;
format.setFontPointSize(defaultFontSize * 1.3);
_formats[H4] = format;
format.setFontPointSize(defaultFontSize * 1.2);
_formats[H5] = format;
format.setFontPointSize(defaultFontSize * 1.1);
_formats[H6] = format;
format.setFontPointSize(defaultFontSize);
// set character format for horizontal rulers
format = QTextCharFormat();
format.setForeground(Qt::darkGray);
format.setBackground(Qt::lightGray);
_formats[HorizontalRuler] = std::move(format);
// set character format for lists
format = QTextCharFormat();
format.setForeground(QColor(163, 0, 123));
_formats[List] = format;
// set character format for checkbox
format = QTextCharFormat();
format.setForeground(QColor(123, 100, 223));
_formats[CheckBoxUnChecked] = std::move(format);
// set character format for checked checkbox
format = QTextCharFormat();
format.setForeground(QColor(223, 50, 123));
_formats[CheckBoxChecked] = std::move(format);
// set character format for links
format = QTextCharFormat();
format.setForeground(QColor(0, 128, 255));
format.setFontUnderline(true);
_formats[Link] = std::move(format);
// set character format for images
format = QTextCharFormat();
format.setForeground(QColor(0, 191, 0));
format.setBackground(QColor(228, 255, 228));
_formats[Image] = std::move(format);
// set character format for code blocks
format = QTextCharFormat();
format.setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
// format.setBackground(QColor(220, 220, 220));
_formats[CodeBlock] = format;
_formats[InlineCodeBlock] = format;
// set character format for italic
format = QTextCharFormat();
format.setFontWeight(QFont::StyleItalic);
format.setFontItalic(true);
_formats[Italic] = std::move(format);
// set character format for underline
format = QTextCharFormat();
format.setFontUnderline(true);
_formats[StUnderline] = std::move(format);
// set character format for bold
format = QTextCharFormat();
format.setFontWeight(QFont::Bold);
_formats[Bold] = std::move(format);
// set character format for comments
format = QTextCharFormat();
format.setForeground(QBrush(Qt::gray));
_formats[Comment] = std::move(format);
// set character format for masked syntax
format = QTextCharFormat();
format.setForeground(QColor(204, 204, 204));
_formats[MaskedSyntax] = std::move(format);
// set character format for tables
format = QTextCharFormat();
format.setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
format.setForeground(QColor(100, 148, 73));
_formats[Table] = std::move(format);
// set character format for block quotes
format = QTextCharFormat();
format.setForeground(Qt::darkRed);
_formats[BlockQuote] = std::move(format);
format = QTextCharFormat();
_formats[HeadlineEnd] = std::move(format);
_formats[NoState] = std::move(format);
// set character format for trailing spaces
format.setBackground(QColor(252, 175, 62));
_formats[TrailingSpace] = std::move(format);
/****************************************
* Formats for syntax highlighting
***************************************/
format = QTextCharFormat();
format.setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
format.setForeground(QColor(249, 38, 114));
_formats[CodeKeyWord] = std::move(format);
format = QTextCharFormat();
format.setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
format.setForeground(QColor(163, 155, 78));
_formats[CodeString] = std::move(format);
format = QTextCharFormat();
format.setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
format.setForeground(QColor(117, 113, 94));
_formats[CodeComment] = std::move(format);
format = QTextCharFormat();
format.setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
format.setForeground(QColor(84, 174, 191));
_formats[CodeType] = std::move(format);
format = QTextCharFormat();
format.setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
format.setForeground(QColor(219, 135, 68));
_formats[CodeOther] = std::move(format);
format = QTextCharFormat();
format.setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
format.setForeground(QColor(174, 129, 255));
_formats[CodeNumLiteral] = std::move(format);
format = QTextCharFormat();
format.setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
format.setForeground(QColor(1, 138, 15));
_formats[CodeBuiltIn] = std::move(format);
}
/**
* @brief initializes the langStringToEnum
*/
void MarkdownHighlighter::initCodeLangs() {
MarkdownHighlighter::_langStringToEnum =
QHash<QString, MarkdownHighlighter::HighlighterState>{
{QLatin1String("bash"), MarkdownHighlighter::CodeBash},
{QLatin1String("c"), MarkdownHighlighter::CodeC},
{QLatin1String("cpp"), MarkdownHighlighter::CodeCpp},
{QLatin1String("cxx"), MarkdownHighlighter::CodeCpp},
{QLatin1String("c++"), MarkdownHighlighter::CodeCpp},
{QLatin1String("c#"), MarkdownHighlighter::CodeCSharp},
{QLatin1String("cmake"), MarkdownHighlighter::CodeCMake},
{QLatin1String("csharp"), MarkdownHighlighter::CodeCSharp},
{QLatin1String("css"), MarkdownHighlighter::CodeCSS},
{QLatin1String("go"), MarkdownHighlighter::CodeGo},
{QLatin1String("html"), MarkdownHighlighter::CodeXML},
{QLatin1String("ini"), MarkdownHighlighter::CodeINI},
{QLatin1String("java"), MarkdownHighlighter::CodeJava},
{QLatin1String("javascript"), MarkdownHighlighter::CodeJava},
{QLatin1String("js"), MarkdownHighlighter::CodeJs},
{QLatin1String("json"), MarkdownHighlighter::CodeJSON},
{QLatin1String("make"), MarkdownHighlighter::CodeMake},
{QLatin1String("nix"), MarkdownHighlighter::CodeNix},
{QLatin1String("php"), MarkdownHighlighter::CodePHP},
{QLatin1String("py"), MarkdownHighlighter::CodePython},
{QLatin1String("python"), MarkdownHighlighter::CodePython},
{QLatin1String("qml"), MarkdownHighlighter::CodeQML},
{QLatin1String("rust"), MarkdownHighlighter::CodeRust},
{QLatin1String("sh"), MarkdownHighlighter::CodeBash},
{QLatin1String("sql"), MarkdownHighlighter::CodeSQL},
{QLatin1String("taggerscript"),
MarkdownHighlighter::CodeTaggerScript},
{QLatin1String("ts"), MarkdownHighlighter::CodeTypeScript},
{QLatin1String("typescript"), MarkdownHighlighter::CodeTypeScript},
{QLatin1String("v"), MarkdownHighlighter::CodeV},
{QLatin1String("vex"), MarkdownHighlighter::CodeVex},
{QLatin1String("xml"), MarkdownHighlighter::CodeXML},
{QLatin1String("yml"), MarkdownHighlighter::CodeYAML},
{QLatin1String("yaml"), MarkdownHighlighter::CodeYAML},
{QLatin1String("forth"), MarkdownHighlighter::CodeForth},
{QLatin1String("systemverilog"),
MarkdownHighlighter::CodeSystemVerilog}};
}
/**
* Sets the text formats
*
* @param formats
*/
void MarkdownHighlighter::setTextFormats(
QHash<HighlighterState, QTextCharFormat> formats) {
_formats = std::move(formats);
}
/**
* Sets a text format
*
* @param formats
*/
void MarkdownHighlighter::setTextFormat(HighlighterState state,
QTextCharFormat format) {
_formats[state] = std::move(format);
}
/**
* Does the Markdown highlighting
*
* @param text
*/
void MarkdownHighlighter::highlightBlock(const QString &text) {
if (currentBlockState() == HeadlineEnd) {
currentBlock().previous().setUserState(NoState);
addDirtyBlock(currentBlock().previous());
}
setCurrentBlockState(HighlighterState::NoState);
currentBlock().setUserState(HighlighterState::NoState);
highlightMarkdown(text);
_highlightingFinished = true;
}
void MarkdownHighlighter::highlightMarkdown(const QString &text) {
const bool isBlockCodeBlock = isCodeBlock(previousBlockState()) ||
text.startsWith(QLatin1String("```")) ||
text.startsWith(QLatin1String("~~~"));
if (!text.isEmpty() && !isBlockCodeBlock) {
highlightAdditionalRules(_highlightingRules, text);
highlightThematicBreak(text);
// needs to be called after the horizontal ruler highlighting
highlightHeadline(text);
highlightIndentedCodeBlock(text);
highlightLists(text);
highlightInlineRules(text);
}
highlightCommentBlock(text);
if (isBlockCodeBlock) highlightCodeFence(text);
highlightFrontmatterBlock(text);
}
/**
* @brief gets indentation(spaces) of text
* @param text
* @return 1, if 1 space, 2 if 2 spaces, 3 if 3 spaces. Otherwise 0
*/
static int getIndentation(const QString &text) {
int spaces = 0;
// no more than 3 spaces
while (spaces < 4 && spaces < text.length() &&
text.at(spaces) == QLatin1Char(' '))
++spaces;
return spaces;
}
static bool isParagraph(const QString &text) {
// blank line
if (text.isEmpty()) return false;
int indent = getIndentation(text);
// code block
if (indent >= 4) return false;
const auto textView = MH_SUBSTR(indent, -1);
if (textView.isEmpty()) return false;
// unordered listtextView
if (textView.startsWith(QStringLiteral("- ")) ||
textView.startsWith(QStringLiteral("+ ")) ||
textView.startsWith(QStringLiteral("* "))) {
return false;
}
// block quote
if (textView.startsWith(QStringLiteral("> "))) return false;
// atx heading
if (textView.startsWith(QStringLiteral("#"))) {
int firstSpace = textView.indexOf(' ');
if (firstSpace > 0 && firstSpace <= 7) {
return false;
}
}
// hr
auto isThematicBreak = [textView]() {
return std::all_of(textView.begin(), textView.end(),
[](QChar c) {
auto ch = c.unicode();
return ch == '-' || ch == ' ' || ch == '\t';
}) ||
std::all_of(textView.begin(), textView.end(),
[](QChar c) {
auto ch = c.unicode();
return ch == '+' || ch == ' ' || ch == '\t';
}) ||
std::all_of(textView.begin(), textView.end(), [](QChar c) {
auto ch = c.unicode();
return ch == '*' || ch == ' ' || ch == '\t';
});
};
if (isThematicBreak()) return false;
// ordered list
if (textView.at(0).isDigit()) {
int i = 1;
int count = 1;
for (; i < textView.size(); ++i) {
if (textView[i].isDigit()) {
count++;
continue;
} else
break;
}
// ordered list marker can't be more than 9 numbers
if (count <= 9 && i + 1 < textView.size() &&
(textView[i] == QLatin1Char('.') ||
textView[i] == QLatin1Char(')')) &&
textView[i + 1] == QLatin1Char(' ')) {
return false;
}
}
return true;
}
/**
* Highlight headlines
*
* @param text
*/
void MarkdownHighlighter::highlightHeadline(const QString &text) {
// three spaces indentation is allowed in headings
const int spacesOffset = getIndentation(text);
if (spacesOffset >= text.length() || spacesOffset == 4) return;
const bool headingFound = text.at(spacesOffset) == QLatin1Char('#');
if (headingFound) {
int headingLevel = 0;
int i = spacesOffset;
if (i >= text.length()) return;
while (i < text.length() && text.at(i) == QLatin1Char('#') &&
i < (spacesOffset + 6))
++i;
if (i < text.length() && text.at(i) == QLatin1Char(' '))
headingLevel = i - spacesOffset;
if (headingLevel > 0) {
const auto state =
HighlighterState(HighlighterState::H1 + headingLevel - 1);
// Set styling of the "#"s to "masked syntax", but with the size of
// the heading
auto maskedFormat = _formats[MaskedSyntax];
maskedFormat.setFontPointSize(_formats[state].fontPointSize());
setFormat(0, headingLevel, maskedFormat);
// Set the styling of the rest of the heading
setFormat(headingLevel + 1, text.length() - 1 - headingLevel,
_formats[state]);
setCurrentBlockState(state);
return;
}
}
auto hasOnlyHeadChars = [](const QString &txt, const QChar c,
int spaces) -> bool {
if (txt.isEmpty()) return false;
for (int i = spaces; i < txt.length(); ++i) {
if (txt.at(i) != c) return false;
}
return true;
};
// take care of ==== and ---- headlines
const QString prev = currentBlock().previous().text();
auto prevSpaces = getIndentation(prev);
const bool isPrevParagraph = isParagraph(prev);
if (text.at(spacesOffset) == QLatin1Char('=') && prevSpaces < 4 &&
isPrevParagraph) {
const bool pattern1 =
!prev.isEmpty() &&
hasOnlyHeadChars(text, QLatin1Char('='), spacesOffset);
if (pattern1) {
highlightSubHeadline(text, H1);
return;
}
} else if (text.at(spacesOffset) == QLatin1Char('-') && prevSpaces < 4 &&
isPrevParagraph) {
const bool pattern2 =
!prev.isEmpty() &&
hasOnlyHeadChars(text, QLatin1Char('-'), spacesOffset);
if (pattern2) {
highlightSubHeadline(text, H2);
return;
}
}
const QString nextBlockText = currentBlock().next().text();
if (nextBlockText.isEmpty()) return;
const int nextSpaces = getIndentation(nextBlockText);
const bool isCurrentParagraph = isParagraph(text);
if (nextSpaces >= nextBlockText.length()) return;
if (nextBlockText.at(nextSpaces) == QLatin1Char('=') && nextSpaces < 4 &&
isCurrentParagraph) {
const bool nextHasEqualChars =
hasOnlyHeadChars(nextBlockText, QLatin1Char('='), nextSpaces);
if (nextHasEqualChars) {
setFormat(0, text.length(), _formats[HighlighterState::H1]);
setCurrentBlockState(HighlighterState::H1);
}
} else if (nextBlockText.at(nextSpaces) == QLatin1Char('-') &&
nextSpaces < 4 && isCurrentParagraph) {
const bool nextHasMinusChars =
hasOnlyHeadChars(nextBlockText, QLatin1Char('-'), nextSpaces);
if (nextHasMinusChars) {
setFormat(0, text.length(), _formats[HighlighterState::H2]);
setCurrentBlockState(HighlighterState::H2);
}
}
}
void MarkdownHighlighter::highlightSubHeadline(const QString &text,
HighlighterState state) {
const QTextCharFormat &maskedFormat =
_formats[HighlighterState::MaskedSyntax];
QTextBlock previousBlock = currentBlock().previous();
// we check for both H1/H2 so that if the user changes his mind, and changes
// === to ---, changes be reflected immediately
if (previousBlockState() == H1 || previousBlockState() == H2 ||
previousBlockState() == NoState) {
QTextCharFormat currentMaskedFormat = maskedFormat;
// set the font size from the current rule's font format
currentMaskedFormat.setFontPointSize(_formats[state].fontPointSize());
setFormat(0, text.length(), currentMaskedFormat);
setCurrentBlockState(HeadlineEnd);
// we want to re-highlight the previous block
// this must not be done directly, but with a queue, otherwise it
// will crash
// setting the character format of the previous text, because this
// causes text to be formatted the same way when writing after
// the text
if (previousBlockState() != state) {
addDirtyBlock(previousBlock);
previousBlock.setUserState(state);
}
}
}
/**
* @brief highlight code blocks with four spaces or tabs in front of them
* and no list character after that
* @param text
*/
void MarkdownHighlighter::highlightIndentedCodeBlock(const QString &text) {
if (text.isEmpty() || (!text.startsWith(QLatin1String(" ")) &&
!text.startsWith(QLatin1Char('\t'))))
return;
const QString prevTrimmed = currentBlock().previous().text().trimmed();
// previous line must be empty according to CommonMark except if it is a
// heading https://spec.commonmark.org/0.29/#indented-code-block
if (!prevTrimmed.isEmpty() && previousBlockState() != CodeBlockIndented &&
!isHeading(previousBlockState()) && previousBlockState() != HeadlineEnd)
return;
const QString trimmed = text.trimmed();
// should not be in a list
if (trimmed.startsWith(QLatin1String("- ")) ||
trimmed.startsWith(QLatin1String("+ ")) ||
trimmed.startsWith(QLatin1String("* ")) ||
(trimmed.length() >= 1 && trimmed.at(0).isNumber()))
return;
setCurrentBlockState(CodeBlockIndented);
setFormat(0, text.length(), _formats[CodeBlock]);
}
void MarkdownHighlighter::highlightCodeFence(const QString &text) {
// already in tilde block
if ((previousBlockState() == CodeBlockTilde ||
previousBlockState() == CodeBlockTildeComment ||
previousBlockState() >= CodeCpp + tildeOffset)) {
highlightCodeBlock(text, QStringLiteral("~~~"));
// start of a tilde block
} else if ((previousBlockState() != CodeBlock &&
previousBlockState() < CodeCpp) &&
text.startsWith(QLatin1String("~~~"))) {
highlightCodeBlock(text, QStringLiteral("~~~"));
} else {
// back tick block
highlightCodeBlock(text);
}
}
/**
* Highlight multi-line code blocks
*
* @param text
*/
void MarkdownHighlighter::highlightCodeBlock(const QString &text,
const QString &opener) {
if (text.startsWith(opener)) {
// if someone decides to put these on the same line
// interpret it as inline code, not code block
if (text.endsWith(QLatin1String("```")) && text.length() > 3) {
setFormat(3, text.length() - 3,
_formats[HighlighterState::InlineCodeBlock]);
setFormat(0, 3, _formats[HighlighterState::MaskedSyntax]);
setFormat(text.length() - 3, 3,
_formats[HighlighterState::MaskedSyntax]);
return;
}
if ((previousBlockState() != CodeBlock &&
previousBlockState() != CodeBlockTilde) &&
(previousBlockState() != CodeBlockComment &&
previousBlockState() != CodeBlockTildeComment) &&
previousBlockState() < CodeCpp) {
const QString &lang = text.mid(3, text.length()).toLower();
HighlighterState progLang = _langStringToEnum.value(lang);
if (progLang >= CodeCpp) {
const int state = text.startsWith(QLatin1String("```"))
? progLang
: progLang + tildeOffset;
setCurrentBlockState(state);
} else {
const int state =
opener == QLatin1String("```") ? CodeBlock : CodeBlockTilde;
setCurrentBlockState(state);
}
} else if (isCodeBlock(previousBlockState())) {
const int state = opener == QLatin1String("```")
? CodeBlockEnd
: CodeBlockTildeEnd;
setCurrentBlockState(state);
}
// set the font size from the current rule's font format
QTextCharFormat &maskedFormat = _formats[MaskedSyntax];
maskedFormat.setFontPointSize(_formats[CodeBlock].fontPointSize());
setFormat(0, text.length(), maskedFormat);
} else if (isCodeBlock(previousBlockState())) {
setCurrentBlockState(previousBlockState());
highlightSyntax(text);
}
}
/**
* @brief Does the code syntax highlighting
* @param text
*/
void MarkdownHighlighter::highlightSyntax(const QString &text) {
if (text.isEmpty()) return;
const auto textLen = text.length();
QChar comment;
bool isCSS = false;
bool isYAML = false;
bool isMake = false;
bool isForth = false;
QMultiHash<char, QLatin1String> keywords{};
QMultiHash<char, QLatin1String> others{};
QMultiHash<char, QLatin1String> types{};
QMultiHash<char, QLatin1String> builtin{};
QMultiHash<char, QLatin1String> literals{};
// apply the default code block format first
setFormat(0, textLen, _formats[CodeBlock]);
switch (currentBlockState()) {
case HighlighterState::CodeCpp:
case HighlighterState::CodeCpp + tildeOffset:
case HighlighterState::CodeCppComment:
case HighlighterState::CodeCppComment + tildeOffset:
loadCppData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeJs:
case HighlighterState::CodeJs + tildeOffset:
case HighlighterState::CodeJsComment:
case HighlighterState::CodeJsComment + tildeOffset:
loadJSData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeC:
case HighlighterState::CodeC + tildeOffset:
case HighlighterState::CodeCComment:
case HighlighterState::CodeCComment + tildeOffset:
loadCppData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeBash:
case HighlighterState::CodeBash + tildeOffset:
loadShellData(types, keywords, builtin, literals, others);
comment = QLatin1Char('#');
break;
case HighlighterState::CodePHP:
case HighlighterState::CodePHP + tildeOffset:
case HighlighterState::CodePHPComment:
case HighlighterState::CodePHPComment + tildeOffset:
loadPHPData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeQML:
case HighlighterState::CodeQML + tildeOffset:
case HighlighterState::CodeQMLComment:
case HighlighterState::CodeQMLComment + tildeOffset:
loadQMLData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodePython:
case HighlighterState::CodePython + tildeOffset:
loadPythonData(types, keywords, builtin, literals, others);
comment = QLatin1Char('#');
break;
case HighlighterState::CodeRust:
case HighlighterState::CodeRust + tildeOffset:
case HighlighterState::CodeRustComment:
case HighlighterState::CodeRustComment + tildeOffset:
loadRustData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeJava:
case HighlighterState::CodeJava + tildeOffset:
case HighlighterState::CodeJavaComment:
case HighlighterState::CodeJavaComment + tildeOffset:
loadJavaData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeCSharp:
case HighlighterState::CodeCSharp + tildeOffset:
case HighlighterState::CodeCSharpComment:
case HighlighterState::CodeCSharpComment + tildeOffset:
loadCSharpData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeGo:
case HighlighterState::CodeGo + tildeOffset:
case HighlighterState::CodeGoComment:
case HighlighterState::CodeGoComment + tildeOffset:
loadGoData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeV:
case HighlighterState::CodeV + tildeOffset:
case HighlighterState::CodeVComment:
case HighlighterState::CodeVComment + tildeOffset:
loadVData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeSQL:
case HighlighterState::CodeSQL + tildeOffset:
loadSQLData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeJSON:
case HighlighterState::CodeJSON + tildeOffset:
loadJSONData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeXML:
case HighlighterState::CodeXML + tildeOffset:
xmlHighlighter(text);
return;
case HighlighterState::CodeCSS:
case HighlighterState::CodeCSS + tildeOffset:
case HighlighterState::CodeCSSComment:
case HighlighterState::CodeCSSComment + tildeOffset:
isCSS = true;
loadCSSData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeTypeScript:
case HighlighterState::CodeTypeScript + tildeOffset:
case HighlighterState::CodeTypeScriptComment:
case HighlighterState::CodeTypeScriptComment + tildeOffset:
loadTypescriptData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeYAML:
case HighlighterState::CodeYAML + tildeOffset:
isYAML = true;
comment = QLatin1Char('#');
loadYAMLData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeINI:
case HighlighterState::CodeINI + tildeOffset:
iniHighlighter(text);
return;
case HighlighterState::CodeTaggerScript:
case HighlighterState::CodeTaggerScript + tildeOffset:
taggerScriptHighlighter(text);
return;
case HighlighterState::CodeVex:
case HighlighterState::CodeVex + tildeOffset:
case HighlighterState::CodeVexComment:
case HighlighterState::CodeVexComment + tildeOffset:
loadVEXData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeCMake:
case HighlighterState::CodeCMake + tildeOffset:
loadCMakeData(types, keywords, builtin, literals, others);
comment = QLatin1Char('#');
break;
case HighlighterState::CodeMake:
case HighlighterState::CodeMake + tildeOffset:
isMake = true;
loadMakeData(types, keywords, builtin, literals, others);
comment = QLatin1Char('#');
break;
case HighlighterState::CodeNix:
case HighlighterState::CodeNix + tildeOffset:
loadNixData(types, keywords, builtin, literals, others);
comment = QLatin1Char('#');
break;
case HighlighterState::CodeForth:
case HighlighterState::CodeForth + tildeOffset:
case HighlighterState::CodeForthComment:
case HighlighterState::CodeForthComment + tildeOffset:
isForth = true;
loadForthData(types, keywords, builtin, literals, others);
break;
case HighlighterState::CodeSystemVerilog:
case HighlighterState::CodeSystemVerilogComment:
loadSystemVerilogData(types, keywords, builtin, literals, others);
break;
default:
setFormat(0, textLen, _formats[CodeBlock]);
return;
}
auto applyCodeFormat =
[this](int i, const QMultiHash<char, QLatin1String> &data,
const QString &text, const QTextCharFormat &fmt) -> int {
// check if we are at the beginning OR if this is the start of a word
if (i == 0 || (!text.at(i - 1).isLetterOrNumber() &&
text.at(i - 1) != QLatin1Char('_'))) {
const char c = text.at(i).toLatin1();
auto it = data.find(c);
for (; it != data.end() && it.key() == c; ++it) {
// we have a word match check
// 1. if we are at the end
// 2. if we have a complete word
const QLatin1String &word = it.value();
if (word == MH_SUBSTR(i, word.size()) &&
(i + word.size() == text.length() ||
(!text.at(i + word.size()).isLetterOrNumber() &&
text.at(i + word.size()) != QLatin1Char('_')))) {
setFormat(i, word.size(), fmt);
i += word.size();
}
}
}
return i;
};
const QTextCharFormat &formatType = _formats[CodeType];
const QTextCharFormat &formatKeyword = _formats[CodeKeyWord];
const QTextCharFormat &formatComment = _formats[CodeComment];
const QTextCharFormat &formatNumLit = _formats[CodeNumLiteral];
const QTextCharFormat &formatBuiltIn = _formats[CodeBuiltIn];
const QTextCharFormat &formatOther = _formats[CodeOther];
for (int i = 0; i < textLen; ++i) {
if (currentBlockState() != -1 && currentBlockState() % 2 != 0)
goto Comment;
while (i < textLen && !text[i].isLetter()) {
if (text[i].isSpace()) {
++i;
// make sure we don't cross the bound
if (i == textLen) break;
if (text[i].isLetter()) break;
continue;
}
// inline comment
if (comment.isNull() && text[i] == QLatin1Char('/')) {
if ((i + 1) < textLen) {
if (text[i + 1] == QLatin1Char('/')) {
setFormat(i, textLen, formatComment);
return;
} else if (text[i + 1] == QLatin1Char('*')) {
Comment:
int next = text.indexOf(QLatin1String("*/"), i);
if (next == -1) {
// we didn't find a comment end.
// Check if we are already in a comment block
if (currentBlockState() % 2 == 0)
setCurrentBlockState(currentBlockState() + 1);
setFormat(i, textLen, formatComment);
return;
} else {
// we found a comment end
// mark this block as code if it was previously
// comment. First check if the comment ended on the
// same line. if modulo 2 is not equal to zero, it
// means we are in a comment, -1 will set this
// block's state as language
if (currentBlockState() % 2 != 0) {
setCurrentBlockState(currentBlockState() - 1);
}
next += 2;
setFormat(i, next - i, formatComment);
i = next;