source: trunk/src/gui/text/qsyntaxhighlighter.cpp@ 139

Last change on this file since 139 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

File size: 19.9 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4** Contact: Qt Software Information ([email protected])
5**
6** This file is part of the QtGui module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial Usage
10** Licensees holding valid Qt Commercial licenses may use this file in
11** accordance with the Qt Commercial License Agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and Nokia.
14**
15** GNU Lesser General Public License Usage
16** Alternatively, this file may be used under the terms of the GNU Lesser
17** General Public License version 2.1 as published by the Free Software
18** Foundation and appearing in the file LICENSE.LGPL included in the
19** packaging of this file. Please review the following information to
20** ensure the GNU Lesser General Public License version 2.1 requirements
21** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
22**
23** In addition, as a special exception, Nokia gives you certain
24** additional rights. These rights are described in the Nokia Qt LGPL
25** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
26** package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you are unsure which license is appropriate for your use, please
37** contact the sales department at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include "qsyntaxhighlighter.h"
43
44#ifndef QT_NO_SYNTAXHIGHLIGHTER
45#include <private/qobject_p.h>
46#include <qtextdocument.h>
47#include <private/qtextdocument_p.h>
48#include <qtextlayout.h>
49#include <qpointer.h>
50#include <qtextobject.h>
51#include <qtextcursor.h>
52#include <qdebug.h>
53#include <qtextedit.h>
54#include <qtimer.h>
55
56QT_BEGIN_NAMESPACE
57
58class QSyntaxHighlighterPrivate : public QObjectPrivate
59{
60 Q_DECLARE_PUBLIC(QSyntaxHighlighter)
61public:
62 inline QSyntaxHighlighterPrivate() : rehighlightPending(false) {}
63
64 QPointer<QTextDocument> doc;
65
66 void _q_reformatBlocks(int from, int charsRemoved, int charsAdded);
67 void reformatBlock(QTextBlock block);
68
69 inline void _q_delayedRehighlight() {
70 if (!rehighlightPending)
71 return;
72 rehighlightPending = false;
73 q_func()->rehighlight();
74 return;
75 }
76
77 void applyFormatChanges();
78 QVector<QTextCharFormat> formatChanges;
79 QTextBlock currentBlock;
80 bool rehighlightPending;
81};
82
83void QSyntaxHighlighterPrivate::applyFormatChanges()
84{
85 QTextLayout *layout = currentBlock.layout();
86
87 QList<QTextLayout::FormatRange> ranges = layout->additionalFormats();
88
89 const int preeditAreaStart = layout->preeditAreaPosition();
90 const int preeditAreaLength = layout->preeditAreaText().length();
91
92 QList<QTextLayout::FormatRange>::Iterator it = ranges.begin();
93 while (it != ranges.end()) {
94 if (it->start >= preeditAreaStart
95 && it->start + it->length <= preeditAreaStart + preeditAreaLength)
96 ++it;
97 else
98 it = ranges.erase(it);
99 }
100
101 QTextCharFormat emptyFormat;
102
103 QTextLayout::FormatRange r;
104 r.start = r.length = -1;
105
106 int i = 0;
107 while (i < formatChanges.count()) {
108
109 while (i < formatChanges.count() && formatChanges.at(i) == emptyFormat)
110 ++i;
111
112 if (i >= formatChanges.count())
113 break;
114
115 r.start = i;
116 r.format = formatChanges.at(i);
117
118 while (i < formatChanges.count() && formatChanges.at(i) == r.format)
119 ++i;
120
121 if (i >= formatChanges.count())
122 break;
123
124 r.length = i - r.start;
125
126 if (r.start >= preeditAreaStart) {
127 r.start += preeditAreaLength;
128 } else if (r.start + r.length >= preeditAreaStart) {
129 r.length += preeditAreaLength;
130 }
131
132 ranges << r;
133 r.start = r.length = -1;
134 }
135
136 if (r.start != -1) {
137 r.length = formatChanges.count() - r.start;
138
139 if (r.start >= preeditAreaStart) {
140 r.start += preeditAreaLength;
141 } else if (r.start + r.length >= preeditAreaStart) {
142 r.length += preeditAreaLength;
143 }
144
145 ranges << r;
146 }
147
148 layout->setAdditionalFormats(ranges);
149}
150
151void QSyntaxHighlighterPrivate::_q_reformatBlocks(int from, int charsRemoved, int charsAdded)
152{
153 Q_UNUSED(charsRemoved);
154 rehighlightPending = false;
155
156 QTextBlock block = doc->findBlock(from);
157 if (!block.isValid())
158 return;
159
160 int endPosition;
161 QTextBlock lastBlock = doc->findBlock(from + charsAdded);
162 if (lastBlock.isValid())
163 endPosition = lastBlock.position() + lastBlock.length();
164 else
165 endPosition = doc->docHandle()->length();
166
167 bool forceHighlightOfNextBlock = false;
168
169 while (block.isValid() && (block.position() < endPosition || forceHighlightOfNextBlock)) {
170 const int stateBeforeHighlight = block.userState();
171
172 reformatBlock(block);
173
174 forceHighlightOfNextBlock = (block.userState() != stateBeforeHighlight);
175
176 block = block.next();
177 }
178
179 formatChanges.clear();
180}
181
182void QSyntaxHighlighterPrivate::reformatBlock(QTextBlock block)
183{
184 Q_Q(QSyntaxHighlighter);
185
186 Q_ASSERT_X(!currentBlock.isValid(), "QSyntaxHighlighter::reformatBlock()", "reFormatBlock() called recursively");
187
188 currentBlock = block;
189 QTextBlock previous = block.previous();
190
191 formatChanges.fill(QTextCharFormat(), block.length() - 1);
192 q->highlightBlock(block.text());
193 applyFormatChanges();
194
195 doc->markContentsDirty(block.position(), block.length());
196
197 currentBlock = QTextBlock();
198}
199
200/*!
201 \class QSyntaxHighlighter
202 \reentrant
203
204 \brief The QSyntaxHighlighter class allows you to define syntax
205 highlighting rules, and in addition you can use the class to query
206 a document's current formatting or user data.
207
208 \since 4.1
209
210 \ingroup text
211
212 The QSyntaxHighlighter class is a base class for implementing
213 QTextEdit syntax highlighters. A syntax highligher automatically
214 highlights parts of the text in a QTextEdit, or more generally in
215 a QTextDocument. Syntax highlighters are often used when the user
216 is entering text in a specific format (for example source code)
217 and help the user to read the text and identify syntax errors.
218
219 To provide your own syntax highlighting, you must subclass
220 QSyntaxHighlighter and reimplement highlightBlock().
221
222 When you create an instance of your QSyntaxHighlighter subclass,
223 pass it the QTextEdit or QTextDocument that you want the syntax
224 highlighting to be applied to. For example:
225
226 \snippet doc/src/snippets/code/src_gui_text_qsyntaxhighlighter.cpp 0
227
228 After this your highlightBlock() function will be called
229 automatically whenever necessary. Use your highlightBlock()
230 function to apply formatting (e.g. setting the font and color) to
231 the text that is passed to it. QSyntaxHighlighter provides the
232 setFormat() function which applies a given QTextCharFormat on
233 the current text block. For example:
234
235 \snippet doc/src/snippets/code/src_gui_text_qsyntaxhighlighter.cpp 1
236
237 Some syntaxes can have constructs that span several text
238 blocks. For example, a C++ syntax highlighter should be able to
239 cope with \c{/}\c{*...*}\c{/} multiline comments. To deal with
240 these cases it is necessary to know the end state of the previous
241 text block (e.g. "in comment").
242
243 Inside your highlightBlock() implementation you can query the end
244 state of the previous text block using the previousBlockState()
245 function. After parsing the block you can save the last state
246 using setCurrentBlockState().
247
248 The currentBlockState() and previousBlockState() functions return
249 an int value. If no state is set, the returned value is -1. You
250 can designate any other value to identify any given state using
251 the setCurrentBlockState() function. Once the state is set the
252 QTextBlock keeps that value until it is set set again or until the
253 corresponding paragraph of text is deleted.
254
255 For example, if you're writing a simple C++ syntax highlighter,
256 you might designate 1 to signify "in comment":
257
258 \snippet doc/src/snippets/code/src_gui_text_qsyntaxhighlighter.cpp 2
259
260 In the example above, we first set the current block state to
261 0. Then, if the previous block ended within a comment, we higlight
262 from the beginning of the current block (\c {startIndex =
263 0}). Otherwise, we search for the given start expression. If the
264 specified end expression cannot be found in the text block, we
265 change the current block state by calling setCurrentBlockState(),
266 and make sure that the rest of the block is higlighted.
267
268 In addition you can query the current formatting and user data
269 using the format() and currentBlockUserData() functions
270 respectively. You can also attach user data to the current text
271 block using the setCurrentBlockUserData() function.
272 QTextBlockUserData can be used to store custom settings. In the
273 case of syntax highlighting, it is in particular interesting as
274 cache storage for information that you may figure out while
275 parsing the paragraph's text. For an example, see the
276 setCurrentBlockUserData() documentation.
277
278 \sa QTextEdit, {Syntax Highlighter Example}
279*/
280
281/*!
282 Constructs a QSyntaxHighlighter with the given \a parent.
283*/
284QSyntaxHighlighter::QSyntaxHighlighter(QObject *parent)
285 : QObject(*new QSyntaxHighlighterPrivate, parent)
286{
287}
288
289/*!
290 Constructs a QSyntaxHighlighter and installs it on \a parent.
291 The specified QTextDocument also becomes the owner of the
292 QSyntaxHighlighter.
293*/
294QSyntaxHighlighter::QSyntaxHighlighter(QTextDocument *parent)
295 : QObject(*new QSyntaxHighlighterPrivate, parent)
296{
297 setDocument(parent);
298}
299
300/*!
301 Constructs a QSyntaxHighlighter and installs it on \a parent 's
302 QTextDocument. The specified QTextEdit also becomes the owner of
303 the QSyntaxHighlighter.
304*/
305QSyntaxHighlighter::QSyntaxHighlighter(QTextEdit *parent)
306 : QObject(*new QSyntaxHighlighterPrivate, parent)
307{
308 setDocument(parent->document());
309}
310
311/*!
312 Destructor. Uninstalls this syntax highlighter from the text document.
313*/
314QSyntaxHighlighter::~QSyntaxHighlighter()
315{
316 setDocument(0);
317}
318
319/*!
320 Installs the syntax highlighter on the given QTextDocument \a doc.
321 A QSyntaxHighlighter can only be used with one document at a time.
322*/
323void QSyntaxHighlighter::setDocument(QTextDocument *doc)
324{
325 Q_D(QSyntaxHighlighter);
326 if (d->doc) {
327 disconnect(d->doc, SIGNAL(contentsChange(int,int,int)),
328 this, SLOT(_q_reformatBlocks(int,int,int)));
329
330 QTextCursor cursor(d->doc);
331 cursor.beginEditBlock();
332 for (QTextBlock blk = d->doc->begin(); blk.isValid(); blk = blk.next())
333 blk.layout()->clearAdditionalFormats();
334 cursor.endEditBlock();
335 }
336 d->doc = doc;
337 if (d->doc) {
338 connect(d->doc, SIGNAL(contentsChange(int,int,int)),
339 this, SLOT(_q_reformatBlocks(int,int,int)));
340 QTimer::singleShot(0, this, SLOT(_q_delayedRehighlight()));
341 d->rehighlightPending = true;
342 }
343}
344
345/*!
346 Returns the QTextDocument on which this syntax highlighter is
347 installed.
348*/
349QTextDocument *QSyntaxHighlighter::document() const
350{
351 Q_D(const QSyntaxHighlighter);
352 return d->doc;
353}
354
355/*!
356 \since 4.2
357
358 Redoes the highlighting of the whole document.
359*/
360void QSyntaxHighlighter::rehighlight()
361{
362 Q_D(QSyntaxHighlighter);
363 if (!d->doc)
364 return;
365
366 disconnect(d->doc, SIGNAL(contentsChange(int,int,int)),
367 this, SLOT(_q_reformatBlocks(int,int,int)));
368 QTextCursor cursor(d->doc);
369 cursor.beginEditBlock();
370 cursor.movePosition(QTextCursor::End);
371 d->_q_reformatBlocks(0, 0, cursor.position());
372 cursor.endEditBlock();
373 connect(d->doc, SIGNAL(contentsChange(int,int,int)),
374 this, SLOT(_q_reformatBlocks(int,int,int)));
375}
376
377/*!
378 \fn void QSyntaxHighlighter::highlightBlock(const QString &text)
379
380 Highlights the given text block. This function is called when
381 necessary by the rich text engine, i.e. on text blocks which have
382 changed.
383
384 To provide your own syntax highlighting, you must subclass
385 QSyntaxHighlighter and reimplement highlightBlock(). In your
386 reimplementation you should parse the block's \a text and call
387 setFormat() as often as necessary to apply any font and color
388 changes that you require. For example:
389
390 \snippet doc/src/snippets/code/src_gui_text_qsyntaxhighlighter.cpp 3
391
392 Some syntaxes can have constructs that span several text
393 blocks. For example, a C++ syntax highlighter should be able to
394 cope with \c{/}\c{*...*}\c{/} multiline comments. To deal with
395 these cases it is necessary to know the end state of the previous
396 text block (e.g. "in comment").
397
398 Inside your highlightBlock() implementation you can query the end
399 state of the previous text block using the previousBlockState()
400 function. After parsing the block you can save the last state
401 using setCurrentBlockState().
402
403 The currentBlockState() and previousBlockState() functions return
404 an int value. If no state is set, the returned value is -1. You
405 can designate any other value to identify any given state using
406 the setCurrentBlockState() function. Once the state is set the
407 QTextBlock keeps that value until it is set set again or until the
408 corresponding paragraph of text gets deleted.
409
410 For example, if you're writing a simple C++ syntax highlighter,
411 you might designate 1 to signify "in comment". For a text block
412 that ended in the middle of a comment you'd set 1 using
413 setCurrentBlockState, and for other paragraphs you'd set 0.
414 In your parsing code if the return value of previousBlockState()
415 is 1, you would highlight the text as a C++ comment until you
416 reached the closing \c{*}\c{/}.
417
418 \sa previousBlockState(), setFormat(), setCurrentBlockState()
419*/
420
421/*!
422 This function is applied to the syntax highlighter's current text
423 block (i.e. the text that is passed to the highlightBlock()
424 function).
425
426 The specified \a format is applied to the text from the \a start
427 position for a length of \a count characters (if \a count is 0,
428 nothing is done). The formatting properties set in \a format are
429 merged at display time with the formatting information stored
430 directly in the document, for example as previously set with
431 QTextCursor's functions. Note that the document itself remains
432 unmodified by the format set through this function.
433
434 \sa format(), highlightBlock()
435*/
436void QSyntaxHighlighter::setFormat(int start, int count, const QTextCharFormat &format)
437{
438 Q_D(QSyntaxHighlighter);
439
440 if (start < 0 || start >= d->formatChanges.count())
441 return;
442
443 const int end = qMin(start + count, d->formatChanges.count());
444 for (int i = start; i < end; ++i)
445 d->formatChanges[i] = format;
446}
447
448/*!
449 \overload
450
451 The specified \a color is applied to the current text block from
452 the \a start position for a length of \a count characters.
453
454 The other attributes of the current text block, e.g. the font and
455 background color, are reset to default values.
456
457 \sa format(), highlightBlock()
458*/
459void QSyntaxHighlighter::setFormat(int start, int count, const QColor &color)
460{
461 QTextCharFormat format;
462 format.setForeground(color);
463 setFormat(start, count, format);
464}
465
466/*!
467 \overload
468
469 The specified \a font is applied to the current text block from
470 the \a start position for a length of \a count characters.
471
472 The other attributes of the current text block, e.g. the font and
473 background color, are reset to default values.
474
475 \sa format(), highlightBlock()
476*/
477void QSyntaxHighlighter::setFormat(int start, int count, const QFont &font)
478{
479 QTextCharFormat format;
480 format.setFont(font);
481 setFormat(start, count, format);
482}
483
484/*!
485 \fn QTextCharFormat QSyntaxHighlighter::format(int position) const
486
487 Returns the format at \a position inside the syntax highlighter's
488 current text block.
489*/
490QTextCharFormat QSyntaxHighlighter::format(int pos) const
491{
492 Q_D(const QSyntaxHighlighter);
493 if (pos < 0 || pos >= d->formatChanges.count())
494 return QTextCharFormat();
495 return d->formatChanges.at(pos);
496}
497
498/*!
499 Returns the end state of the text block previous to the
500 syntax highlighter's current block. If no value was
501 previously set, the returned value is -1.
502
503 \sa highlightBlock(), setCurrentBlockState()
504*/
505int QSyntaxHighlighter::previousBlockState() const
506{
507 Q_D(const QSyntaxHighlighter);
508 if (!d->currentBlock.isValid())
509 return -1;
510
511 const QTextBlock previous = d->currentBlock.previous();
512 if (!previous.isValid())
513 return -1;
514
515 return previous.userState();
516}
517
518/*!
519 Returns the state of the current text block. If no value is set,
520 the returned value is -1.
521*/
522int QSyntaxHighlighter::currentBlockState() const
523{
524 Q_D(const QSyntaxHighlighter);
525 if (!d->currentBlock.isValid())
526 return -1;
527
528 return d->currentBlock.userState();
529}
530
531/*!
532 Sets the state of the current text block to \a newState.
533
534 \sa highlightBlock()
535*/
536void QSyntaxHighlighter::setCurrentBlockState(int newState)
537{
538 Q_D(QSyntaxHighlighter);
539 if (!d->currentBlock.isValid())
540 return;
541
542 d->currentBlock.setUserState(newState);
543}
544
545/*!
546 Attaches the given \a data to the current text block. The
547 ownership is passed to the underlying text document, i.e. the
548 provided QTextBlockUserData object will be deleted if the
549 corresponding text block gets deleted.
550
551 QTextBlockUserData can be used to store custom settings. In the
552 case of syntax highlighting, it is in particular interesting as
553 cache storage for information that you may figure out while
554 parsing the paragraph's text.
555
556 For example while parsing the text, you can keep track of
557 parenthesis characters that you encounter ('{[(' and the like),
558 and store their relative position and the actual QChar in a simple
559 class derived from QTextBlockUserData:
560
561 \snippet doc/src/snippets/code/src_gui_text_qsyntaxhighlighter.cpp 4
562
563 During cursor navigation in the associated editor, you can ask the
564 current QTextBlock (retrieved using the QTextCursor::block()
565 function) if it has a user data object set and cast it to your \c
566 BlockData object. Then you can check if the current cursor
567 position matches with a previously recorded parenthesis position,
568 and, depending on the type of parenthesis (opening or closing),
569 find the next opening or closing parenthesis on the same level.
570
571 In this way you can do a visual parenthesis matching and highlight
572 from the current cursor position to the matching parenthesis. That
573 makes it easier to spot a missing parenthesis in your code and to
574 find where a corresponding opening/closing parenthesis is when
575 editing parenthesis intensive code.
576
577 \sa QTextBlock::setUserData()
578*/
579void QSyntaxHighlighter::setCurrentBlockUserData(QTextBlockUserData *data)
580{
581 Q_D(QSyntaxHighlighter);
582 if (!d->currentBlock.isValid())
583 return;
584
585 d->currentBlock.setUserData(data);
586}
587
588/*!
589 Returns the QTextBlockUserData object previously attached to the
590 current text block.
591
592 \sa QTextBlock::userData(), setCurrentBlockUserData()
593*/
594QTextBlockUserData *QSyntaxHighlighter::currentBlockUserData() const
595{
596 Q_D(const QSyntaxHighlighter);
597 if (!d->currentBlock.isValid())
598 return 0;
599
600 return d->currentBlock.userData();
601}
602
603/*!
604 \since 4.4
605
606 Returns the current text block.
607 */
608QTextBlock QSyntaxHighlighter::currentBlock() const
609{
610 Q_D(const QSyntaxHighlighter);
611 return d->currentBlock;
612}
613
614QT_END_NAMESPACE
615
616#include "moc_qsyntaxhighlighter.cpp"
617
618#endif // QT_NO_SYNTAXHIGHLIGHTER
Note: See TracBrowser for help on using the repository browser.