|
| 1 | +#include "Syntax.h" |
| 2 | + |
| 3 | +Syntax::Syntax(QTextDocument *parent) : QSyntaxHighlighter(parent) |
| 4 | +{ |
| 5 | + keywordFormat.setForeground(Qt::blue); |
| 6 | + keywordFormat.setFontWeight(QFont::Bold); |
| 7 | + QStringList keywordPatterns; |
| 8 | + keywordPatterns << "\\bchar\\b" << "\\bclass\\b" << "\\bconst\\b" |
| 9 | + << "\\bdouble\\b" << "\\benum\\b" << "\\bexplicit\\b" |
| 10 | + << "\\bfriend\\b" << "\\binline\\b" << "\\bint\\b" |
| 11 | + << "\\blong\\b" << "\\bnamespace\\b" << "\\boperator\\b" |
| 12 | + << "\\bprivate\\b" << "\\bprotected\\b" << "\\bpublic\\b" |
| 13 | + << "\\bshort\\b" << "\\bsignals\\b" << "\\bsigned\\b" |
| 14 | + << "\\bslots\\b" << "\\bstatic\\b" << "\\bstruct\\b" |
| 15 | + << "\\btemplate\\b" << "\\btypedef\\b" << "\\btypename\\b" |
| 16 | + << "\\bunion\\b" << "\\bunsigned\\b" << "\\bvirtual\\b" |
| 17 | + << "\\bvoid\\b" << "\\bvolatile\\b" << "\\bforeach\\b"; |
| 18 | + foreach (const QString &pattern, keywordPatterns) |
| 19 | + { |
| 20 | + addPattern(pattern, keywordFormat); |
| 21 | + } |
| 22 | + |
| 23 | + // Single line comment format expression |
| 24 | + singleLineCommentFormat.setForeground(Qt::darkGray); |
| 25 | + addPattern("//[^\n]*", singleLineCommentFormat); |
| 26 | + |
| 27 | + // Double quotation mark for string |
| 28 | + quotationMark.setForeground(Qt::darkGreen); |
| 29 | + addPattern("\".*\"", quotationMark); |
| 30 | + |
| 31 | + // Function format expression |
| 32 | + functionFormat.setFontItalic(true); |
| 33 | + functionFormat.setForeground(Qt::darkYellow); |
| 34 | + addPattern("\\b[a-zA-Z_][a-zA-Z0-9_]*(?=\\s*\\()", functionFormat); |
| 35 | + |
| 36 | + // Color pattern for parenthesis |
| 37 | + QColor parenthesisColor("#6495ED"); |
| 38 | + parenthesisFormat.setForeground(parenthesisColor); |
| 39 | + addPattern("[()]", parenthesisFormat); |
| 40 | + |
| 41 | + // Regex for single character format 'a', '\n', etc |
| 42 | + charFormat.setForeground(Qt::darkCyan); |
| 43 | + addPattern("'(\\\\.|[^'])'", charFormat); |
| 44 | +} |
| 45 | + |
| 46 | +// Add syntax highlighting patterns |
| 47 | +void Syntax::addPattern(const QString &pattern, const QTextCharFormat &format) |
| 48 | +{ |
| 49 | + SyntaxRule rule; |
| 50 | + rule.pattern = QRegularExpression(pattern); |
| 51 | + rule.format = format; |
| 52 | + syntaxRules.append(rule); |
| 53 | +} |
| 54 | + |
| 55 | +void Syntax::highlightBlock(const QString &text) |
| 56 | +{ |
| 57 | + foreach (const SyntaxRule &rule, syntaxRules) |
| 58 | + { |
| 59 | + QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text); |
| 60 | + while (matchIterator.hasNext()) |
| 61 | + { |
| 62 | + QRegularExpressionMatch match = matchIterator.next(); |
| 63 | + setFormat(match.capturedStart(), match.capturedLength(), rule.format); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments