File: PythonSyntaxHighlighter.cpp

package info (click to toggle)
bornagain 23.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 103,936 kB
  • sloc: cpp: 423,131; python: 40,997; javascript: 11,167; awk: 630; sh: 318; ruby: 173; xml: 130; makefile: 51; ansic: 24
file content (250 lines) | stat: -rw-r--r-- 10,384 bytes parent folder | download | duplicates (2)
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
//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Info/PythonSyntaxHighlighter.cpp
//! @brief     Implements class PythonSyntaxHighlighter.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

/*
This is a C++ port of the following PyQt example
http://diotavelli.net/PyQtWiki/Python%20syntax%20highlighting
C++ port by Frankie Simon (docklight.de, www.fuh-edv.de)

The following free software license applies for this file ("X11 license"):

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 X CONSORTIUM 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.
*/

#include "GUI/View/Info/PythonSyntaxHighlighter.h"

PythonSyntaxHighlighter::PythonSyntaxHighlighter(QTextDocument* parent)
    : QSyntaxHighlighter(parent)
{
    keywords = QStringList() << "and"
                             << "assert"
                             << "break"
                             << "class"
                             << "continue"
                             << "def"
                             << "del"
                             << "elif"
                             << "else"
                             << "except"
                             << "exec"
                             << "finally"
                             << "for"
                             << "from"
                             << "global"
                             << "if"
                             << "import"
                             << "in"
                             << "is"
                             << "lambda"
                             << "not"
                             << "or"
                             << "pass"
                             << "print"
                             << "raise"
                             << "return"
                             << "try"
                             << "while"
                             << "yield"
                             << "None"
                             << "True"
                             << "False";

    operators = QStringList() << "=" <<
                // Comparison
                "==" << "!="
                              << "<"
                              << "<="
                              << ">"
                              << ">=" <<
                // Arithmetic
                "\\+" << "-"
                              << "\\*"
                              << "/"
                              << "//"
                              << "%"
                              << "\\*\\*" <<
                // In-place
                "\\+=" << "-="
                              << "\\*="
                              << "/="
                              << "%=" <<
                // Bitwise
                "\\^" << "\\|"
                              << "&"
                              << "~"
                              << ">>"
                              << "<<";

    braces = QStringList() << "{"
                           << "}"
                           << "\\("
                           << "\\)"
                           << "\\["
                           << "]";

    basicStyles.insert("keyword", getTextCharFormat("blue"));
    basicStyles.insert("operator", getTextCharFormat("red"));
    basicStyles.insert("brace", getTextCharFormat("darkGray"));
    basicStyles.insert("defclass", getTextCharFormat("black", "bold"));
    basicStyles.insert("brace", getTextCharFormat("black"));
    basicStyles.insert("string", getTextCharFormat("magenta"));
    basicStyles.insert("string2", getTextCharFormat("darkMagenta"));
    basicStyles.insert("comment", getTextCharFormat("darkGreen", "italic"));
    basicStyles.insert("self", getTextCharFormat("black", "italic"));
    basicStyles.insert("numbers", getTextCharFormat("brown"));

    triSingleQuote.setPattern("'''");
    triDoubleQuote.setPattern(R"(""")");

    initializeRules();
}

