Markdown: Follow local anchor links in text editor

Github and others turn `[^footnote]` into anchor links to the next
occurrence of `[^footnote]: Description`.

Task-number: QTCREATORBUG-30119
Change-Id: Ieebcad8ef58ccd8c7faa6aa83a165ce3f7ea1a01
Reviewed-by: David Schulz <david.schulz@qt.io>
This commit is contained in:
Mathias Hasselmann
2024-01-05 00:06:28 +01:00
parent 444da70fcf
commit 8dde6b0a67

View File

@@ -569,7 +569,12 @@ void MarkdownEditorWidget::findLinkAt(const QTextCursor &cursor,
bool /*inNextSplit*/) bool /*inNextSplit*/)
{ {
static const QStringView CAPTURE_GROUP_LINK = u"link"; static const QStringView CAPTURE_GROUP_LINK = u"link";
static const QRegularExpression markdownLink{R"(\[[^[\]]*\]\((?<link>.+?)\))"}; static const QStringView CAPTURE_GROUP_ANCHOR = u"anchor";
static const QRegularExpression markdownLink{
R"(\[[^[\]]*\]\((?<link>.+?)\))"
R"(|(?<anchor>\[\^[^\]]+\])(?:[^:]|$))"
};
QTC_ASSERT(markdownLink.isValid(), return); QTC_ASSERT(markdownLink.isValid(), return);
@@ -604,6 +609,25 @@ void MarkdownEditorWidget::findLinkAt(const QTextCursor &cursor,
result.linkTextEnd = match.capturedEnd() + blockOffset; result.linkTextEnd = match.capturedEnd() + blockOffset;
processLinkCallback(result); processLinkCallback(result);
break; break;
} else if (const QStringView anchor = match.capturedView(CAPTURE_GROUP_ANCHOR);
!anchor.isEmpty()) {
// Process local anchor links of the form `[^footnote]` that point
// to anchors in the current document: `[^footnote]: Description`.
const QTextCursor target = cursor.document()->find(anchor + u':');
if (target.isNull())
continue;
int line = 0;
int column = 0;
convertPosition(target.position(), &line, &column);
Link result{textDocument()->filePath(), line, column};
result.linkTextStart = match.capturedStart(CAPTURE_GROUP_ANCHOR) + blockOffset;
result.linkTextEnd = match.capturedEnd(CAPTURE_GROUP_ANCHOR) + blockOffset;
processLinkCallback(result);
break;
} else { } else {
QTC_ASSERT_STRING("This line should not be reached unless 'markdownLink' is wrong"); QTC_ASSERT_STRING("This line should not be reached unless 'markdownLink' is wrong");
return; return;