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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
|
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "cppdocumentationcommenthelper.h"
#include "cppautocompleter.h"
#include <cpptools/cpptoolssettings.h>
#include <cpptools/doxygengenerator.h>
#include <texteditor/texteditor.h>
#include <QDebug>
#include <QKeyEvent>
#include <QTextBlock>
using namespace CppTools;
namespace {
bool isStartOfDoxygenComment(const QTextCursor &cursor)
{
const int pos = cursor.position();
QTextDocument *document = cursor.document();
QString comment = QString(document->characterAt(pos - 3))
+ document->characterAt(pos - 2)
+ document->characterAt(pos - 1);
if ((comment == QLatin1String("/**"))
|| (comment == QLatin1String("/*!"))
|| (comment == QLatin1String("///"))
|| (comment == QLatin1String("//!"))) {
return true;
}
return false;
}
DoxygenGenerator::DocumentationStyle doxygenStyle(const QTextCursor &cursor,
const QTextDocument *doc)
{
const int pos = cursor.position();
QString comment = QString(doc->characterAt(pos - 3))
+ doc->characterAt(pos - 2)
+ doc->characterAt(pos - 1);
if (comment == QLatin1String("/**"))
return DoxygenGenerator::JavaStyle;
else if (comment == QLatin1String("/*!"))
return DoxygenGenerator::QtStyle;
else if (comment == QLatin1String("///"))
return DoxygenGenerator::CppStyleA;
else
return DoxygenGenerator::CppStyleB;
}
/// Check if previous line is a CppStyle Doxygen Comment
bool isPreviousLineCppStyleComment(const QTextCursor &cursor)
{
const QTextBlock ¤tBlock = cursor.block();
if (!currentBlock.isValid())
return false;
const QTextBlock &actual = currentBlock.previous();
if (!actual.isValid())
return false;
const QString text = actual.text().trimmed();
if (text.startsWith(QLatin1String("///")) || text.startsWith(QLatin1String("//!")))
return true;
return false;
}
/// Check if next line is a CppStyle Doxygen Comment
bool isNextLineCppStyleComment(const QTextCursor &cursor)
{
const QTextBlock ¤tBlock = cursor.block();
if (!currentBlock.isValid())
return false;
const QTextBlock &actual = currentBlock.next();
if (!actual.isValid())
return false;
const QString text = actual.text().trimmed();
if (text.startsWith(QLatin1String("///")) || text.startsWith(QLatin1String("//!")))
return true;
return false;
}
bool isCppStyleContinuation(const QTextCursor& cursor)
{
return (isPreviousLineCppStyleComment(cursor) || isNextLineCppStyleComment(cursor));
}
bool lineStartsWithCppDoxygenCommentAndCursorIsAfter(const QTextCursor &cursor,
const QTextDocument *doc)
{
QTextCursor cursorFirstNonBlank(cursor);
cursorFirstNonBlank.movePosition(QTextCursor::StartOfLine);
while (doc->characterAt(cursorFirstNonBlank.position()).isSpace()
&& cursorFirstNonBlank.movePosition(QTextCursor::NextCharacter)) {
}
const QTextBlock& block = cursorFirstNonBlank.block();
const QString text = block.text().trimmed();
if (text.startsWith(QLatin1String("///")) || text.startsWith(QLatin1String("//!")))
return (cursor.position() >= cursorFirstNonBlank.position() + 3);
return false;
}
bool isCursorAfterNonNestedCppStyleComment(const QTextCursor &cursor,
TextEditor::TextEditorWidget *editorWidget)
{
QTextDocument *document = editorWidget->document();
QTextCursor cursorBeforeCppComment(cursor);
while (document->characterAt(cursorBeforeCppComment.position()) != QLatin1Char('/')
&& cursorBeforeCppComment.movePosition(QTextCursor::PreviousCharacter)) {
}
if (!cursorBeforeCppComment.movePosition(QTextCursor::PreviousCharacter))
return false;
if (document->characterAt(cursorBeforeCppComment.position()) != QLatin1Char('/'))
return false;
if (!cursorBeforeCppComment.movePosition(QTextCursor::PreviousCharacter))
return false;
return !editorWidget->autoCompleter()->isInComment(cursorBeforeCppComment);
}
bool handleDoxygenCppStyleContinuation(QTextCursor &cursor, QKeyEvent *e)
{
const int blockPos = cursor.positionInBlock();
const QString &text = cursor.block().text();
int offset = 0;
for (; offset < blockPos; ++offset) {
if (!text.at(offset).isSpace())
break;
}
// If the line does not start with the comment we don't
// consider it as a continuation. Handles situations like:
// void d(); ///<enter>
if (!(text.trimmed().startsWith(QLatin1String("///"))
|| text.startsWith(QLatin1String("//!")))) {
return false;
}
QString newLine(QLatin1Char('\n'));
newLine.append(QString(offset, QLatin1Char(' '))); // indent correctly
const QString commentMarker = text.mid(offset, 3);
newLine.append(commentMarker);
newLine.append(QLatin1Char(' '));
cursor.insertText(newLine);
e->accept();
return true;
}
bool handleDoxygenContinuation(QTextCursor &cursor,
QKeyEvent *e,
TextEditor::TextEditorWidget *editorWidget,
const bool enableDoxygen,
const bool leadingAsterisks)
{
const QTextDocument *doc = editorWidget->document();
// It might be a continuation if:
// a) current line starts with /// or //! and cursor is positioned after the comment
// b) current line is in the middle of a multi-line Qt or Java style comment
if (!cursor.atEnd()) {
if (enableDoxygen && lineStartsWithCppDoxygenCommentAndCursorIsAfter(cursor, doc))
return handleDoxygenCppStyleContinuation(cursor, e);
if (isCursorAfterNonNestedCppStyleComment(cursor, editorWidget))
return false;
}
// We continue the comment if the cursor is after a comment's line asterisk and if
// there's no asterisk immediately after the cursor (that would already be considered
// a leading asterisk).
int offset = 0;
const int blockPos = cursor.positionInBlock();
const QString ¤tLine = cursor.block().text();
for (; offset < blockPos; ++offset) {
if (!currentLine.at(offset).isSpace())
break;
}
// In case we don't need to insert leading asteriskses, this code will be run once (right after
// hitting enter on the line containing '/*'). It will insert a continuation without an
// asterisk, but with an extra space. After that, the normal indenting will take over and do the
// Right Thing <TM>.
if (offset < blockPos
&& (currentLine.at(offset) == QLatin1Char('*')
|| (offset < blockPos - 1
&& currentLine.at(offset) == QLatin1Char('/')
&& currentLine.at(offset + 1) == QLatin1Char('*')))) {
// Ok, so the line started with an '*' or '/*'
int followinPos = blockPos;
// Now search for the first non-whitespace character to align to:
for (; followinPos < currentLine.length(); ++followinPos) {
if (!currentLine.at(followinPos).isSpace())
break;
}
if (followinPos == currentLine.length() // a)
|| currentLine.at(followinPos) != QLatin1Char('*')) { // b)
// So either a) the line ended after a '*' and we need to insert a continuation, or
// b) we found the start of some text and we want to align the continuation to that.
QString newLine(QLatin1Char('\n'));
QTextCursor c(cursor);
c.movePosition(QTextCursor::StartOfBlock);
c.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, offset);
newLine.append(c.selectedText());
if (currentLine.at(offset) == QLatin1Char('/')) {
if (leadingAsterisks)
newLine.append(QLatin1String(" * "));
else
newLine.append(QLatin1String(" "));
} else {
// If '*' is not within a comment, skip.
QTextCursor cursorOnFirstNonWhiteSpace(cursor);
const int positionOnFirstNonWhiteSpace = cursor.position() - blockPos + offset;
cursorOnFirstNonWhiteSpace.setPosition(positionOnFirstNonWhiteSpace);
if (!editorWidget->autoCompleter()->isInComment(cursorOnFirstNonWhiteSpace))
return false;
// ...otherwise do the continuation
int start = offset;
while (offset < blockPos && currentLine.at(offset) == QLatin1Char('*'))
++offset;
const QChar ch = leadingAsterisks ? QLatin1Char('*') : QLatin1Char(' ');
newLine.append(QString(offset - start, ch));
newLine.append(QLatin1Char(' '));
}
cursor.insertText(newLine);
e->accept();
return true;
}
}
return false;
}
} // anonymous namespace
namespace CppEditor {
namespace Internal {
CppDocumentationCommentHelper::CppDocumentationCommentHelper(
TextEditor::TextEditorWidget *editorWidget)
: m_editorWidget(editorWidget)
, m_settings(CppToolsSettings::instance()->commentsSettings())
{
connect(CppToolsSettings::instance(),
SIGNAL(commentsSettingsChanged(CppTools::CommentsSettings)),
this,
SLOT(onCommentsSettingsChanged(CppTools::CommentsSettings)));
}
bool CppDocumentationCommentHelper::handleKeyPressEvent(QKeyEvent *e) const
{
if (!m_settings.m_enableDoxygen && !m_settings.m_leadingAsterisks)
return false;
if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) {
QTextCursor cursor = m_editorWidget->textCursor();
if (!m_editorWidget->autoCompleter()->isInComment(cursor))
return false;
// We are interested on two particular cases:
// 1) The cursor is right after a /**, /*!, /// or ///! and the user pressed enter.
// If Doxygen is enabled we need to generate an entire comment block.
// 2) The cursor is already in the middle of a multi-line comment and the user pressed
// enter. If leading asterisk(s) is set we need to write a comment continuation
// with those.
if (m_settings.m_enableDoxygen && cursor.positionInBlock() >= 3) {
const int pos = cursor.position();
if (isStartOfDoxygenComment(cursor)) {
QTextDocument *textDocument = m_editorWidget->document();
DoxygenGenerator::DocumentationStyle style = doxygenStyle(cursor, textDocument);
// Check if we're already in a CppStyle Doxygen comment => continuation
// Needs special handling since CppStyle does not have start and end markers
if ((style == DoxygenGenerator::CppStyleA || style == DoxygenGenerator::CppStyleB)
&& isCppStyleContinuation(cursor)) {
return handleDoxygenCppStyleContinuation(cursor, e);
}
DoxygenGenerator doxygen;
doxygen.setStyle(style);
doxygen.setAddLeadingAsterisks(m_settings.m_leadingAsterisks);
doxygen.setGenerateBrief(m_settings.m_generateBrief);
doxygen.setStartComment(false);
// Move until we reach any possibly meaningful content.
while (textDocument->characterAt(cursor.position()).isSpace()
&& cursor.movePosition(QTextCursor::NextCharacter)) {
}
if (!cursor.atEnd()) {
const QString &comment = doxygen.generate(cursor);
if (!comment.isEmpty()) {
cursor.beginEditBlock();
cursor.setPosition(pos);
cursor.insertText(comment);
cursor.setPosition(pos - 3, QTextCursor::KeepAnchor);
m_editorWidget->textDocument()->autoIndent(cursor);
cursor.endEditBlock();
e->accept();
return true;
}
}
}
} // right after first doxygen comment
return handleDoxygenContinuation(cursor,
e,
m_editorWidget,
m_settings.m_enableDoxygen,
m_settings.m_leadingAsterisks);
}
return false;
}
void CppDocumentationCommentHelper::onCommentsSettingsChanged(const CommentsSettings &settings)
{
m_settings = settings;
}
} // namespace Internal
} // namespace CppEditor
|