gui: preserve newlines in plaintext blocks

This commit is contained in:
Levi Neely 2026-08-03 00:24:52 +02:00
parent 4dabab1f71
commit b841f556d4
1 changed files with 19 additions and 13 deletions

View File

@ -201,9 +201,13 @@ QString ChatBlockModel::renderMarkdown(const QString &markdown) const
auto it = fenceRe.globalMatch(markdown); auto it = fenceRe.globalMatch(markdown);
while (it.hasNext()) { while (it.hasNext()) {
const auto match = it.next(); const auto match = it.next();
QTextDocument prose; // Prose before this fence: HTML-escape and wrap in pre-wrap div to
prose.setMarkdown(markdown.mid(cursor, match.capturedStart() - cursor)); // preserve newlines and whitespace. QTextDocument::setMarkdown would
result += prose.toHtml(); // collapse single newlines (standard Markdown behavior).
const QString prose = markdown.mid(cursor, match.capturedStart() - cursor);
if (!prose.isEmpty())
result += QStringLiteral("<div style=\"white-space:pre-wrap\">")
+ prose.toHtmlEscaped() + QStringLiteral("</div>");
result += highlightCode(match.captured(2), match.captured(1)); result += highlightCode(match.captured(2), match.captured(1));
cursor = match.capturedEnd(); cursor = match.capturedEnd();
} }
@ -215,16 +219,18 @@ QString ChatBlockModel::renderMarkdown(const QString &markdown) const
R"(^```([A-Za-z0-9_+.-]*)[^\n]*\n([\s\S]*)$)", R"(^```([A-Za-z0-9_+.-]*)[^\n]*\n([\s\S]*)$)",
QRegularExpression::MultilineOption); QRegularExpression::MultilineOption);
const auto tail = markdown.mid(cursor); const auto tail = markdown.mid(cursor);
const auto open = openFenceRe.match(tail); if (!tail.isEmpty()) {
if (open.hasMatch()) { const auto open = openFenceRe.match(tail);
QTextDocument prose; if (open.hasMatch()) {
prose.setMarkdown(tail.left(open.capturedStart())); const QString prose = tail.left(open.capturedStart());
result += prose.toHtml(); if (!prose.isEmpty())
result += highlightCode(open.captured(2), open.captured(1)); result += QStringLiteral("<div style=\"white-space:pre-wrap\">")
} else { + prose.toHtmlEscaped() + QStringLiteral("</div>");
QTextDocument prose; result += highlightCode(open.captured(2), open.captured(1));
prose.setMarkdown(tail); } else {
result += prose.toHtml(); result += QStringLiteral("<div style=\"white-space:pre-wrap\">")
+ tail.toHtmlEscaped() + QStringLiteral("</div>");
}
} }
return result; return result;
} }