Utils: Fix markdown code highlighting at end of document

When a code block happend to be at the end of the document
the while loop over "curBlock" would end with an invalid block.

The code assumed that there always is a valid block after the
code block and therefor broke.

Change-Id: I22ea57834a721ff6bd99579cfa04c36c68743fa8
Reviewed-by: David Schulz <david.schulz@qt.io>
This commit is contained in:
Marcus Tillmanns
2024-10-24 10:34:29 +02:00
parent 08a7cc1a3d
commit a7f4944ea9

View File

@@ -80,32 +80,25 @@ static QStringList defaultCodeFontFamilies()
static void highlightCodeBlock(QTextDocument *document, QTextBlock &block, const QString &language) static void highlightCodeBlock(QTextDocument *document, QTextBlock &block, const QString &language)
{ {
int startBlockNumner = block.blockNumber(); const int position = block.position();
// Find the end of the code block ... // Find the end of the code block ...
QTextBlock curBlock = block; for (block = block.next(); block.isValid(); block = block.next()) {
while (curBlock.isValid()) { if (!block.blockFormat().hasProperty(QTextFormat::BlockCodeLanguage))
curBlock = curBlock.next(); break;
const auto valid = curBlock.isValid(); if (language != block.blockFormat().stringProperty(QTextFormat::BlockCodeLanguage))
const auto hasProp = curBlock.blockFormat().hasProperty(QTextFormat::BlockCodeLanguage);
const auto prop = curBlock.blockFormat().stringProperty(QTextFormat::BlockCodeLanguage);
if (!valid || !hasProp || prop != language)
break; break;
} }
const int end = (block.isValid() ? block.position() : document->characterCount()) - 1;
// Get the text of the code block and erase it // Get the text of the code block and erase it
QTextCursor eraseCursor(document); QTextCursor eraseCursor(document);
eraseCursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor, startBlockNumner); eraseCursor.setPosition(position);
eraseCursor.movePosition( eraseCursor.setPosition(end, QTextCursor::KeepAnchor);
QTextCursor::NextBlock,
QTextCursor::KeepAnchor,
curBlock.blockNumber() - startBlockNumner - 1);
eraseCursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
QString code = eraseCursor.selectedText(); const QString code = eraseCursor.selectedText();
eraseCursor.deleteChar(); eraseCursor.removeSelectedText();
// Create a new Frame and insert the highlighted code ... // Create a new Frame and insert the highlighted code ...
block = document->findBlockByNumber(startBlockNumner); block = document->findBlock(position);
QTextCursor cursor(block); QTextCursor cursor(block);
QTextFrameFormat format; QTextFrameFormat format;