From be93ee75deb2c4afdcc49ef1f56f0e0aa6bd93c2 Mon Sep 17 00:00:00 2001 From: Jared Van Bortel Date: Thu, 18 Apr 2024 14:50:32 -0400 Subject: [PATCH] responsetext : fix markdown code block trimming (#2232) Signed-off-by: Jared Van Bortel --- gpt4all-chat/responsetext.cpp | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/gpt4all-chat/responsetext.cpp b/gpt4all-chat/responsetext.cpp index 3e2f51f9..534a6f9a 100644 --- a/gpt4all-chat/responsetext.cpp +++ b/gpt4all-chat/responsetext.cpp @@ -1045,8 +1045,6 @@ void ResponseText::handleCodeBlocks() static const QRegularExpression reCode("```(.*?)(```|$)", QRegularExpression::DotMatchesEverythingOption); QRegularExpressionMatchIterator iCode = reCode.globalMatch(doc->toPlainText()); - static const QRegularExpression reWhitespace("^\\s*(\\w+)"); - QList matchesCode; while (iCode.hasNext()) matchesCode.append(iCode.next()); @@ -1062,9 +1060,13 @@ void ResponseText::handleCodeBlocks() QString capturedText = matchesCode[index].captured(1); QString codeLanguage; - QRegularExpressionMatch match = reWhitespace.match(capturedText); - if (match.hasMatch()) { - const QString firstWord = match.captured(1).trimmed(); + QStringList lines = capturedText.split('\n'); + if (lines.last().isEmpty()) { + lines.removeLast(); + } + + if (lines.count() >= 2) { + const auto &firstWord = lines.first(); if (firstWord == "python" || firstWord == "cpp" || firstWord == "c++" @@ -1082,12 +1084,10 @@ void ResponseText::handleCodeBlocks() || firstWord == "html" || firstWord == "php") { codeLanguage = firstWord; - capturedText.remove(0, match.captured(0).length()); } + lines.removeFirst(); } - const QStringList lines = capturedText.split('\n'); - QTextFrame *mainFrame = cursor.currentFrame(); cursor.setCharFormat(textFormat); @@ -1141,10 +1141,6 @@ void ResponseText::handleCodeBlocks() } else { codeCursor.insertText(lines.join("\n")); } - if (codeCursor.position() > 0) { - codeCursor.setPosition(codeCursor.position() - 1); - codeCursor.deleteChar(); - } cursor = mainFrame->lastCursorPosition(); cursor.setCharFormat(QTextCharFormat());