From 914907a6e41c01c61ed78d1ca20242bf08b5695b Mon Sep 17 00:00:00 2001
From: Reda Hilal <reda0x04@gmail.com>
Date: Thu, 12 Nov 2026 18:08:38 +0400
Subject: [PATCH] SyntaxHighlighter: don't queue a QTextBlock for
 re-highlighting

When the end state or folding regions of a block change, highlightBlock()
queues a re-highlight of the next block. It passed that block to the queued
call as a QTextBlock, which is only an index into the document's block map.
If the text is replaced before the call is delivered, for example with
setPlainText() right after a definition change, the block is stale:
QSyntaxHighlighter::rehighlightBlock() still accepts it, and
QTextBlock::position() reads past the new block map and crashes.

Queue the block number instead and look the block up when the call runs.
If the document changed in between, the worst case is re-highlighting a
block that did not need it.

BUG: 528753
---
 autotests/CMakeLists.txt             |   5 ++
 autotests/syntaxhighlighter_test.cpp | 121 +++++++++++++++++++++++++++
 src/lib/syntaxhighlighter.cpp        |  14 +++-
 3 files changed, 139 insertions(+), 1 deletion(-)
 create mode 100644 autotests/syntaxhighlighter_test.cpp

diff --git a/autotests/CMakeLists.txt b/autotests/CMakeLists.txt
index 33485b700..a740cf3bd 100644
--- a/autotests/CMakeLists.txt
+++ b/autotests/CMakeLists.txt
@@ -47,6 +47,11 @@ ecm_mark_nongui_executable(folding_test)
 add_test(NAME folding_test COMMAND folding_test)
 target_link_libraries(folding_test KF6SyntaxHighlighting Qt6::Test)
 
+add_executable(syntaxhighlighter_test syntaxhighlighter_test.cpp)
+ecm_mark_nongui_executable(syntaxhighlighter_test)
+add_test(NAME syntaxhighlighter_test COMMAND syntaxhighlighter_test ${OFFSCREEN_QPA})
+target_link_libraries(syntaxhighlighter_test KF6SyntaxHighlighting Qt6::Test)
+
 #
 # benchmarks, don't execute during normal testing
 # they don't test additional stuff but only hang the CI
