1 #include <QtGui>
2 
3 #include "common/MdHighlighter.h"
4 
MdHighlighter(QTextDocument * parent)5 MdHighlighter::MdHighlighter(QTextDocument *parent)
6     : QSyntaxHighlighter(parent)
7 {
8     HighlightingRule rule;
9 
10     keywordFormat.setForeground(Qt::gray);
11     keywordFormat.setFontWeight(QFont::Bold);
12 
13     QStringList keywordPatterns;
14     keywordPatterns << "^\\#{1,6}[ A-Za-z]+\\b" << "\\*\\*([^\\\\]+)\\*\\*"
15                     << "\\*([^\\\\]+)\\*" << "\\_([^\\\\]+)\\_"
16                     << "\\_\\_([^\\\\]+)\\_\\_";
17 
18     for (const QString &pattern : keywordPatterns) {
19         rule.pattern.setPattern(pattern);
20         rule.format = keywordFormat;
21         highlightingRules.append(rule);
22     }
23 
24     singleLineCommentFormat.setFontWeight(QFont::Bold);
25     singleLineCommentFormat.setForeground(Qt::darkGreen);
26     rule.pattern.setPattern(";[^\n]*");
27     rule.format = singleLineCommentFormat;
28     highlightingRules.append(rule);
29 }
30 
highlightBlock(const QString & text)31 void MdHighlighter::highlightBlock(const QString &text)
32 {
33     for (const HighlightingRule &rule : highlightingRules) {
34         QRegularExpression expression(rule.pattern);
35         int index = expression.match(text).capturedStart();
36         while (index >= 0) {
37             int length = expression.match(text).capturedLength();
38             setFormat(index, length, rule.format);
39             index = expression.match(text.mid(index + length)).capturedStart();
40         }
41     }
42     setCurrentBlockState(0);
43 }
44