File indexing completed on 2024-03-24 05:54:38
0001 /* 0002 * SPDX-FileCopyrightText: 2002-2003 Jesper K. Pedersen <blackie@kde.org> 0003 * SPDX-FileCopyrightText: 2011 Morten A. B. Sjøgren <m_abs@mabs.dk> 0004 * 0005 * SPDX-License-Identifier: LGPL-2.0-only 0006 **/ 0007 0008 #include "qtregexphighlighter.h" 0009 0010 #include <QRegularExpression> 0011 #include <QTextEdit> 0012 0013 // krazy:excludeall=qclasses 0014 0015 QtRegexpHighlighter::QtRegexpHighlighter(QTextEdit *editor) 0016 : RegexpHighlighter(editor) 0017 , _editor(editor) 0018 { 0019 } 0020 0021 void QtRegexpHighlighter::highlightBlock(const QString &text) 0022 { 0023 QRegularExpression regexp(_regexp); 0024 QRegularExpression::PatternOptions options; 0025 if (!_caseSensitive) { 0026 options |= QRegularExpression::CaseInsensitiveOption; 0027 } 0028 if (!_minimal) { 0029 options |= QRegularExpression::InvertedGreedinessOption; 0030 } 0031 regexp.setPatternOptions(options); 0032 0033 QTextCharFormat format; 0034 format.setForeground(Qt::black); 0035 format.setFont(_editor->font()); 0036 setFormat(0, text.length(), format); 0037 0038 if (!regexp.isValid() || regexp.pattern().isEmpty()) { 0039 return; 0040 } 0041 0042 // ------------------------------ Process with the regular expression. 0043 QColor colors[] = {Qt::red, Qt::blue}; 0044 int color = previousBlockState(); 0045 if (color < 0 || color > 1) { 0046 color = 0; 0047 } 0048 0049 int index = 0; 0050 int start, length; 0051 QRegularExpressionMatch match; 0052 while ((index = text.indexOf(regexp, index, &match)) != -1 && index < (int)text.length()) { 0053 if (match.capturedStart(1) != -1) { 0054 start = match.capturedStart(1); 0055 length = match.captured(1).length(); 0056 } else { 0057 start = index; 0058 length = match.capturedLength(); 0059 } 0060 0061 if (start != index) { 0062 setFormat(index, start - index, colors[color]); 0063 } 0064 0065 QFont font = _editor->font(); 0066 font.setUnderline(true); 0067 font.setPointSize((int)(font.pointSize() * 1.3)); 0068 QTextCharFormat format; 0069 format.setFont(font); 0070 format.setForeground(colors[color]); 0071 setFormat(start, length, format); 0072 0073 if (length + (start - index) != match.capturedLength()) { 0074 setFormat(start + length, match.capturedLength() - length - (start - index), colors[color]); 0075 } 0076 0077 index += qMax(1, match.capturedLength()); // ensure progress when matching for example ^ or \b 0078 color = (color + 1) % 2; 0079 } 0080 setCurrentBlockState(color); 0081 }