00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020 #include <SyntaxHighLighter.hpp>
00021 #include <QtGui/QTextDocument>
00022 #include <QtGui/QTextLayout>
00023
00024 SyntaxHighLighter::
00025 SyntaxHighLighter(QObject *parent)
00026 : QObject(parent)
00027 {
00028 ;
00029 }
00030
00031 SyntaxHighLighter::
00032 ~SyntaxHighLighter()
00033 {
00034 ;
00035 }
00036
00037 void SyntaxHighLighter::
00038 addToDocument(QTextDocument *doc)
00039 {
00040 connect(doc, SIGNAL(contentsChange(int, int, int)),
00041 this, SLOT(highlight(int, int, int)));
00042 }
00043
00044 void SyntaxHighLighter::
00045 addMapping(const QString &pattern,
00046 const QTextCharFormat &format)
00047 {
00048 __mappings[pattern] = format;
00049 }
00050
00051 void SyntaxHighLighter::
00052 highlight(int position, int removed, int added)
00053 {
00054 QTextDocument *doc = qobject_cast<QTextDocument *>(sender());
00055
00056 QTextBlock block = doc->findBlock(position);
00057 if (!block.isValid())
00058 return;
00059
00060 QTextBlock endBlock;
00061 if (added > removed)
00062 endBlock = doc->findBlock(position + added);
00063 else
00064 endBlock = block;
00065
00066 while (block.isValid() && !(endBlock < block)) {
00067 highlightBlock(block);
00068 block = block.next();
00069 }
00070 }
00071
00072 void SyntaxHighLighter::
00073 highlightBlock(QTextBlock block)
00074 {
00075 QTextLayout *layout = block.layout();
00076 const QString text = block.text();
00077
00078 QList<QTextLayout::FormatRange> overrides;
00079
00080 foreach (QString pattern, __mappings.keys()) {
00081 QRegExp expression(pattern);
00082 int i = text.indexOf(expression);
00083 while (i >= 0) {
00084 QTextLayout::FormatRange range;
00085 range.start = i;
00086 range.length = expression.matchedLength();
00087 range.format = __mappings[pattern];
00088 range.format.setFontFamily("Courier New");
00089 range.format.setFontPointSize(10);
00090
00091 overrides << range;
00092
00093 i = text.indexOf(expression, i + expression.matchedLength());
00094 }
00095 }
00096
00097 layout->setAdditionalFormats(overrides);
00098 const_cast<QTextDocument *>(block.document())->markContentsDirty(block.position(), block.length());
00099 }