| 1 | // QCodeEditor |
| 2 | #include <QJSONHighlighter> |
| 3 | #include <QSyntaxStyle> |
| 4 | |
| 5 | |
| 6 | QJSONHighlighter::QJSONHighlighter(QTextDocument* document) : |
| 7 | QStyleSyntaxHighlighter(document), |
| 8 | m_highlightRules(), |
| 9 | m_keyRegex(R"(("[^\r\n:]+?")\s*:)") |
| 10 | { |
| 11 | auto keywords = QStringList() |
| 12 | << "null" << "true" << "false"; |
| 13 | |
| 14 | for (auto&& keyword : keywords) |
| 15 | { |
| 16 | m_highlightRules.append({ |
| 17 | QRegularExpression(QString(R"(\b%1\b)").arg(keyword)), |
| 18 | "Keyword" |
| 19 | }); |
| 20 | } |
| 21 | |
| 22 | // Numbers |
| 23 | m_highlightRules.append({ |
| 24 | QRegularExpression(R"(\b(0b|0x){0,1}[\d.']+\b)"), |
| 25 | "Number" |
| 26 | }); |
| 27 | |
| 28 | // Strings |
| 29 | m_highlightRules.append({ |
| 30 | QRegularExpression(R"("[^\n"]*")"), |
| 31 | "String" |
| 32 | }); |
| 33 | } |
| 34 | |
| 35 | void QJSONHighlighter::highlightBlock(const QString& text) |
| 36 | { |
| 37 | for (auto&& rule : m_highlightRules) |
| 38 | { |
| 39 | auto matchIterator = rule.pattern.globalMatch(text); |
| 40 | |
| 41 | while (matchIterator.hasNext()) |
| 42 | { |
| 43 | auto match = matchIterator.next(); |
| 44 | |
| 45 | setFormat( |
| 46 | match.capturedStart(), |
| 47 | match.capturedLength(), |
| 48 | syntaxStyle()->getFormat(rule.formatName) |
| 49 | ); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | // Special treatment for key regex |
| 54 | auto matchIterator = m_keyRegex.globalMatch(text); |
| 55 | |
| 56 | while (matchIterator.hasNext()) |
| 57 | { |
| 58 | auto match = matchIterator.next(); |
| 59 | |
| 60 | setFormat( |
| 61 | match.capturedStart(1), |
| 62 | match.capturedLength(1), |
| 63 | syntaxStyle()->getFormat("Keyword") |
| 64 | ); |
| 65 | } |
| 66 | } |