Update editor, workspace, Git services, appearance, and project guides
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
import { markdownLanguage } from "@codemirror/lang-markdown";
|
||||
|
||||
export type DocumentLink = { from: number; to: 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");
|
||||
links.push({ from: node.from, to: node.to, 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;
|
||||
links.push({ from: match.index, to: match.index + match[0].length, kind: "wiki", target: match[1].split("|")[0].trim() });
|
||||
}
|
||||
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, kind: "md", target });
|
||||
}
|
||||
return links.sort((a, b) => a.from - b.from);
|
||||
}
|
||||
|
||||
export function documentLinkAt(source: string, position: number) {
|
||||
return documentLinks(source).find(link => position >= link.from && position < link.to);
|
||||
}
|
||||
Reference in New Issue
Block a user