void PythonSyntaxHighlighter::initializeRules()
{
    for (const QString& currKeyword : keywords) {
        rules.append(HighlightingRule(QString("\\b%1\\b").arg(currKeyword), 0,
                                      basicStyles.value("keyword")));
    }
    for (const QString& currOperator : operators) {
        rules.append(
            HighlightingRule(QString("%1").arg(currOperator), 0, basicStyles.value("operator")));
    }
    for (const QString& currBrace : braces)
        rules.append(HighlightingRule(QString("%1").arg(currBrace), 0, basicStyles.value("brace")));
    // 'self'
    rules.append(HighlightingRule("\\bself\\b", 0, basicStyles.value("self")));

    // Double-quoted string, possibly containing escape sequences
    // FF: originally in python : r'"[^"\\]*(\\.[^"\\]*)*"'
    rules.append(HighlightingRule(R"("[^"\\]*(\\.[^"\\]*)*")", 0, basicStyles.value("string")));
    // Single-quoted string, possibly containing escape sequences
    // FF: originally in python : r"'[^'\\]*(\\.[^'\\]*)*'"
    rules.append(HighlightingRule(R"('[^'\\]*(\\.[^'\\]*)*')", 0, basicStyles.value("string")));

    // 'def' followed by an identifier
    // FF: originally: r'\bdef\b\s*(\w+)'
    rules.append(HighlightingRule(R"(\bdef\b\s*(\w+))", 1, basicStyles.value("defclass")));
    //  'class' followed by an identifier
    // FF: originally: r'\bclass\b\s*(\w+)'
    rules.append(HighlightingRule(R"(\bclass\b\s*(\w+))", 1, basicStyles.value("defclass")));

    // From '#' until a newline
    // FF: originally: r'#[^\\n]*'
    rules.append(HighlightingRule("#[^\\n]*", 0, basicStyles.value("comment")));

    // Numeric literals
    rules.append(HighlightingRule("\\b[+-]?[0-9]+[lL]?\\b", 0,
                                  basicStyles.value("numbers"))); // r'\b[+-]?[0-9]+[lL]?\b'
    rules.append(
        HighlightingRule("\\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\\b", 0,
                         basicStyles.value("numbers"))); // r'\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b'
    rules.append(HighlightingRule(
        R"(\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b)", 0,
        basicStyles.value("numbers"))); // r'\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b'
}

void PythonSyntaxHighlighter::highlightBlock(const QString& text)
{
    for (const HighlightingRule& currRule : rules) {
        QRegularExpressionMatch matched{currRule.pattern.match(text)};
        int idx = matched.capturedStart(0);
        while (idx >= 0) {
            // Get index of Nth match
            idx = matched.capturedStart(currRule.nth);
            const int length = matched.capturedLength(currRule.nth);
            setFormat(idx, length, currRule.format);
            matched = currRule.pattern.match(text, idx + length);
            idx = matched.capturedStart(0);
        }
    }
    setCurrentBlockState(0);

    // Do multi-line strings
    if (!matchMultiline(text, triSingleQuote, 1, basicStyles.value("string2")))
        matchMultiline(text, triDoubleQuote, 2, basicStyles.value("string2"));
}

bool PythonSyntaxHighlighter::matchMultiline(const QString& text,
                                             const QRegularExpression& delimiter, const int inState,
                                             const QTextCharFormat& style)
{
    int start = -1;
    int add = -1;
    int end = -1;
    int length = 0;

    // If inside triple-single quotes, start at 0
    if (previousBlockState() == inState) {
        start = 0;
        add = 0;
    }
    // Otherwise, look for the delimiter on this line
    else {
        QRegularExpressionMatch matched{delimiter.match(text)};
        // TODO: What if match fails?
        start = matched.capturedStart(0);
        // Move past this match
        add = matched.capturedLength(0);
    }
    // As long as there's a delimiter match on this line...
    while (start >= 0) {
        // Look for the ending delimiter
        // TODO: What if match fails?
        QRegularExpressionMatch matched{delimiter.match(text, start + add)};
        end = matched.capturedStart(0);
        // Ending delimiter on this line?
        if (end >= add) {
            length = end - start + add + matched.capturedLength(0);
            setCurrentBlockState(0);
        }
        // No; multi-line string
        else {
            setCurrentBlockState(inState);
            length = text.length() - start + add;
        }
        // Apply formatting and look for next
        setFormat(start, length, style);
        matched = delimiter.match(text, start + length);
        // TODO: What if match fails?
        start = matched.capturedStart(0);
    }
    // Return True if still inside a multi-line string, False otherwise
    return currentBlockState() == inState;
}

QTextCharFormat PythonSyntaxHighlighter::getTextCharFormat(const QString& colorName,
                                                           const QString& style)
{
    QTextCharFormat charFormat;
    QColor color(colorName);
    charFormat.setForeground(color);
    if (style.contains("bold", Qt::CaseInsensitive))
        charFormat.setFontWeight(QFont::Bold);
    if (style.contains("italic", Qt::CaseInsensitive))
        charFormat.setFontItalic(true);
    return charFormat;
}