PageRenderTime 43ms CodeModel.GetById 20ms app.highlight 20ms RepoModel.GetById 0ms app.codeStats 0ms

/src/plugins/qmljseditor/qmljshighlighter.cpp

https://github.com/KDAB/KDAB-Creator
C++ | 334 lines | 254 code | 46 blank | 34 comment | 193 complexity | 1ff03ee02ae5eb5e8843632bbff96afb MD5 | raw file
  1/**************************************************************************
  2**
  3** This file is part of Qt Creator
  4**
  5** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
  6**
  7** Contact: Nokia Corporation (qt-info@nokia.com)
  8**
  9**
 10** GNU Lesser General Public License Usage
 11**
 12** This file may be used under the terms of the GNU Lesser General Public
 13** License version 2.1 as published by the Free Software Foundation and
 14** appearing in the file LICENSE.LGPL included in the packaging of this file.
 15** Please review the following information to ensure the GNU Lesser General
 16** Public License version 2.1 requirements will be met:
 17** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
 18**
 19** In addition, as a special exception, Nokia gives you certain additional
 20** rights. These rights are described in the Nokia Qt LGPL Exception
 21** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
 22**
 23** Other Usage
 24**
 25** Alternatively, this file may be used in accordance with the terms and
 26** conditions contained in a signed written agreement between you and Nokia.
 27**
 28** If you have questions regarding the use of this file, please contact
 29** Nokia at qt-info@nokia.com.
 30**
 31**************************************************************************/
 32
 33#include "qmljshighlighter.h"
 34
 35#include <QSet>
 36#include <QtAlgorithms>
 37#include <QDebug>
 38
 39#include <utils/qtcassert.h>
 40
 41using namespace QmlJSEditor;
 42using namespace QmlJS;
 43
 44Highlighter::Highlighter(QTextDocument *parent)
 45    : TextEditor::SyntaxHighlighter(parent),
 46      m_qmlEnabled(true),
 47      m_inMultilineComment(false)
 48{
 49    m_currentBlockParentheses.reserve(20);
 50    m_braceDepth = 0;
 51    m_foldingIndent = 0;
 52}
 53
 54Highlighter::~Highlighter()
 55{
 56}
 57
 58bool Highlighter::isQmlEnabled() const
 59{
 60    return m_qmlEnabled;
 61}
 62
 63void Highlighter::setQmlEnabled(bool qmlEnabled)
 64{
 65    m_qmlEnabled = qmlEnabled;
 66}
 67
 68void Highlighter::setFormats(const QVector<QTextCharFormat> &formats)
 69{
 70    QTC_ASSERT(formats.size() == NumFormats, return);
 71    qCopy(formats.begin(), formats.end(), m_formats);
 72}
 73
 74void Highlighter::highlightBlock(const QString &text)
 75{
 76    const QList<Token> tokens = m_scanner(text, onBlockStart());
 77
 78    int index = 0;
 79    while (index < tokens.size()) {
 80        const Token &token = tokens.at(index);
 81
 82        switch (token.kind) {
 83            case Token::Keyword:
 84                setFormat(token.offset, token.length, m_formats[KeywordFormat]);
 85                break;
 86
 87            case Token::String:
 88                setFormat(token.offset, token.length, m_formats[StringFormat]);
 89                break;
 90
 91            case Token::Comment:
 92                if (m_inMultilineComment && text.midRef(token.end() - 2, 2) == QLatin1String("*/")) {
 93                    onClosingParenthesis('-', token.end() - 1, index == tokens.size()-1);
 94                    m_inMultilineComment = false;
 95                } else if (!m_inMultilineComment
 96                           && (m_scanner.state() & Scanner::MultiLineMask) == Scanner::MultiLineComment
 97                           && index == tokens.size() - 1) {
 98                    onOpeningParenthesis('+', token.offset, index == 0);
 99                    m_inMultilineComment = true;
100                }
101                setFormat(token.offset, token.length, m_formats[CommentFormat]);
102                break;
103
104            case Token::RegExp:
105                setFormat(token.offset, token.length, m_formats[StringFormat]);
106                break;
107
108            case Token::LeftParenthesis:
109                onOpeningParenthesis('(', token.offset, index == 0);
110                break;
111
112            case Token::RightParenthesis:
113                onClosingParenthesis(')', token.offset, index == tokens.size()-1);
114                break;
115
116            case Token::LeftBrace:
117                onOpeningParenthesis('{', token.offset, index == 0);
118                break;
119
120            case Token::RightBrace:
121                onClosingParenthesis('}', token.offset, index == tokens.size()-1);
122                break;
123
124            case Token::LeftBracket:
125                onOpeningParenthesis('[', token.offset, index == 0);
126                break;
127
128            case Token::RightBracket:
129                onClosingParenthesis(']', token.offset, index == tokens.size()-1);
130                break;
131
132            case Token::Identifier: {
133                if (!m_qmlEnabled)
134                    break;
135
136                const QStringRef spell = text.midRef(token.offset, token.length);
137
138                if (maybeQmlKeyword(spell)) {
139                    // check the previous token
140                    if (index == 0 || tokens.at(index - 1).isNot(Token::Dot)) {
141                        if (index + 1 == tokens.size() || tokens.at(index + 1).isNot(Token::Colon)) {
142                            setFormat(token.offset, token.length, m_formats[KeywordFormat]);
143                            break;
144                        }
145                    }
146                } else if (index > 0 && maybeQmlBuiltinType(spell)) {
147                    const Token &previousToken = tokens.at(index - 1);
148                    if (previousToken.is(Token::Identifier) && text.at(previousToken.offset) == QLatin1Char('p')
149                        && text.midRef(previousToken.offset, previousToken.length) == QLatin1String("property")) {
150                        setFormat(token.offset, token.length, m_formats[KeywordFormat]);
151                        break;
152                    }
153                }
154            }   break;
155
156            case Token::Delimiter:
157                break;
158
159            default:
160                break;
161        } // end swtich
162
163        ++index;
164    }
165
166    int previousTokenEnd = 0;
167    for (int index = 0; index < tokens.size(); ++index) {
168        const Token &token = tokens.at(index);
169        setFormat(previousTokenEnd, token.begin() - previousTokenEnd, m_formats[VisualWhitespace]);
170
171        switch (token.kind) {
172        case Token::Comment:
173        case Token::String:
174        case Token::RegExp: {
175            int i = token.begin(), e = token.end();
176            while (i < e) {
177                const QChar ch = text.at(i);
178                if (ch.isSpace()) {
179                    const int start = i;
180                    do {
181                        ++i;
182                    } while (i < e && text.at(i).isSpace());
183                    setFormat(start, i - start, m_formats[VisualWhitespace]);
184                } else {
185                    ++i;
186                }
187            }
188        } break;
189
190        default:
191            break;
192        } // end of switch
193
194        previousTokenEnd = token.end();
195    }
196
197    setFormat(previousTokenEnd, text.length() - previousTokenEnd, m_formats[VisualWhitespace]);
198
199    setCurrentBlockState(m_scanner.state());
200    onBlockEnd(m_scanner.state());
201}
202
203bool Highlighter::maybeQmlKeyword(const QStringRef &text) const
204{
205    if (text.isEmpty())
206        return false;
207
208    const QChar ch = text.at(0);
209    if (ch == QLatin1Char('p') && text == QLatin1String("property")) {
210        return true;
211    } else if (ch == QLatin1Char('a') && text == QLatin1String("alias")) {
212        return true;
213    } else if (ch == QLatin1Char('s') && text == QLatin1String("signal")) {
214        return true;
215    } else if (ch == QLatin1Char('p') && text == QLatin1String("property")) {
216        return true;
217    } else if (ch == QLatin1Char('r') && text == QLatin1String("readonly")) {
218        return true;
219    } else if (ch == QLatin1Char('i') && text == QLatin1String("import")) {
220        return true;
221    } else if (ch == QLatin1Char('o') && text == QLatin1String("on")) {
222        return true;
223    } else {
224        return false;
225    }
226}
227
228bool Highlighter::maybeQmlBuiltinType(const QStringRef &text) const
229{
230    if (text.isEmpty())
231        return false;
232
233    const QChar ch = text.at(0);
234
235    if (ch == QLatin1Char('a') && text == QLatin1String("action")) {
236            return true;
237    } else if (ch == QLatin1Char('b') && text == QLatin1String("bool")) {
238        return true;
239    } else if (ch == QLatin1Char('c') && text == QLatin1String("color")) {
240        return true;
241    } else if (ch == QLatin1Char('d') && text == QLatin1String("date")) {
242        return true;
243    } else if (ch == QLatin1Char('d') && text == QLatin1String("double")) {
244        return true;
245    } else if (ch == QLatin1Char('e') && text == QLatin1String("enumeration")) {
246        return true;
247    } else if (ch == QLatin1Char('f') && text == QLatin1String("font")) {
248        return true;
249    } else if (ch == QLatin1Char('i') && text == QLatin1String("int")) {
250        return true;
251    } else if (ch == QLatin1Char('l') && text == QLatin1String("list")) {
252        return true;
253    } else if (ch == QLatin1Char('p') && text == QLatin1String("point")) {
254        return true;
255    } else if (ch == QLatin1Char('r') && text == QLatin1String("real")) {
256        return true;
257    } else if (ch == QLatin1Char('r') && text == QLatin1String("rect")) {
258        return true;
259    } else if (ch == QLatin1Char('s') && text == QLatin1String("size")) {
260        return true;
261    } else if (ch == QLatin1Char('s') && text == QLatin1String("string")) {
262        return true;
263    } else if (ch == QLatin1Char('t') && text == QLatin1String("time")) {
264        return true;
265    } else if (ch == QLatin1Char('u') && text == QLatin1String("url")) {
266        return true;
267    } else if (ch == QLatin1Char('v') && text == QLatin1String("variant")) {
268        return true;
269    } else if (ch == QLatin1Char('v') && text == QLatin1String("var")) {
270        return true;
271    } else if (ch == QLatin1Char('v') && text == QLatin1String("vector3d")) {
272        return true;
273    } else {
274        return false;
275    }
276}
277
278int Highlighter::onBlockStart()
279{
280    m_currentBlockParentheses.clear();
281    m_braceDepth = 0;
282    m_foldingIndent = 0;
283    m_inMultilineComment = false;
284    if (TextEditor::TextBlockUserData *userData = TextEditor::BaseTextDocumentLayout::testUserData(currentBlock())) {
285        userData->setFoldingIndent(0);
286        userData->setFoldingStartIncluded(false);
287        userData->setFoldingEndIncluded(false);
288    }
289
290    int state = 0;
291    int previousState = previousBlockState();
292    if (previousState != -1) {
293        state = previousState & 0xff;
294        m_braceDepth = (previousState >> 8);
295        m_inMultilineComment = ((state & Scanner::MultiLineMask) == Scanner::MultiLineComment);
296    }
297    m_foldingIndent = m_braceDepth;
298
299    return state;
300}
301
302void Highlighter::onBlockEnd(int state)
303{
304    typedef TextEditor::TextBlockUserData TextEditorBlockData;
305
306    setCurrentBlockState((m_braceDepth << 8) | state);
307    TextEditor::BaseTextDocumentLayout::setParentheses(currentBlock(), m_currentBlockParentheses);
308    TextEditor::BaseTextDocumentLayout::setFoldingIndent(currentBlock(), m_foldingIndent);
309}
310
311void Highlighter::onOpeningParenthesis(QChar parenthesis, int pos, bool atStart)
312{
313    if (parenthesis == QLatin1Char('{') || parenthesis == QLatin1Char('[') || parenthesis == QLatin1Char('+')) {
314        ++m_braceDepth;
315        // if a folding block opens at the beginning of a line, treat the entire line
316        // as if it were inside the folding block
317        if (atStart)
318            TextEditor::BaseTextDocumentLayout::userData(currentBlock())->setFoldingStartIncluded(true);
319    }
320    m_currentBlockParentheses.push_back(Parenthesis(Parenthesis::Opened, parenthesis, pos));
321}
322
323void Highlighter::onClosingParenthesis(QChar parenthesis, int pos, bool atEnd)
324{
325    if (parenthesis == QLatin1Char('}') || parenthesis == QLatin1Char(']') || parenthesis == QLatin1Char('-')) {
326        --m_braceDepth;
327        if (atEnd)
328            TextEditor::BaseTextDocumentLayout::userData(currentBlock())->setFoldingEndIncluded(true);
329        else
330            m_foldingIndent = qMin(m_braceDepth, m_foldingIndent); // folding indent is the minimum brace depth of a block
331    }
332    m_currentBlockParentheses.push_back(Parenthesis(Parenthesis::Closed, parenthesis, pos));
333}
334