1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the documentation of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:FDL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Free Documentation License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Free
19 ** Documentation License version 1.3 as published by the Free Software
20 ** Foundation and appearing in the file included in the packaging of
21 ** this file. Please review the following information to ensure
22 ** the GNU Free Documentation License version 1.3 requirements
23 ** will be met: http://www.gnu.org/copyleft/fdl.html.
26 ****************************************************************************/
29 \example richtext/syntaxhighlighter
30 \title Syntax Highlighter Example
31 \group examples-richtext
32 \brief The Syntax Highligher example shows how to perform
33 simple syntax highlighing.
35 \brief The Syntax Highlighter example shows how to perform simple syntax
36 highlighting by subclassing the QSyntaxHighlighter class.
38 \image syntaxhighlighter-example.png
40 The Syntax Highlighter application displays C++ files with custom
43 The example consists of two classes:
46 \li The \c Highlighter class defines and applies the
48 \li The \c MainWindow widget is the application's main window.
51 We will first review the \c Highlighter class to see how you can
52 customize the QSyntaxHighlighter class to fit your preferences,
53 then we will take a look at the relevant parts of the \c
54 MainWindow class to see how you can use your custom highlighter
55 class in an application.
57 \section1 Highlighter Class Definition
59 \snippet richtext/syntaxhighlighter/highlighter.h 0
61 To provide your own syntax highlighting, you must subclass
62 QSyntaxHighlighter, reimplement the \l
63 {QSyntaxHighlighter::highlightBlock()}{highlightBlock()} function,
64 and define your own highlighting rules.
66 We have chosen to store our highlighting rules using a private
67 struct: A rule consists of a QRegExp pattern and a QTextCharFormat
68 instance. The various rules are then stored using a QVector.
70 The QTextCharFormat class provides formatting information for
71 characters in a QTextDocument specifying the visual properties of
72 the text, as well as information about its role in a hypertext
73 document. In this example, we will only define the font weight and
74 color using the QTextCharFormat::setFontWeight() and
75 QTextCharFormat::setForeground() functions.
77 \section1 Highlighter Class Implementation
79 When subclassing the QSyntaxHighlighter class you must pass the
80 parent parameter to the base class constructor. The parent is the
81 text document upon which the syntax highligning will be
82 applied. In this example, we have also chosen to define our
83 highlighting rules in the constructor:
85 \snippet richtext/syntaxhighlighter/highlighter.cpp 0
86 \snippet richtext/syntaxhighlighter/highlighter.cpp 1
88 First we define a keyword rule which recognizes the most common
89 C++ keywords. We give the \c keywordFormat a bold, dark blue
90 font. For each keyword, we assign the keyword and the specified
91 format to a HighlightingRule object and append the object to our
94 \snippet richtext/syntaxhighlighter/highlighter.cpp 2
96 \snippet richtext/syntaxhighlighter/highlighter.cpp 4
98 \snippet richtext/syntaxhighlighter/highlighter.cpp 5
100 Then we create a format that we will apply to Qt class names. The
101 class names will be rendered with a dark magenta color and a bold
102 style. We specify a string pattern that is actually a regular
103 expression capturing all Qt class names. Then we assign the
104 regular expression and the specified format to a HighlightingRule
105 object and append the object to our list of rules.
107 We also define highlighting rules for quotations and functions
108 using the same approach: The patterns have the form of regular
109 expressions and are stored in HighlightingRule objects with the
112 \snippet richtext/syntaxhighlighter/highlighter.cpp 3
114 \snippet richtext/syntaxhighlighter/highlighter.cpp 6
116 The C++ language has two variations of comments: The single line
117 comment (\c //) and the multiline comment (\c{/*...*}\c{/}). The single
118 line comment can easily be defined through a highlighting rule
119 similar to the previous ones. But the multiline comment needs
120 special care due to the design of the QSyntaxHighlighter class.
122 After a QSyntaxHighlighter object is created, its \l
123 {QSyntaxHighlighter::highlightBlock()}{highlightBlock()} function
124 will be called automatically whenever it is necessary by the rich
125 text engine, highlighting the given text block. The problem
126 appears when a comment spans several text blocks. We will take a
127 closer look at how this problem can be solved when reviewing the
128 implementation of the \c Highlighter::highlightBlock()
129 function. At this point we only specify the multiline comment's
132 \snippet richtext/syntaxhighlighter/highlighter.cpp 7
134 The highlightBlock() function is called automatically whenever it
135 is necessary by the rich text engine, i.e. when there are text
136 blocks that have changed.
138 First we apply the syntax highlighting rules that we stored in the
139 \c highlightingRules vector. For each rule (i.e. for each
140 HighlightingRule object) we search for the pattern in the given
141 textblock using the QString::indexOf() function. When the first
142 occurrence of the pattern is found, we use the
143 QRegExp::matchedLength() function to determine the string that
144 will be formatted. QRegExp::matchedLength() returns the length of
145 the last matched string, or -1 if there was no match.
147 To perform the actual formatting the QSyntaxHighlighter class
148 provides the \l {QSyntaxHighlighter::setFormat()}{setFormat()}
149 function. This function operates on the text block that is passed
150 as argument to the \c highlightBlock() function. The specified
151 format is applied to the text from the given start position for
152 the given length. The formatting properties set in the given
153 format are merged at display time with the formatting information
154 stored directly in the document. Note that the document itself
155 remains unmodified by the format set through this function.
157 This process is repeated until the last occurrence of the pattern
158 in the current text block is found.
160 \snippet richtext/syntaxhighlighter/highlighter.cpp 8
162 To deal with constructs that can span several text blocks (like
163 the C++ multiline comment), it is necessary to know the end state
164 of the previous text block (e.g. "in comment"). Inside your \c
165 highlightBlock() implementation you can query the end state of the
166 previous text block using the
167 QSyntaxHighlighter::previousBlockState() function. After parsing
168 the block you can save the last state using
169 QSyntaxHighlighter::setCurrentBlockState().
172 {QSyntaxHighlighter::previousBlockState()}{previousBlockState()}
173 function return an int value. If no state is set, the returned
174 value is -1. You can designate any other value to identify any
175 given state using the \l
176 {QSyntaxHighlighter::setCurrentBlockState()}{setCurrentBlockState()}
177 function. Once the state is set, the QTextBlock keeps that value
178 until it is set again or until the corresponding paragraph of text
181 In this example we have chosen to use 0 to represent the "not in
182 comment" state, and 1 for the "in comment" state. When the stored
183 syntax highlighting rules are applied we initialize the current
186 \snippet richtext/syntaxhighlighter/highlighter.cpp 9
188 If the previous block state was "in comment" (\c
189 {previousBlockState() == 1}), we start the search for an end
190 expression at the beginning of the text block. If the
191 previousBlockState() returns 0, we start the search at the
192 location of the first occurrence of a start expression.
194 \snippet richtext/syntaxhighlighter/highlighter.cpp 10
195 \snippet richtext/syntaxhighlighter/highlighter.cpp 11
197 When an end expression is found, we calculate the length of the
198 comment and apply the multiline comment format. Then we search for
199 the next occurrence of the start expression and repeat the
200 process. If no end expression can be found in the current text
201 block we set the current block state to 1, i.e. "in comment".
203 This completes the \c Highlighter class implementation; it is now
206 \section1 MainWindow Class Definition
208 Using a QSyntaxHighlighter subclass is simple; just provide your
209 application with an instance of the class and pass it the document
210 upon which you want the highlighting to be applied.
212 \snippet richtext/syntaxhighlighter/mainwindow.h 0
214 In this example we declare a pointer to a \c Highlighter instance
215 which we later will initialize in the private \c setupEditor()
218 \section1 MainWindow Class Implementation
220 The constructor of the main window is straight forward. We first
221 set up the menus, then we initialize the editor and make it the
222 central widget of the application. Finally we set the main
225 \snippet richtext/syntaxhighlighter/mainwindow.cpp 0
227 We initialize and install the \c Highlighter object in the private
228 setupEditor() convenience function:
230 \snippet richtext/syntaxhighlighter/mainwindow.cpp 1
232 First we create the font we want to use in the editor, then we
233 create the editor itself which is an instance of the QTextEdit
234 class. Before we initialize the editor with the \c MainWindow
235 class definition file, we create a \c Highlighter instance passing
236 the editor's document as argument. This is the document that the
237 highlighting will be applied to. Then we are done.
239 A QSyntaxHighlighter object can only be installed on one document
240 at the time, but you can easily reinstall the highlighter on
241 another document using the QSyntaxHighlighter::setDocument()
242 function. The QSyntaxHighlighter class also provides the \l
243 {QSyntaxHighlighter::document()}{document()} function which
244 returns the currently set document.
246 \section1 Other Code Editor Features
248 It is possible to implement parenthesis matching with
249 QSyntaxHighlighter. The "Matching Parentheses with
250 QSyntaxHighlighter" article in Qt Quarterly 31
251 (\l{http://doc.qt.nokia.com/qq/}) implements this. We also have
252 the \l{Code Editor Example}, which shows how to implement line
253 numbers and how to highlight the current line.