// SPDX-FileCopyrightText: 2023 James Graham // SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // // Adapted from NeoChat's src/libneochat/texthandler.cpp and utils.h. See the // note at the top of TextHandler.h for what is ported and what is not. #include "TextHandler.h" #include #include #include using namespace Qt::StringLiterals; // Ported verbatim from NeoChat's utils.h, minus the Matrix ones (mxId, // matrixLink) and minus the magnet/matrix schemes, which mean nothing here. // // the (*SKIP)(*F) prefix is what stops the pass from linkifying the inside of an // anchor it has already written. namespace TextRegex { static const QRegularExpression plainUrl(uR"((*SKIP)(*F)|\b((www\.(?!\.)(?!(\w|\.|-)+@)|(https?|ftp):(//)?\w)(&(?![lg]t;)|[^&\s<>"])+(&(?![lg]t;)|[^?&!,.\s<>"\]):])))"_s, QRegularExpression::CaseInsensitiveOption | QRegularExpression::UseUnicodePropertiesOption); static const QRegularExpression emailAddress(uR"((*SKIP)(*F)|\b(mailto:)?((\w|\.|-)+@(\w|\.|-)+\.\w+\b))"_s, QRegularExpression::CaseInsensitiveOption | QRegularExpression::UseUnicodePropertiesOption); } TextHandler::TextHandler(QObject *parent) : QObject(parent) { } QString TextHandler::escapeHtml(QString stringIn) { // Upstream leaves & alone because cmark has already escaped it by the time // the string reaches them. Nothing escapes it on the way here, so it goes // first - after the other two it would eat the entities they just wrote. stringIn.replace(u'&', u"&"_s); stringIn.replace(u'<', u"<"_s); stringIn.replace(u'>', u">"_s); return stringIn; } QString TextHandler::unescapeHtml(QString stringIn) { // For those situations where brackets in code block get double escaped stringIn.replace(u"&lt;"_s, u"<"_s); stringIn.replace(u"&gt;"_s, u">"_s); stringIn.replace(u"<"_s, u"<"_s); stringIn.replace(u">"_s, u">"_s); stringIn.replace(u"&"_s, u"&"_s); stringIn.replace(u"""_s, u"\""_s); stringIn.replace(u"'"_s, u"'"_s); stringIn.replace(u" "_s, u" "_s); return stringIn; } // Upstream's loop, with the Matrix id pass dropped and one thing added: the // anchor's visible text is shortened when the URL is long, while href keeps the // whole thing. A pasted tracking URL is otherwise three lines of the timeline. QString TextHandler::linkifyUrls(QString stringIn, int elideAt) { const auto elide = [elideAt](const QString &url) { if (elideAt <= 0 || url.length() <= elideAt) { return url; } // Cut in the middle rather than at the end: the host is the part that // says where the link goes, and it is at the front. const int head = elideAt * 2 / 3; const int tail = elideAt - head; return QString(url.left(head) + QString::fromUtf8("\xe2\x80\xa6") + url.right(tail)); }; QRegularExpressionMatch match; int start = 0; for (int index = 0; index != -1; index = stringIn.indexOf(TextRegex::plainUrl, start, &match)) { int skip = 0; if (match.captured(0).size() > 0) { if (stringIn.left(index).count(u""_s) == stringIn.left(index).count(u""_s)) { const auto target = match.captured(1); // A bare www. link is not a URL until it has a scheme, or the // text item will resolve it against the document and open // nothing at all. const auto href = target.startsWith(u"www."_s, Qt::CaseInsensitive) ? u"https://"_s + target : target; auto replacement = u"%2"_s.arg(href, elide(target)); stringIn = stringIn.replace(index, match.captured(0).size(), replacement); skip = replacement.length(); } else { skip = match.captured().length(); } } start = index + skip; match = {}; } start = 0; match = {}; for (int index = 0; index != -1; index = stringIn.indexOf(TextRegex::emailAddress, start, &match)) { int skip = 0; if (match.captured(0).size() > 0) { if (stringIn.left(index).count(u""_s) == stringIn.left(index).count(u""_s)) { auto replacement = u"%1"_s.arg(match.captured(2)); stringIn = stringIn.replace(index, match.captured(0).size(), replacement); skip = replacement.length(); } else { skip = match.captured().length(); } } start = index + skip; match = {}; } return stringIn; } // Ported from upstream unchanged. Pairs up an inline syntax, skipping anything // that falls inside a code span, inside an anchor, or inside a bare URL. void TextHandler::processWithinHTML(QString &buffer, const QString &syntax, const QString &beginTag, const QString &endTag) { qsizetype beginCodeBlockTag = buffer.indexOf(u""_s); qsizetype endCodeBlockTag = buffer.indexOf(u""_s, beginCodeBlockTag + 1); qsizetype beginlinkBlockTag = buffer.indexOf(u""_s, beginCodeBlockTag + 1); QRegularExpressionMatch plainLinkMatch; qsizetype plainLink = buffer.indexOf(TextRegex::plainUrl, 0, &plainLinkMatch); // Index to search from qsizetype lastPos = 0; while (true) { const qsizetype pos = buffer.indexOf(syntax, lastPos); if (pos == -1) { break; } // if we're inside a code block, ignore and move the search past this code block const bool validCodeBlock = beginCodeBlockTag != -1 && endCodeBlockTag != -1; if (validCodeBlock && pos > beginCodeBlockTag && pos < endCodeBlockTag) { lastPos = endCodeBlockTag + 7; // since we moved past this code block, make sure to update the indices for the next one beginCodeBlockTag = buffer.indexOf(u""_s, lastPos + 1); endCodeBlockTag = buffer.indexOf(u""_s, beginCodeBlockTag + 1); continue; } const bool validLinkBlock = beginlinkBlockTag != -1 && endLinkBlockTag != -1; if (validLinkBlock && pos > beginlinkBlockTag && pos < endLinkBlockTag) { lastPos = endLinkBlockTag + 4; beginlinkBlockTag = buffer.indexOf(u""_s, beginlinkBlockTag + 1); continue; } if (plainLink != -1 && pos > plainLink && pos < plainLink + plainLinkMatch.capturedLength()) { lastPos = plainLink + plainLinkMatch.capturedLength(); plainLink = buffer.indexOf(TextRegex::plainUrl, lastPos, &plainLinkMatch); continue; } const auto findNextPos = [&pos, &buffer, &syntax] { return buffer.indexOf(syntax, pos + 1); }; // Find the next valid closing character qsizetype nextPos = findNextPos(); if (nextPos == -1) { break; } // Replace the beginning syntax buffer.replace(pos, syntax.length(), beginTag); // Update positions and re-search since the underlying text buffer changed nextPos = findNextPos(); // now replace the end syntax buffer.replace(nextPos, syntax.length(), endTag); // if we have begun checking spoilers past our current code block, make sure we're in the next one (if it exists) if (nextPos > endCodeBlockTag) { beginCodeBlockTag = buffer.indexOf(u""_s, nextPos + 1); endCodeBlockTag = buffer.indexOf(u""_s, beginCodeBlockTag + 1); } // Move the search pointer past this point. // not technically needed in most cases since we replaced the original tag, but needed for code blocks // which still have the characters. lastPos = nextPos + syntax.length(); } } // Local. Single backticks, done before anything else touches the segment so the // markers are in place for every guard above to see. QString TextHandler::markInlineCode(const QString &stringIn) { QString buffer = stringIn; processWithinHTML(buffer, u"`"_s, u""_s, u""_s); return buffer; } // Local. Whole-word match on the name, so "sam" does not light up "sample". QString TextHandler::highlightMentions(QString stringIn, const QString &name, const QString &colour) { if (name.isEmpty()) { return stringIn; } // Captured rather than matched bare so the replacement can use \1: the // whole-match backreference is the one that differs between regex engines. const QRegularExpression mention(u"(\\b"_s + QRegularExpression::escape(name) + u"\\b)"_s, QRegularExpression::CaseInsensitiveOption); return stringIn.replace(mention, u"\\1"_s.arg(colour)); } QString TextHandler::renderSegment(QString segment, const QVariantMap &options) const { const auto colour = [&options](const char *key, const QString &fallback) { const auto v = options.value(QString::fromUtf8(key)).toString(); return v.isEmpty() ? fallback : v; }; segment = escapeHtml(std::move(segment)); segment = markInlineCode(segment); segment = linkifyUrls(std::move(segment), options.value(u"elideLinksAt"_s, 48).toInt()); // Order matters: the two-character syntaxes go first, or the single-asterisk // pass would take the first character of a ** pair and leave the second. processWithinHTML(segment, u"**"_s, u""_s, u""_s); processWithinHTML(segment, u"~~"_s, u""_s, u""_s); const bool revealed = options.value(u"spoilerRevealed"_s, false).toBool(); const QString spoilerBg = colour("spoilerBackground", u"#808080"_s); // Hidden is the text colour painted on itself, which is a solid block the // width of the words behind it. Revealed is left completely unstyled rather // than tinted: a background that stays behind revealed text is a second // thing to read past, and the reader has already asked to see it. const QString spoilerOpen = revealed ? u""_s : u""_s.arg(spoilerBg); processWithinHTML(segment, u"||"_s, spoilerOpen, u""_s); processWithinHTML(segment, u"*"_s, u""_s, u""_s); // Upstream also pairs a single _ into , to match what Qt's markdown // writer emits. Not done here: upstream is reading markdown somebody wrote // by hand, and this is reading whatever was typed - which turns // some_variable_name into "somevariablename" the first time anybody // pastes an identifier. segment = highlightMentions(std::move(segment), options.value(u"mentionName"_s).toString(), colour("mentionColor", u"#3daee9"_s)); segment.replace(u'\n', u"
"_s); return segment; } namespace { qsizetype findTagEnd(const QString &html, qsizetype start) { QChar quote; for (qsizetype i = start; i < html.size(); ++i) { const QChar c = html.at(i); if (!quote.isNull()) { if (c == quote) quote = QChar(); continue; } if (c == u'\'' || c == u'"') { quote = c; continue; } if (c == u'>') return i; } return -1; } QString decodeEntities(const QString &text) { static const QRegularExpression entity(uR"(&(#x[0-9A-Fa-f]+|#[0-9]+|[A-Za-z][A-Za-z0-9]+);)"_s); QString out; qsizetype last = 0; auto it = entity.globalMatch(text); while (it.hasNext()) { const auto match = it.next(); out += text.mid(last, match.capturedStart() - last); const QString name = match.captured(1); bool ok = false; char32_t code = 0; if (name.startsWith(u'#')) { const bool hex = name.size() > 1 && (name.at(1) == u'x' || name.at(1) == u'X'); code = name.mid(hex ? 2 : 1).toUInt(&ok, hex ? 16 : 10); } else if (name == u"amp"_s) { code = u'&'; ok = true; } else if (name == u"lt"_s) { code = u'<'; ok = true; } else if (name == u"gt"_s) { code = u'>'; ok = true; } else if (name == u"quot"_s) { code = u'"'; ok = true; } else if (name == u"apos"_s) { code = u'\''; ok = true; } else if (name == u"nbsp"_s) { code = u' '; ok = true; } if (ok && code > 0 && code <= 0x10FFFF && !(code >= 0xD800 && code <= 0xDFFF)) out += QString::fromUcs4(&code, 1); else out += match.captured(0); last = match.capturedEnd(); } out += text.mid(last); return out; } bool safeColour(const QString &value) { const QString colour = value.trimmed(); static const QRegularExpression hex(uR"(^#[0-9A-Fa-f]{3,8}$)"_s); if (hex.match(colour).hasMatch()) return true; static const QRegularExpression functional(uR"(^(rgb|rgba|hsl|hsla)\(\s*[0-9.,%\s]+\)$)"_s, QRegularExpression::CaseInsensitiveOption); if (functional.match(colour).hasMatch()) return true; static const QRegularExpression named(uR"(^[A-Za-z]{1,20}$)"_s); return named.match(colour).hasMatch(); } QString cleanStyle(const QString &style) { QStringList kept; const auto declarations = style.split(u';'); for (const QString &declaration : declarations) { const qsizetype colon = declaration.indexOf(u':'); if (colon <= 0) continue; const QString property = declaration.left(colon).trimmed().toLower(); const QString value = declaration.mid(colon + 1).trimmed(); if ((property == u"color"_s || property == u"background-color"_s) && safeColour(value)) kept.append(property + u": "_s + value); } return kept.join(u"; "_s); } QHash parseAttributes(const QString &text) { QHash attributes; static const QRegularExpression attribute(uR"re(([A-Za-z_:][-A-Za-z0-9_:.]*)\s*(?:=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?)re"_s); auto it = attribute.globalMatch(text); while (it.hasNext()) { const auto match = it.next(); const QString name = match.captured(1).toLower(); if (name.isEmpty() || attributes.contains(name)) continue; const QString value = !match.captured(2).isNull() ? match.captured(2) : !match.captured(3).isNull() ? match.captured(3) : match.captured(4); attributes.insert(name, decodeEntities(value)); } return attributes; } bool safeHref(const QString &href) { const QUrl url(href.trimmed()); if (!url.isValid() || url.isRelative()) return false; const QString scheme = url.scheme().toLower(); return scheme == u"http"_s || scheme == u"https"_s || scheme == u"mailto"_s; } QString escapeAttribute(QString value) { value.replace(u'&', u"&"_s); value.replace(u'<', u"<"_s); value.replace(u'>', u">"_s); value.replace(u'"', u"""_s); value.replace(u'\'', u"'"_s); return value; } } // namespace QString TextHandler::sanitizeFormattedBody(const QString &html) { static const QSet allowed = { u"b"_s, u"i"_s, u"u"_s, u"s"_s, u"code"_s, u"pre"_s, u"blockquote"_s, u"p"_s, u"br"_s, u"ul"_s, u"ol"_s, u"li"_s, u"a"_s, u"span"_s, }; static const QHash renamed = { {u"strong"_s, u"b"_s}, {u"em"_s, u"i"_s}, {u"del"_s, u"s"_s}, {u"strike"_s, u"s"_s}, }; static const QSet skippedWithContent = { u"script"_s, u"style"_s, u"iframe"_s, u"object"_s, u"embed"_s, u"template"_s, u"svg"_s, u"math"_s, u"mx-reply"_s, }; static const QRegularExpression nameExpression(uR"(^([A-Za-z][A-Za-z0-9]*))"_s); QString out; qsizetype pos = 0; while (pos < html.size()) { const qsizetype lt = html.indexOf(u'<', pos); if (lt < 0) { out += escapeHtml(decodeEntities(html.mid(pos))); break; } if (lt > pos) out += escapeHtml(decodeEntities(html.mid(pos, lt - pos))); if (html.mid(lt, 4) == u""_s, lt + 4); pos = end < 0 ? html.size() : end + 3; continue; } const qsizetype gt = findTagEnd(html, lt + 1); if (gt < 0) { out += u"<"_s; out += escapeHtml(decodeEntities(html.mid(lt + 1))); break; } QString inside = html.mid(lt + 1, gt - lt - 1).trimmed(); if (inside.isEmpty() || inside.startsWith(u'!') || inside.startsWith(u'?')) { pos = gt + 1; continue; } const bool closing = inside.startsWith(u'/'); if (closing) inside = inside.mid(1).trimmed(); bool selfClosing = false; if (inside.endsWith(u'/')) { selfClosing = true; inside.chop(1); inside = inside.trimmed(); } const auto nameMatch = nameExpression.match(inside); if (!nameMatch.hasMatch()) { out += u"<"_s; out += escapeHtml(decodeEntities(html.mid(lt + 1, gt - lt - 1))); out += u">"_s; pos = gt + 1; continue; } const QString name = nameMatch.captured(1).toLower(); if (skippedWithContent.contains(name)) { if (!closing) { const QRegularExpression closeExpression(uR"("_s; pos = gt + 1; continue; } const QHash attributes = parseAttributes(inside.mid(nameMatch.capturedLength())); if (tag == u"br"_s) { out += u"
"_s; } else if (tag == u"a"_s) { out += u""_s; } else if (tag == u"span"_s) { QString style = cleanStyle(attributes.value(u"style"_s)); const QString foreground = attributes.value(u"data-mx-color"_s); const QString background = attributes.value(u"data-mx-bg-color"_s); if (safeColour(foreground)) style += (style.isEmpty() ? QString() : u"; "_s) + u"color: "_s + foreground; if (safeColour(background)) style += (style.isEmpty() ? QString() : u"; "_s) + u"background-color: "_s + background; out += u""_s; } else if (tag == u"ol"_s) { bool ok = false; const int start = attributes.value(u"start"_s).toInt(&ok); out += ok && start > 0 ? u"
    "_s.arg(start) : u"
      "_s; } else { out += u"<"_s + tag + u">"_s; } if (selfClosing && tag != u"br"_s) out += u""_s; pos = gt + 1; } return out.trimmed(); } QString TextHandler::renderFormatted(const QString &html, const QVariantMap &options) const { QString safe = sanitizeFormattedBody(html); if (safe.isEmpty()) return {}; static const QRegularExpression spoiler(uR"(]*\bdata-mx-spoiler\b[^>]*>)"_s, QRegularExpression::CaseInsensitiveOption); const bool revealed = options.value(u"spoilerRevealed"_s, false).toBool(); if (revealed) { safe.replace(spoiler, u""_s); } else { const QString background = options.value(u"spoilerBackground"_s, u"#808080"_s).toString(); safe.replace(spoiler, u""_s.arg(escapeAttribute(background))); } return safe; } QStringList TextHandler::codeBlocks(const QString &plain) const { QStringList blocks; const auto parts = plain.split(u"```"_s); // Odd indices are the inside of a fence, but only when the fences pair up. // an unclosed trailing fence is still being typed and has no block in it. if (parts.size() % 2 == 0) { return blocks; } for (int i = 1; i < parts.size(); i += 2) { QString body = parts.at(i); // A language tag on the opening fence is not part of the code. const int firstNewline = body.indexOf(u'\n'); if (firstNewline >= 0 && !body.left(firstNewline).contains(u' ')) { body = body.mid(firstNewline + 1); } blocks.append(body.trimmed()); } return blocks; } QString TextHandler::toRichText(const QString &plain, const QVariantMap &options) const { const auto parts = plain.split(u"```"_s); const bool fencesBalanced = parts.size() % 2 == 1; QString out; for (int i = 0; i < parts.size(); ++i) { const bool isCode = (i % 2 == 1) && fencesBalanced; if (!isCode) { // an unclosed trailing fence is text, including the ``` itself, // which is what the writer sees while they are still typing it. if (i > 0 && !fencesBalanced) { out += escapeHtml(u"```"_s); } out += renderSegment(parts.at(i), options); continue; } QString body = parts.at(i); const int firstNewline = body.indexOf(u'\n'); if (firstNewline >= 0 && !body.left(firstNewline).contains(u' ')) { body = body.mid(firstNewline + 1); } const auto bg = options.value(u"codeBackground"_s).toString(); out += u"
      %2
      "_s.arg(bg.isEmpty() ? u"#00000018"_s : bg, escapeHtml(body.trimmed()).replace(u'\n', u"
      "_s)); } return out; }