diff --git a/autotests/syntaxhighlighter_test.cpp b/autotests/syntaxhighlighter_test.cpp
new file mode 100644
index 000000000..1a896523a
--- /dev/null
+++ b/autotests/syntaxhighlighter_test.cpp
@@ -0,0 +1,121 @@
+/*
+    SPDX-FileCopyrightText: 2026 Reda Hilal <reda0x04@gmail.com>
+
+    SPDX-License-Identifier: MIT
+*/
+
+#include "test-config.h"
+
+#include <KSyntaxHighlighting/Definition>
+#include <KSyntaxHighlighting/Repository>
+#include <KSyntaxHighlighting/SyntaxHighlighter>
+#include <KSyntaxHighlighting/Theme>
+
+#include <QAbstractTextDocumentLayout>
+#include <QCoreApplication>
+#include <QObject>
+#include <QStandardPaths>
+#include <QTest>
+#include <QTextBlock>
+#include <QTextCursor>
+#include <QTextDocument>
+#include <QTextLayout>
+
+using namespace KSyntaxHighlighting;
+
+class SyntaxHighlighterTest : public QObject
+{
+    Q_OBJECT
+private:
+    Repository m_repo;
+    Definition m_cpp;
+    Theme m_theme;
+
+    // without a layout, QTextDocument doesn't emit contentsChange() and nothing gets highlighted
+    static void createLayout(QTextDocument &doc)
+    {
+        QVERIFY(doc.documentLayout());
+    }
+
+    static void runQueuedRehighlights(const QTextDocument &doc)
+    {
+        for (int i = 0; i <= doc.blockCount(); ++i) {
+            QCoreApplication::sendPostedEvents();
+        }
+    }
+
+    static QList<QList<QTextLayout::FormatRange>> blockFormats(const QTextDocument &doc)
+    {
+        QList<QList<QTextLayout::FormatRange>> formats;
+        for (auto block = doc.begin(); block.isValid(); block = block.next()) {
+            formats.push_back(block.layout()->formats());
+        }
+        return formats;
+    }
+
+    QList<QList<QTextLayout::FormatRange>> freshlyHighlightedFormats(const QString &text) const
+    {
+        QTextDocument doc;
+        createLayout(doc);
+        SyntaxHighlighter highlighter(&doc);
+        highlighter.setTheme(m_theme);
+        highlighter.setDefinition(m_cpp);
+        doc.setPlainText(text);
+        return blockFormats(doc);
+    }
+
+private Q_SLOTS:
+    void initTestCase()
+    {
+        QStandardPaths::setTestModeEnabled(true);
+        initRepositorySearchPaths(m_repo);
+        m_cpp = m_repo.definitionForName(QStringLiteral("C++"));
+        QVERIFY(m_cpp.isValid());
+        m_theme = m_repo.defaultTheme(Repository::LightTheme);
+        QVERIFY(m_theme.isValid());
+    }
+
+    void testEditRehighlightsFollowingBlocks()
+    {
+        QTextDocument doc;
+        createLayout(doc);
+        SyntaxHighlighter highlighter(&doc);
+        highlighter.setTheme(m_theme);
+        highlighter.setDefinition(m_cpp);
+        doc.setPlainText(QStringLiteral("int a;\nint b;\nint c;\n"));
+
+        QTextCursor cursor(doc.firstBlock());
+        cursor.insertText(QStringLiteral("/*"));
+        runQueuedRehighlights(doc);
+
+        QCOMPARE(blockFormats(doc), freshlyHighlightedFormats(doc.toPlainText()));
+    }
+
+    void testReplaceTextWhileRehighlightIsQueued()
+    {
+        // every line is in a comment, so switching to C++ queues a re-highlight for each one
+        QString longText = QStringLiteral("/*\n");
+        for (int i = 0; i < 20000; ++i) {
+            longText += QStringLiteral("line %1\n").arg(i);
+        }
+        const QString shortText = QStringLiteral("int a;\nint b;\n");
+
+        // no layout, it would make the test slow
+        QTextDocument doc;
+        SyntaxHighlighter highlighter(&doc);
+        highlighter.setTheme(m_theme);
+        doc.setPlainText(longText);
+        highlighter.rehighlight();
+        highlighter.setDefinition(m_cpp);
+
+        doc.setPlainText(shortText);
+        highlighter.rehighlight();
+        runQueuedRehighlights(doc);
+
+        QCOMPARE(blockFormats(doc), freshlyHighlightedFormats(shortText));
+    }
+};
+
+QTEST_MAIN(SyntaxHighlighterTest)
+
+#include "syntaxhighlighter_test.moc"
diff --git a/src/lib/syntaxhighlighter.cpp b/src/lib/syntaxhighlighter.cpp
index 70b26a79b..056015f0d 100644
--- a/src/lib/syntaxhighlighter.cpp
+++ b/src/lib/syntaxhighlighter.cpp
@@ -218,7 +218,19 @@ void SyntaxHighlighter::highlightBlock(const QString &text)
 
     const auto nextBlock = currentBlock().next();
     if (nextBlock.isValid()) {
-        QMetaObject::invokeMethod(this, "rehighlightBlock", Qt::QueuedConnection, Q_ARG(QTextBlock, nextBlock));
+        // a QTextBlock doesn't survive the document text being replaced, queue the block number
+        const int nextBlockNumber = nextBlock.blockNumber();
+        QMetaObject::invokeMethod(
+            this,
+            [this, nextBlockNumber]() {
+                if (const auto doc = document()) {
+                    const auto block = doc->findBlockByNumber(nextBlockNumber);
+                    if (block.isValid()) {
+                        rehighlightBlock(block);
+                    }
+                }
+            },
+            Qt::QueuedConnection);
     }
 }
 
-- 
GitLab

