File indexing completed on 2024-11-03 04:35:41

0001 /*
0002    SPDX-FileCopyrightText: 2018-2024 Laurent Montel <montel@kde.org>
0003 
0004    SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "texthighlighter.h"
0008 
0009 #include <KSyntaxHighlighting/Format>
0010 #include <KSyntaxHighlighting/State>
0011 #include <KSyntaxHighlighting/Theme>
0012 
0013 #include <QTextStream>
0014 
0015 TextHighlighter::TextHighlighter(QTextStream *stream)
0016     : mStream(stream)
0017 {
0018 }
0019 
0020 void TextHighlighter::highlight(const QString &str)
0021 {
0022     *mStream << QStringLiteral("<code>");
0023 
0024     KSyntaxHighlighting::State state;
0025 
0026     int lineStart = 0;
0027     int lineEnd = str.indexOf(QLatin1Char('\n'));
0028 
0029     for (; lineEnd != -1; lineStart = lineEnd + 1, lineEnd = str.indexOf(QLatin1Char('\n'), lineStart)) {
0030         mCurrentLine = str.mid(lineStart, lineEnd - lineStart);
0031         state = highlightLine(mCurrentLine, state);
0032         *mStream << QStringLiteral("<br>");
0033     }
0034     if (lineStart < str.size()) { // remaining content if str isn't ending with a newline
0035         mCurrentLine = str.mid(lineStart);
0036         state = highlightLine(mCurrentLine, state);
0037     }
0038     *mStream << QLatin1String("</code>");
0039 }
0040 
0041 void TextHighlighter::applyFormat(int offset, int length, const KSyntaxHighlighting::Format &format)
0042 {
0043     if (!format.isDefaultTextStyle(theme())) {
0044         *mStream << QStringLiteral("<span style=\"");
0045         if (format.hasTextColor(theme())) {
0046             *mStream << QStringLiteral("color:") << format.textColor(theme()).name() << QStringLiteral(";");
0047         }
0048         if (format.hasBackgroundColor(theme())) {
0049             *mStream << QStringLiteral("background-color:") << format.backgroundColor(theme()).name() << QStringLiteral(";");
0050         }
0051         if (format.isBold(theme())) {
0052             *mStream << QStringLiteral("font-weight:bold;");
0053         }
0054         if (format.isItalic(theme())) {
0055             *mStream << QStringLiteral("font-style:italic;");
0056         }
0057         if (format.isUnderline(theme())) {
0058             *mStream << QStringLiteral("text-decoration:underline;");
0059         }
0060         if (format.isStrikeThrough(theme())) {
0061             *mStream << QStringLiteral("text-decoration:line-through;");
0062         }
0063         *mStream << QStringLiteral("\">");
0064     }
0065 
0066     *mStream << mCurrentLine.mid(offset, length).toHtmlEscaped().replace(QLatin1Char(' '), QLatin1String("&nbsp;"));
0067 
0068     if (!format.isDefaultTextStyle(theme())) {
0069         *mStream << QStringLiteral("</span>");
0070     }
0071 }