From 6831e11c3e8b58fe0daf9ebc11ad0c491f076b7d Mon Sep 17 00:00:00 2001 From: Eike Ziller Date: Thu, 4 Jan 2024 10:47:58 +0100 Subject: [PATCH] Markdown: Add anchors for headings It looks like GitHub creates heading IDs by - converting spaces to '-' - removing anything that is not '-', '_', a number, or a letter - converting to lower case Task-number: QTBUG-120518 Change-Id: If09a8e2e0d964e751869eaebd3326a6f983ac495 Reviewed-by: David Schulz --- src/plugins/texteditor/markdowneditor.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/plugins/texteditor/markdowneditor.cpp b/src/plugins/texteditor/markdowneditor.cpp index c8106692e3a..877b032465a 100644 --- a/src/plugins/texteditor/markdowneditor.cpp +++ b/src/plugins/texteditor/markdowneditor.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include #include @@ -184,6 +185,26 @@ public: m_previewRestoreScrollPosition.reset(); m_previewWidget->setMarkdown(m_document->plainText()); + // Add anchors to headings. This should actually be done by Qt QTBUG-120518 + for (QTextBlock block = m_previewWidget->document()->begin(); block.isValid(); + block = block.next()) { + QTextBlockFormat fmt = block.blockFormat(); + if (fmt.hasProperty(QTextFormat::HeadingLevel)) { + QTextCharFormat cFormat = block.charFormat(); + QString anchor; + const QString text = block.text(); + for (const QChar &c : text) { + if (c == ' ') + anchor.append('-'); + else if (c == '_' || c == '-' || c.isDigit() || c.isLetter()) + anchor.append(c.toLower()); + } + cFormat.setAnchor(true); + cFormat.setAnchorNames({anchor}); + QTextCursor cursor(block); + cursor.setBlockCharFormat(cFormat); + } + } m_previewWidget->horizontalScrollBar()->setValue(positions.x()); m_previewWidget->verticalScrollBar()->setValue(positions.y());