1 /**************************************************************************
3 ** This file is part of Qt Creator
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
7 ** Contact: Nokia Corporation (qt-info@nokia.com)
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
16 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Nokia gives you certain additional
26 ** rights. These rights are described in the Nokia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** If you have questions regarding the use of this file, please contact
30 ** Nokia at qt-info@nokia.com.
32 **************************************************************************/
33 #include "MatchingText.h"
34 #include "BackwardsScanner.h"
38 #include <QtGui/QTextDocument>
39 #include <QtCore/QtDebug>
41 using namespace CPlusPlus;
43 enum { MAX_NUM_LINES = 20 };
45 static bool shouldOverrideChar(QChar ch)
47 switch (ch.unicode()) {
48 case ')': case ']': case ';': case '"': case '\'':
56 static bool isCompleteStringLiteral(const BackwardsScanner &tk, int index)
58 const QStringRef text = tk.textRef(index);
60 if (text.length() < 2)
63 else if (text.at(text.length() - 1) == QLatin1Char('"'))
64 return text.at(text.length() - 2) != QLatin1Char('\\'); // ### not exactly.
69 static bool isCompleteCharLiteral(const BackwardsScanner &tk, int index)
71 const QStringRef text = tk.textRef(index);
73 if (text.length() < 2)
76 else if (text.at(text.length() - 1) == QLatin1Char('\''))
77 return text.at(text.length() - 2) != QLatin1Char('\\'); // ### not exactly.
82 bool MatchingText::shouldInsertMatchingText(const QTextCursor &tc)
84 QTextDocument *doc = tc.document();
85 return shouldInsertMatchingText(doc->characterAt(tc.selectionEnd()));
88 bool MatchingText::shouldInsertMatchingText(QChar lookAhead)
90 switch (lookAhead.unicode()) {
97 if (lookAhead.isSpace())
104 QString MatchingText::insertMatchingBrace(const QTextCursor &cursor, const QString &textToProcess,
105 QChar la, int *skippedChars) const
107 QTextCursor tc = cursor;
108 QTextDocument *doc = tc.document();
109 QString text = textToProcess;
111 const QString blockText = tc.block().text().mid(tc.positionInBlock());
112 const int length = qMin(blockText.length(), textToProcess.length());
114 const QChar previousChar = doc->characterAt(tc.selectionEnd() - 1);
118 if (! text.isEmpty() && (text.at(0) == QLatin1Char('"') ||
119 text.at(0) == QLatin1Char('\''))) {
120 if (previousChar == QLatin1Char('\\')) {
122 int index = tc.selectionEnd() - 1;
126 } while (doc->characterAt(index) == QLatin1Char('\\'));
128 if ((escapeCount % 2) != 0)
134 for (int i = 0; i < length; ++i) {
135 const QChar ch1 = blockText.at(i);
136 const QChar ch2 = textToProcess.at(i);
140 else if (! shouldOverrideChar(ch1))
147 if (*skippedChars != 0) {
148 tc.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, *skippedChars);
149 text = textToProcess.mid(*skippedChars);
152 if (text.isEmpty() || !shouldInsertMatchingText(la))
155 BackwardsScanner tk(tc, MAX_NUM_LINES, textToProcess.left(*skippedChars));
156 const int startToken = tk.startToken();
157 int index = startToken;
159 const Token &token = tk[index - 1];
161 if (text.at(0) == QLatin1Char('"') && (token.is(T_STRING_LITERAL) || token.is(T_WIDE_STRING_LITERAL))) {
162 if (text.length() != 1)
163 qWarning() << Q_FUNC_INFO << "handle event compression";
165 if (isCompleteStringLiteral(tk, index - 1))
166 return QLatin1String("\"");
169 } else if (text.at(0) == QLatin1Char('\'') && (token.is(T_CHAR_LITERAL) || token.is(T_WIDE_CHAR_LITERAL))) {
170 if (text.length() != 1)
171 qWarning() << Q_FUNC_INFO << "handle event compression";
173 if (isCompleteCharLiteral(tk, index - 1))
174 return QLatin1String("'");
181 foreach (const QChar &ch, text) {
182 if (ch == QLatin1Char('(')) result += ')';
183 else if (ch == QLatin1Char('[')) result += ']';
184 else if (ch == QLatin1Char('"')) result += '"';
185 else if (ch == QLatin1Char('\'')) result += '\'';
191 bool MatchingText::shouldInsertNewline(const QTextCursor &tc) const
193 QTextDocument *doc = tc.document();
194 int pos = tc.selectionEnd();
196 // count the number of empty lines.
198 for (int e = doc->characterCount(); pos != e; ++pos) {
199 const QChar ch = doc->characterAt(pos);
203 else if (ch == QChar::ParagraphSeparator)
207 if (newlines <= 1 && doc->characterAt(pos) != QLatin1Char('}'))
213 QString MatchingText::insertParagraphSeparator(const QTextCursor &tc) const
215 BackwardsScanner tk(tc, MAX_NUM_LINES);
216 int index = tk.startToken();
218 if (tk[index - 1].isNot(T_LBRACE))
219 return QString(); // nothing to do.
221 const QString textBlock = tc.block().text().mid(tc.positionInBlock()).trimmed();
222 if (! textBlock.isEmpty())
225 --index; // consume the `{'
227 const Token &token = tk[index - 1];
229 if (token.is(T_STRING_LITERAL) && tk[index - 2].is(T_EXTERN)) {
230 // recognized extern "C"
231 return QLatin1String("}");
233 } else if (token.is(T_IDENTIFIER)) {
237 const Token ¤t = tk[i - 1];
239 if (current.is(T_EOF_SYMBOL))
242 else if (current.is(T_CLASS) || current.is(T_STRUCT) || current.is(T_UNION) || current.is(T_ENUM)) {
243 // found a class key.
244 QString str = QLatin1String("};");
246 if (shouldInsertNewline(tc))
247 str += QLatin1Char('\n');
252 else if (current.is(T_NAMESPACE))
253 return QLatin1String("}"); // found a namespace declaration
255 else if (current.is(T_SEMICOLON))
256 break; // found the `;' sync token
258 else if (current.is(T_LBRACE) || current.is(T_RBRACE))
259 break; // braces are considered sync tokens
261 else if (current.is(T_LPAREN) || current.is(T_RPAREN))
264 else if (current.is(T_LBRACKET) || current.is(T_RBRACKET))
271 if (token.is(T_NAMESPACE)) {
272 // anonymous namespace
273 return QLatin1String("}");
275 } else if (token.is(T_CLASS) || token.is(T_STRUCT) || token.is(T_UNION) || token.is(T_ENUM)) {
276 if (tk[index - 2].is(T_TYPEDEF)) {
280 // in this case we don't want to insert the extra semicolon+newline.
281 return QLatin1String("}");
285 return QLatin1String("};");
287 } else if (token.is(T_RPAREN)) {
288 // search the matching brace.
289 const int lparenIndex = tk.startOfMatchingBrace(index);
291 if (lparenIndex == index) {
292 // found an unmatched brace. We don't really know to do in this case.
296 // look at the token before the matched brace
297 const Token &tokenBeforeBrace = tk[lparenIndex - 1];
299 if (tokenBeforeBrace.is(T_IF)) {
300 // recognized an if statement
301 return QLatin1String("}");
303 } else if (tokenBeforeBrace.is(T_FOR) || tokenBeforeBrace.is(T_WHILE)) {
304 // recognized a for-like statement
305 return QLatin1String("}");
309 // if we reached this point there is a good chance that we are parsing a function definition
310 QString str = QLatin1String("}");
312 if (shouldInsertNewline(tc))
313 str += QLatin1Char('\n');
319 return QLatin1String("}");