responsetext : fix markdown code block trimming (#2232)

Signed-off-by: Jared Van Bortel <jared@nomic.ai>
This commit is contained in:
Jared Van Bortel 2024-04-18 14:50:32 -04:00 committed by GitHub
parent 4ebb0c6ac0
commit be93ee75de
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1045,8 +1045,6 @@ void ResponseText::handleCodeBlocks()
static const QRegularExpression reCode("```(.*?)(```|$)", QRegularExpression::DotMatchesEverythingOption); static const QRegularExpression reCode("```(.*?)(```|$)", QRegularExpression::DotMatchesEverythingOption);
QRegularExpressionMatchIterator iCode = reCode.globalMatch(doc->toPlainText()); QRegularExpressionMatchIterator iCode = reCode.globalMatch(doc->toPlainText());
static const QRegularExpression reWhitespace("^\\s*(\\w+)");
QList<QRegularExpressionMatch> matchesCode; QList<QRegularExpressionMatch> matchesCode;
while (iCode.hasNext()) while (iCode.hasNext())
matchesCode.append(iCode.next()); matchesCode.append(iCode.next());
@ -1062,9 +1060,13 @@ void ResponseText::handleCodeBlocks()
QString capturedText = matchesCode[index].captured(1); QString capturedText = matchesCode[index].captured(1);
QString codeLanguage; QString codeLanguage;
QRegularExpressionMatch match = reWhitespace.match(capturedText); QStringList lines = capturedText.split('\n');
if (match.hasMatch()) { if (lines.last().isEmpty()) {
const QString firstWord = match.captured(1).trimmed(); lines.removeLast();
}
if (lines.count() >= 2) {
const auto &firstWord = lines.first();
if (firstWord == "python" if (firstWord == "python"
|| firstWord == "cpp" || firstWord == "cpp"
|| firstWord == "c++" || firstWord == "c++"
@ -1082,12 +1084,10 @@ void ResponseText::handleCodeBlocks()
|| firstWord == "html" || firstWord == "html"
|| firstWord == "php") { || firstWord == "php") {
codeLanguage = firstWord; codeLanguage = firstWord;
capturedText.remove(0, match.captured(0).length());
} }
lines.removeFirst();
} }
const QStringList lines = capturedText.split('\n');
QTextFrame *mainFrame = cursor.currentFrame(); QTextFrame *mainFrame = cursor.currentFrame();
cursor.setCharFormat(textFormat); cursor.setCharFormat(textFormat);
@ -1141,10 +1141,6 @@ void ResponseText::handleCodeBlocks()
} else { } else {
codeCursor.insertText(lines.join("\n")); codeCursor.insertText(lines.join("\n"));
} }
if (codeCursor.position() > 0) {
codeCursor.setPosition(codeCursor.position() - 1);
codeCursor.deleteChar();
}
cursor = mainFrame->lastCursorPosition(); cursor = mainFrame->lastCursorPosition();
cursor.setCharFormat(QTextCharFormat()); cursor.setCharFormat(QTextCharFormat());