OSDN Git Service

It's 2011 now.
[qt-creator-jp/qt-creator-jp.git] / src / libs / cplusplus / MatchingText.cpp
1 /**************************************************************************
2 **
3 ** This file is part of Qt Creator
4 **
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6 **
7 ** Contact: Nokia Corporation (qt-info@nokia.com)
8 **
9 ** No Commercial Usage
10 **
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
14 ** this package.
15 **
16 ** GNU Lesser General Public License Usage
17 **
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.
24 **
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.
28 **
29 ** If you have questions regarding the use of this file, please contact
30 ** Nokia at qt-info@nokia.com.
31 **
32 **************************************************************************/
33 #include "MatchingText.h"
34 #include "BackwardsScanner.h"
35
36 #include <Token.h>
37
38 #include <QtGui/QTextDocument>
39 #include <QtCore/QtDebug>
40
41 using namespace CPlusPlus;
42
43 enum { MAX_NUM_LINES = 20 };
44
45 static bool shouldOverrideChar(QChar ch)
46 {
47     switch (ch.unicode()) {
48     case ')': case ']': case ';': case '"': case '\'':
49         return true;
50
51     default:
52         return false;
53     }
54 }
55
56 static bool isCompleteStringLiteral(const BackwardsScanner &tk, int index)
57 {
58     const QStringRef text = tk.textRef(index);
59
60     if (text.length() < 2)
61         return false;
62
63     else if (text.at(text.length() - 1) == QLatin1Char('"'))
64         return text.at(text.length() - 2) != QLatin1Char('\\'); // ### not exactly.
65
66     return false;
67 }
68
69 static bool isCompleteCharLiteral(const BackwardsScanner &tk, int index)
70 {
71     const QStringRef text = tk.textRef(index);
72
73     if (text.length() < 2)
74         return false;
75
76     else if (text.at(text.length() - 1) == QLatin1Char('\''))
77         return text.at(text.length() - 2) != QLatin1Char('\\'); // ### not exactly.
78
79     return false;
80 }
81
82 bool MatchingText::shouldInsertMatchingText(const QTextCursor &tc)
83 {
84     QTextDocument *doc = tc.document();
85     return shouldInsertMatchingText(doc->characterAt(tc.selectionEnd()));
86 }
87
88 bool MatchingText::shouldInsertMatchingText(QChar lookAhead)
89 {
90     switch (lookAhead.unicode()) {
91     case '{': case '}':
92     case ']': case ')':
93     case ';': case ',':
94         return true;
95
96     default:
97         if (lookAhead.isSpace())
98             return true;
99
100         return false;
101     } // switch
102 }
103
104 QString MatchingText::insertMatchingBrace(const QTextCursor &cursor, const QString &textToProcess,
105                                           QChar la, int *skippedChars) const
106 {
107     QTextCursor tc = cursor;
108     QTextDocument *doc = tc.document();
109     QString text = textToProcess;
110
111     const QString blockText = tc.block().text().mid(tc.positionInBlock());
112     const int length = qMin(blockText.length(), textToProcess.length());
113
114     const QChar previousChar = doc->characterAt(tc.selectionEnd() - 1);
115
116     bool escape = false;
117
118     if (! text.isEmpty() && (text.at(0) == QLatin1Char('"') ||
119                              text.at(0) == QLatin1Char('\''))) {
120         if (previousChar == QLatin1Char('\\')) {
121             int escapeCount = 0;
122             int index = tc.selectionEnd() - 1;
123             do {
124                 ++escapeCount;
125                 --index;
126             } while (doc->characterAt(index) == QLatin1Char('\\'));
127
128             if ((escapeCount % 2) != 0)
129                 escape = true;
130         }
131     }
132
133     if (! escape) {
134         for (int i = 0; i < length; ++i) {
135             const QChar ch1 = blockText.at(i);
136             const QChar ch2 = textToProcess.at(i);
137
138             if (ch1 != ch2)
139                 break;
140             else if (! shouldOverrideChar(ch1))
141                 break;
142
143             ++*skippedChars;
144         }
145     }
146
147     if (*skippedChars != 0) {
148         tc.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, *skippedChars);
149         text = textToProcess.mid(*skippedChars);
150     }
151
152     if (text.isEmpty() || !shouldInsertMatchingText(la))
153         return QString();
154
155     BackwardsScanner tk(tc, MAX_NUM_LINES, textToProcess.left(*skippedChars));
156     const int startToken = tk.startToken();
157     int index = startToken;
158
159     const Token &token = tk[index - 1];
160
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";
164
165         if (isCompleteStringLiteral(tk, index - 1))
166             return QLatin1String("\"");
167
168         return QString();
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";
172
173         if (isCompleteCharLiteral(tk, index - 1))
174             return QLatin1String("'");
175
176         return QString();
177     }
178
179     QString result;
180
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 += '\'';
186     }
187
188     return result;
189 }
190
191 bool MatchingText::shouldInsertNewline(const QTextCursor &tc) const
192 {
193     QTextDocument *doc = tc.document();
194     int pos = tc.selectionEnd();
195
196     // count the number of empty lines.
197     int newlines = 0;
198     for (int e = doc->characterCount(); pos != e; ++pos) {
199         const QChar ch = doc->characterAt(pos);
200
201         if (! ch.isSpace())
202             break;
203         else if (ch == QChar::ParagraphSeparator)
204             ++newlines;
205     }
206
207     if (newlines <= 1 && doc->characterAt(pos) != QLatin1Char('}'))
208         return true;
209
210     return false;
211 }
212
213 QString MatchingText::insertParagraphSeparator(const QTextCursor &tc) const
214 {
215     BackwardsScanner tk(tc, MAX_NUM_LINES);
216     int index = tk.startToken();
217
218     if (tk[index - 1].isNot(T_LBRACE))
219         return QString(); // nothing to do.
220
221     const QString textBlock = tc.block().text().mid(tc.positionInBlock()).trimmed();
222     if (! textBlock.isEmpty())
223         return QString();
224
225     --index; // consume the `{'
226
227     const Token &token = tk[index - 1];
228
229     if (token.is(T_STRING_LITERAL) && tk[index - 2].is(T_EXTERN)) {
230         // recognized extern "C"
231         return QLatin1String("}");
232
233     } else if (token.is(T_IDENTIFIER)) {
234         int i = index - 1;
235
236         forever {
237             const Token &current = tk[i - 1];
238
239             if (current.is(T_EOF_SYMBOL))
240                 break;
241
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("};");
245
246                 if (shouldInsertNewline(tc))
247                     str += QLatin1Char('\n');
248
249                 return str;
250             }
251
252             else if (current.is(T_NAMESPACE))
253                 return QLatin1String("}"); // found a namespace declaration
254
255             else if (current.is(T_SEMICOLON))
256                 break; // found the `;' sync token
257
258             else if (current.is(T_LBRACE) || current.is(T_RBRACE))
259                 break; // braces are considered sync tokens
260
261             else if (current.is(T_LPAREN) || current.is(T_RPAREN))
262                 break; // sync token
263
264             else if (current.is(T_LBRACKET) || current.is(T_RBRACKET))
265                 break; // sync token
266
267             --i;
268         }
269     }
270
271     if (token.is(T_NAMESPACE)) {
272         // anonymous namespace
273         return QLatin1String("}");
274
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)) {
277             // recognized:
278             //   typedef struct {
279             //
280             // in this case we don't want to insert the extra semicolon+newline.
281             return QLatin1String("}");
282         }
283
284         // anonymous class
285         return QLatin1String("};");
286
287     } else if (token.is(T_RPAREN)) {
288         // search the matching brace.
289         const int lparenIndex = tk.startOfMatchingBrace(index);
290
291         if (lparenIndex == index) {
292             // found an unmatched brace. We don't really know to do in this case.
293             return QString();
294         }
295
296         // look at the token before the matched brace
297         const Token &tokenBeforeBrace = tk[lparenIndex - 1];
298
299         if (tokenBeforeBrace.is(T_IF)) {
300             // recognized an if statement
301             return QLatin1String("}");
302
303         } else if (tokenBeforeBrace.is(T_FOR) || tokenBeforeBrace.is(T_WHILE)) {
304             // recognized a for-like statement
305             return QLatin1String("}");
306
307         }
308
309         // if we reached this point there is a good chance that we are parsing a function definition
310         QString str = QLatin1String("}");
311
312         if (shouldInsertNewline(tc))
313             str += QLatin1Char('\n');
314
315         return str;
316     }
317
318     // match the block
319     return QLatin1String("}");
320 }