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