Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(markdown): complete note links after [[
Elian Doran74f29d100d5d
diff --git a/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts b/apps/client/src/widgets/type_widgets/markdown/completions.spec.tsindex e2477fdb7d..2c12e67484 100644--- a/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts+++ b/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts@@ -189,6 +189,18 @@ describe("markdownCompletionAt", () => {expect(at("@a and @b c")).toEqual({ kind: "note", from: 7, query: "b c" });// An address is no mention.expect(at("mail [email protected]")).toBeNull();+ });++ it("finds a note after [[, as a Wikilink is typed, until its brackets close", () => {+ expect(at("see [[")).toEqual({ kind: "note", from: 4, query: "" });+ expect(at("see [[My meeting no")).toEqual({ kind: "note", from: 4, query: "My meeting no" });+ expect(at("word[[Al")).toEqual({ kind: "note", from: 4, query: "Al" });+ expect(at("see [[Al]] then")).toBeNull();+ expect(at("see [Al")).toBeNull();+ // The marker nearest the caret wins.+ expect(at("[[My @Al")).toEqual({ kind: "note", from: 5, query: "Al" });+ expect(at("@My [[Al")).toEqual({ kind: "note", from: 4, query: "Al" });+ expect(at("`[[Al` b", 5)).toBeNull();expect(at("text `a @` b", 9)).toBeNull();});@@ -329,7 +341,7 @@ describe("useMarkdownCompletions", () => {editor.destroy();});- it("lists the notes for what follows an @, as the text editor does, and links the one picked or created", async () => {+ it("lists the notes for what follows an @ or a [[, as the text editor does, and links the one picked or created", async () => {getNoteSuggestions.mockResolvedValue([{ notePath: "root/projects/abc123", noteTitle: "Alpha", notePathTitle: "Projects / Alpha", highlightedNotePathTitle: "<b>Al</b>pha" },{ action: "create-child-note", noteTitle: "Al", parentNoteId: "parent", highlightedNotePathTitle: "Create child note" }@@ -364,6 +376,18 @@ describe("useMarkdownCompletions", () => {created("root/parent/new1");await vi.waitFor(() => expect(editor.state.doc.toString()).toBe("see [[abc123]] [[new1]]"));+ // After [[ the same list opens, and a pick inside a link already closed takes its brackets too.+ editor.focus();+ editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: "see [[Al" }, selection: { anchor: 8 } });+ await vi.waitFor(() => expect(rows()).toHaveLength(2));+ press("Enter");+ await vi.waitFor(() => expect(editor.state.doc.toString()).toBe("see [[abc123]]"));+ editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: "see [[Al]] x" }, selection: { anchor: 8 } });+ await vi.waitFor(() => expect(rows()).toHaveLength(2));+ press("Enter");+ await vi.waitFor(() => expect(editor.state.doc.toString()).toBe("see [[abc123]] x"));+ expect(editor.state.selection.main.head).toBe(14);+act(() => render(null, container));editor.destroy();});diff --git a/apps/client/src/widgets/type_widgets/markdown/completions.tsx b/apps/client/src/widgets/type_widgets/markdown/completions.tsxindex f6107130e6..607fb265a4 100644--- a/apps/client/src/widgets/type_widgets/markdown/completions.tsx+++ b/apps/client/src/widgets/type_widgets/markdown/completions.tsx@@ -36,11 +36,11 @@ export interface SlashCommand extends CommandEntry {apply: HostedCompletionApply;}-/** A `/command` or an `@` note typed before the caret, from its `/` or its `@`. */+/** A `/command` or a note typed before the caret, from its `/`, its `@` or its `[[`. */export interface MarkdownCompletionMatch {kind: "command" | "note";from: number;- /** What follows the `/` or the `@`, which the list filters by, as the text editor's do. */+ /** What follows the `/`, the `@` or the `[[`, which the list filters by, as the text editor's do. */query: string;}@@ -55,8 +55,9 @@ export interface SlashCommandContext {}/**- * Lists the `/` commands and the `@` notes typed at the start of a line or after whitespace in- * the text editor's lists, through `hostedCompletion()`. A note picked is linked as `[[noteId]]`,+ * Lists the `/` commands and the `@` notes typed at the start of a line or after whitespace, and+ * the notes typed after a Wikilink's `[[`, in the text editor's lists, through+ * `hostedCompletion()`. A note picked is linked as `[[noteId]]`,* and one created goes under the note at `getNotePath()`. The code-fence languages stay with* CodeMirror's own completion.*/@@ -115,23 +116,32 @@ export function useMarkdownCompletions(/*** The `/command` or the `@` note typed before the caret, at the start of a line or after whitespace,- * or `null` in a code block or a code span, where either is part of the code.+ * or the note typed after a `[[`, the marker nearest the caret where both stand; or `null` in a code+ * block or a code span, where any of them is part of the code.*/export function markdownCompletionAt(before: string, _explicit: boolean, state: EditorState): MarkdownCompletionMatch | null {const command = COMMAND_TYPED.exec(before);- const typed = command ?? NOTE_TYPED.exec(before);+ const mention = NOTE_TYPED.exec(before);+ const wikilink = WIKILINK_TYPED.exec(before);+ const note = mention && wikilink+ ? (mention.index > wikilink.index ? mention : wikilink)+ : mention ?? wikilink;+ const typed = command ?? note;if (!typed) return null;for (let node: SyntaxNode | null = syntaxTree(state).resolveInner(state.selection.main.head, -1); node; node = node.parent) {if (node.name.includes("Code")) return null;}- return { kind: command ? "command" : "note", from: typed.index, query: typed[0].slice(1) };+ const markerLength = typed === wikilink ? 2 : 1;+ return { kind: command ? "command" : "note", from: typed.index, query: typed[0].slice(markerLength) };}const COMMAND_TYPED = new RegExp(`${SLASH_COMMAND_REGEX.source}$`);/** An `@`, and the note title typed after it, spaces included, as the text editor's `@` allows. */const NOTE_TYPED = /(?:^|(?<=\s))@[^@]*$/;+/** A Wikilink's `[[`, anywhere, and the note title typed after it, until a bracket ends it. */+const WIKILINK_TYPED = /\[\[[^[\]]*$/;/*** The commands the `/` list offers, titled, described, found by the same words and drawn with the same@@ -376,7 +386,7 @@ function createMarkdownCompletionList(commands: () => SlashCommand[], getParentNallowCreatingNotesparentNotePath={getParentNotePath()}onPick={(notePath) => state.commit(typeof notePath === "string"- ? noteLink(notePath)+ ? linkTo(notePath): notePath.then((path) => path ? noteLink(path) : undefined))}/>);@@ -395,6 +405,23 @@ function createMarkdownCompletionList(commands: () => SlashCommand[], getParentN});}+/**+ * Puts the link to the note at `notePath` in place of the typed note. Where the caret is inside a+ * Wikilink already closed, the rest of the link up to its `]]` goes too.+ */+function linkTo(notePath: string): HostedCompletionApply {+ return (view, from, to) => {+ const isWikilink = view.state.sliceDoc(from, from + 2) === "[[";+ const rest = isWikilink ? /^[^[\]\n]*\]\]/.exec(view.state.sliceDoc(to, view.state.doc.lineAt(to).to)) : null;+ const link = noteLink(notePath);+ view.dispatch({+ changes: { from, to: to + (rest?.[0].length ?? 0), insert: link },+ selection: { anchor: from + link.length },+ userEvent: "input.complete"+ });+ };+}+/** The reference link to the note at `notePath`, which the preview renders with the note's title. */function noteLink(notePath: string) {return `[[${notePath.split("/").pop()}]]`;diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.htmlindex d2203deb47..42167e23a9 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html@@ -211,7 +211,7 @@title, its keyword (as listed above) or a related word such as <code>latex</code> or <code>grid</code> findsit.</p><p>Note that slash commands only work outside of code blocks and inline code.</p>-<h4>Linking notes with <code>@</code></h4>+<h4>Linking notes with <code>@</code> or <code>[[</code></h4><p>As in <a class="reference-link" href="#root/_help_iPIMuisry3hd">Text</a> notes,typing <code>@</code> at the start of a line or after a space opens the notesearch. Picking a note replaces what was typed with a link to it in the@@ -223,8 +223,11 @@close the list and go on writing. If no note fits, the list offers to createone, as a child of the Markdown note or in the inbox; the link is insertedonce the note is created.</p>-<p>Like slash commands, <code>@</code> does nothing inside code blocks and- inline code.</p>+<p>You can also start typing the link directly: <code>[[</code> opens the same+ list, and closing the brackets yourself dismisses it. To change where an+ existing link points, place the cursor inside it and pick another note.</p>+<p>Like slash commands, <code>@</code> and <code>[[</code> do nothing inside+ code blocks and inline code.</p><h4>Code block language auto-completion</h4><p>Starting with v0.104.0, typing ``` to insert a code block will automaticallyopen a list of suggested language types which have syntax highlighting.</p>diff --git a/docs/User Guide/User Guide/Note Types/Markdown.md b/docs/User Guide/User Guide/Note Types/Markdown.mdindex a51c606760..fc54d8066d 100644--- a/docs/User Guide/User Guide/Note Types/Markdown.md+++ b/docs/User Guide/User Guide/Note Types/Markdown.md@@ -175,13 +175,15 @@ The list shows each command by its title, as in Text notes. Typing a command's tNote that slash commands only work outside of code blocks and inline code.-#### Linking notes with `@`+#### Linking notes with `@` or `[[`As in <a class="reference-link" href="Text.md">Text</a> notes, typing `@` at the start of a line or after a space opens the note search. Picking a note replaces what was typed with a link to it in the Wikilinks-like format (`[[noteId]]`), which the preview shows as an <a class="reference-link" href="Text/Links/Internal%20(reference)%20links.md">internal link</a> with the note's title.The search runs on everything typed after the `@`, spaces included, so a title such as `@My meeting notes` can be typed out; press <kbd>Esc</kbd> to close the list and go on writing. If no note fits, the list offers to create one, as a child of the Markdown note or in the inbox; the link is inserted once the note is created.-Like slash commands, `@` does nothing inside code blocks and inline code.+You can also start typing the link directly: `[[` opens the same list, and closing the brackets yourself dismisses it. To change where an existing link points, place the cursor inside it and pick another note.++Like slash commands, `@` and `[[` do nothing inside code blocks and inline code.#### Code block language auto-completion