2 * \file LaTeXHighlighter.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "LaTeXHighlighter.h"
16 #include <QTextDocument>
21 LaTeXHighlighter::LaTeXHighlighter(QTextDocument * parent)
22 : QSyntaxHighlighter(parent)
24 keywordFormat.setForeground(Qt::darkBlue);
25 keywordFormat.setFontWeight(QFont::Bold);
26 commentFormat.setForeground(Qt::darkGray);
27 mathFormat.setForeground(Qt::red);
31 void LaTeXHighlighter::highlightBlock(QString const & text)
34 static const QRegExp exprMath("\\$[^\\$]*\\$");
35 int index = text.indexOf(exprMath);
37 int length = exprMath.matchedLength();
38 setFormat(index, length, mathFormat);
39 index = text.indexOf(exprMath, index + length);
42 static const QRegExp exprStartDispMath("(\\\\\\[|"
43 "\\\\begin\\{equation\\**\\}|"
44 "\\\\begin\\{eqnarray\\**\\}|"
45 "\\\\begin\\{align(ed|at)*\\**\\}|"
46 "\\\\begin\\{flalign\\**\\}|"
47 "\\\\begin\\{gather\\**\\}|"
48 "\\\\begin\\{multline\\**\\}|"
49 "\\\\begin\\{array\\**\\}|"
50 "\\\\begin\\{cases\\**\\}"
52 static const QRegExp exprEndDispMath("(\\\\\\]|"
53 "\\\\end\\{equation\\**\\}|"
54 "\\\\end\\{eqnarray\\**\\}|"
55 "\\\\end\\{align(ed|at)*\\**\\}|"
56 "\\\\end\\{flalign\\**\\}|"
57 "\\\\end\\{gather\\**\\}|"
58 "\\\\end\\{multline\\**\\}|"
59 "\\\\end\\{array\\**\\}|"
60 "\\\\end\\{cases\\**\\}"
63 // if previous block was in 'disp math'
64 // start search from 0 (for end disp math)
65 // otherwise, start search from 'begin disp math'
66 if (previousBlockState() != 1)
67 startIndex = text.indexOf(exprStartDispMath);
68 while (startIndex >= 0) {
69 int endIndex = text.indexOf(exprEndDispMath, startIndex);
72 setCurrentBlockState(1);
73 length = text.length() - startIndex;
75 length = endIndex - startIndex + exprEndDispMath.matchedLength();
77 setFormat(startIndex, length, mathFormat);
78 startIndex = text.indexOf(exprStartDispMath, startIndex + length);
81 static const QRegExp exprKeyword("\\\\[A-Za-z]+");
82 index = text.indexOf(exprKeyword);
84 int length = exprKeyword.matchedLength();
85 setFormat(index, length, keywordFormat);
86 index = text.indexOf(exprKeyword, index + length);
89 // Treat a line as a comment starting at a percent sign
90 // * that is the first character in a line
91 // * that is preceded by
92 // ** an even number of backslashes
93 // ** any character other than a backslash
94 QRegExp exprComment("(?:^|[^\\\\])(?:\\\\\\\\)*(%).*$");
95 text.indexOf(exprComment);
96 index = exprComment.pos(1);
98 int const length = exprComment.matchedLength()
99 - (index - exprComment.pos(0));
100 setFormat(index, length, commentFormat);
101 text.indexOf(exprComment, index + length);
102 index = exprComment.pos(1);
106 } // namespace frontend