import { markdownLanguage } from "@codemirror/lang-markdown"; export type DocumentLink = { from: number; to: number; targetFrom: number; targetTo: number; kind: "md" | "wiki"; target: string }; /** Source ranges survive the change from formatted text to editable Markdown. */ export function documentLinks(source: string): DocumentLink[] { const links: DocumentLink[] = []; const literal: { from: number; to: number }[] = []; markdownLanguage.parser.parse(source).iterate({ enter(node) { if (["FencedCode", "CodeBlock", "InlineCode", "Image"].includes(node.name)) { literal.push({ from: node.from, to: node.to }); return false; } if (node.name !== "Link" && node.name !== "Autolink") return; const url = node.node.getChild("URL"); if (!url) return; const target = source.slice(url.from, url.to).replace(/^<|>$/g, "").replace(/\\([\\()])/g, "$1"); const angled = source[url.from] === "<"; links.push({ from: node.from, to: node.to, targetFrom: url.from + Number(angled), targetTo: url.to - Number(angled), kind: "md", target }); return false; } }); const occupied = (from: number, to: number) => [...literal, ...links].some(range => from < range.to && to > range.from); for (const match of source.matchAll(/\[\[([^\]\n]+)\]\]/g)) { if (occupied(match.index, match.index + match[0].length)) continue; if (source[match.index - 1] === "!") continue; const raw = match[1].split(/\\?\|/)[0], target = raw.trim(); const targetFrom = match.index + 2 + raw.length - raw.trimStart().length; links.push({ from: match.index, to: match.index + match[0].length, targetFrom, targetTo: targetFrom + target.length, kind: "wiki", target }); } links.push(...plainUrls(source, occupied)); return links.sort((a, b) => a.from - b.from); } function plainUrls(source: string, occupied: (from: number, to: number) => boolean = () => false) { const links: DocumentLink[] = []; for (const match of source.matchAll(/(?:https?:\/\/|mailto:)[^\s<>]+/g)) { if (occupied(match.index, match.index + match[0].length)) continue; const target = match[0].replace(/[.,;:!?]+$/, "").replace(/\)+$/, suffix => { const open = (match[0].match(/\(/g) || []).length, close = (match[0].match(/\)/g) || []).length; return suffix.slice(0, Math.max(0, suffix.length - Math.max(0, close - open))); }); links.push({ from: match.index, to: match.index + target.length, targetFrom: match.index, targetTo: match.index + target.length, kind: "md" as const, target }); } return links; } export function documentLinkAt(source: string, position: number) { return documentLinks(source).find(link => position >= link.from && position < link.to); } /** The plain URL at a position, for files that are not Markdown. */ export function urlAt(source: string, position: number) { return plainUrls(source).find(link => position >= link.from && position < link.to); }