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): list the slash commands in the shared command list
Elian Doranc17e0b966702
diff --git a/apps/client/src/widgets/quick_search.spec.tsx b/apps/client/src/widgets/quick_search.spec.tsxindex 4ff011dfad..d876706ade 100644--- a/apps/client/src/widgets/quick_search.spec.tsx+++ b/apps/client/src/widgets/quick_search.spec.tsx@@ -11,7 +11,7 @@ import server from "../services/server";import { renderInto } from "../test/render";import QuickSearch from "./quick_search";import { ParentComponent } from "./react/react_utils";-import type { SearchCompletion, SearchEntry } from "./ribbon/search_completions";+import type { SearchCompletion } from "./ribbon/search_completions";// The completions fetch attribute names and values through the server, so a spec that opens them// supplies its own.@@ -25,8 +25,7 @@ vi.mock("../services/i18n", async (importOriginal) => ({}));vi.mock("./ribbon/search_completions", () => ({- searchCompletionAt: (before: string, explicit: boolean) => completions.at?.(before, explicit) ?? null,- filterSearchEntries: (entries: SearchEntry[]) => entries+ searchCompletionAt: (before: string, explicit: boolean) => completions.at?.(before, explicit) ?? null}));describe("QuickSearch", () => {diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsxindex 2b79ad4511..721048150b 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx@@ -22,7 +22,7 @@ import { collectShortcutHints } from "../../services/shortcut_hints";import { buildNote } from "../../test/easy-froca";import { renderInto } from "../../test/render";import type { AutocompleteListHandle } from "./FormAutocomplete";-import NoteAutocomplete, { HighlightedText, type NoteAutocompleteHandle, type NoteAutocompleteProps, NoteMentionList } from "./NoteAutocomplete";+import NoteAutocomplete, { filterCommandEntries, HighlightedText, type NoteAutocompleteHandle, type NoteAutocompleteProps, NoteMentionList } from "./NoteAutocomplete";import { ParentComponent } from "./react_utils";async function render(props: NoteAutocompleteProps = {}) {@@ -1296,3 +1296,15 @@ describe("HighlightedText", () => {expect(html("title", "")).toBe("title");});});++describe("filterCommandEntries", () => {+ it("keeps the entries holding the query, ignoring case, those starting with it first", () => {+ const entries = [ "contentSize", "dateCreated", "content", "childrenCount", "title" ]+ .map((title) => ({ id: title, title }));++ expect(filterCommandEntries(entries, "CONT").map((entry) => entry.title)).toEqual([ "contentSize", "content" ]);+ expect(filterCommandEntries(entries, "c").map((entry) => entry.title))+ .toEqual([ "contentSize", "content", "childrenCount", "dateCreated" ]);+ expect(filterCommandEntries(entries, "")).toEqual(entries);+ });+});diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsxindex 25b456c4d7..77670e32f2 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx@@ -555,6 +555,18 @@ export function CommandMentionList<T extends CommandEntry>({ query, source, anch);}+/**+ * The entries of a {@link CommandMentionList} whose title holds `query`, ignoring case: those it+ * starts first, then the rest, each in the order they are offered in.+ */+export function filterCommandEntries<T extends CommandEntry>(entries: T[], query: string) {+ const typed = query.toLowerCase();+ const starting = entries.filter(({ title }) => title.toLowerCase().startsWith(typed));+ const containing = entries.filter(({ title }) => !title.toLowerCase().startsWith(typed) && title.toLowerCase().includes(typed));++ return [ ...starting, ...containing ];+}+/** What a list drawn by {@link createHostedList} is given to draw itself with. */export interface HostedListProps {/** At the caret, placed again each time the query changes. */diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.spec.tsx b/apps/client/src/widgets/ribbon/SearchStringEditor.spec.tsxindex d031459b23..0d2dab620c 100644--- a/apps/client/src/widgets/ribbon/SearchStringEditor.spec.tsx+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.spec.tsx@@ -10,8 +10,7 @@ import SearchStringEditor from "./SearchStringEditor";// The completions fetch attribute names and values through the server; nothing here opens their list.vi.mock("./search_completions", () => ({- searchCompletionAt: () => null,- filterSearchEntries: () => []+ searchCompletionAt: () => null}));describe("SearchStringEditor", () => {diff --git a/apps/client/src/widgets/ribbon/search_completions.spec.ts b/apps/client/src/widgets/ribbon/search_completions.spec.tsindex 331c5db68f..2139fb5843 100644--- a/apps/client/src/widgets/ribbon/search_completions.spec.ts+++ b/apps/client/src/widgets/ribbon/search_completions.spec.ts@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from "vitest";import server from "../../services/server";-import { filterSearchEntries, type SearchCompletion, searchCompletionAt, type SearchEntry } from "./search_completions";+import { type SearchCompletion, searchCompletionAt, type SearchEntry } from "./search_completions";// The descriptions are catalogue lookups, which specs don't initialize; the keys identify them.vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));@@ -272,18 +272,6 @@ describe("searchCompletionAt", () => {});});-describe("filterSearchEntries", () => {- it("keeps the entries holding the query, ignoring case, those starting with it first", () => {- const entries = [ "contentSize", "dateCreated", "content", "childrenCount", "title" ]- .map((title) => ({ id: title, title, insert: title }));-- expect(filterSearchEntries(entries, "CONT").map((entry) => entry.title)).toEqual([ "contentSize", "content" ]);- expect(filterSearchEntries(entries, "c").map((entry) => entry.title))- .toEqual([ "contentSize", "content", "childrenCount", "dateCreated" ]);- expect(filterSearchEntries(entries, "")).toEqual(entries);- });-});-function complete(text: string, { explicit = false } = {}) {return searchCompletionAt(text, explicit);}diff --git a/apps/client/src/widgets/ribbon/search_completions.ts b/apps/client/src/widgets/ribbon/search_completions.tsindex dd87b0f764..c3d75c3baa 100644--- a/apps/client/src/widgets/ribbon/search_completions.ts+++ b/apps/client/src/widgets/ribbon/search_completions.ts@@ -98,18 +98,6 @@ export function searchCompletionAt(before: string, explicit: boolean): SearchComreturn null;}-/**- * The entries whose title holds `query`, ignoring case: those it starts first, then the rest, each- * in the order they are offered in.- */-export function filterSearchEntries(entries: SearchEntry[], query: string) {- const typed = query.toLowerCase();- const starting = entries.filter(({ title }) => title.toLowerCase().startsWith(typed));- const containing = entries.filter(({ title }) => !title.toLowerCase().startsWith(typed) && title.toLowerCase().includes(typed));-- return [ ...starting, ...containing ];-}-/*** A note picked with `@`, which opens only where a value can stand — at the start, or after* whitespace, an opening bracket or an operator. `@` is a name character to the lexer, so onediff --git a/apps/client/src/widgets/search_field_editor.tsx b/apps/client/src/widgets/search_field_editor.tsxindex d30416db47..8a69e640f0 100644--- a/apps/client/src/widgets/search_field_editor.tsx+++ b/apps/client/src/widgets/search_field_editor.tsx@@ -12,8 +12,8 @@ import { t } from "../services/i18n";import server from "../services/server";import { AttributeNameSuggestion, fetchAttributeNames } from "./attribute_widgets/attribute_detail";import { AutocompleteList } from "./react/FormAutocomplete";-import { CommandMentionList, createHostedList, NoteMentionList } from "./react/NoteAutocomplete";-import { filterSearchEntries, type SearchCompletion, searchCompletionAt, type SearchEntry } from "./ribbon/search_completions";+import { CommandMentionList, createHostedList, filterCommandEntries, NoteMentionList } from "./react/NoteAutocomplete";+import { type SearchCompletion, searchCompletionAt, type SearchEntry } from "./ribbon/search_completions";/** The class the styles in `search_field_editor.css` are scoped under. */export const SEARCH_FIELD_EDITOR_CLASS = "search-string-editor";@@ -97,7 +97,7 @@ function createSearchCompletionList() {{...props}query={match.query}preselect={match.preselect}- source={async (query) => filterSearchEntries(await entries, query)}+ source={async (query) => filterCommandEntries(await entries, query)}onPick={(entry) => state.commit(entry.insert)}/>);diff --git a/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts b/apps/client/src/widgets/type_widgets/markdown/completions.spec.tsindex 817cfd7ef1..ad1d618a4e 100644--- a/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts+++ b/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts@@ -2,8 +2,8 @@ import type { CompletionContext } from "@codemirror/autocomplete";import { markdown } from "@codemirror/lang-markdown";import { ensureSyntaxTree } from "@codemirror/language";import { EditorState } from "@codemirror/state";-import type VanillaCodeMirror from "@triliumnext/codemirror";-import type { MimeType } from "@triliumnext/commons";+import VanillaCodeMirror from "@triliumnext/codemirror";+import type { MimeType, TaskStateDef } from "@triliumnext/commons";import { h, render } from "preact";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -11,7 +11,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type FNote from "../../../entities/fnote";import mime_types from "../../../services/mime_types.js";import type { TypeWidgetProps } from "../type_widget";-import { buildCodeFenceOptions, buildTaskItemInsert, codeFenceCompletionSource, isClosingFence, parseCodeFencePrefix, useSlashCommands } from "./completions.js";+import { buildCodeFenceOptions, buildSlashCommands, buildTaskItemInsert, codeFenceCompletionSource, isClosingFence, parseCodeFencePrefix, slashCommandAt, useSlashCommands } from "./completions";// The hook's two asynchronous sources of menu entries, stubbed so mounting it needs no server.vi.mock("../code/snippets", async (importOriginal) => ({@@ -19,6 +19,8 @@ vi.mock("../code/snippets", async (importOriginal) => ({useCodeSnippets: () => ({ current: [] })}));vi.mock("../../../services/task_states", () => ({ getTaskStateDefinitions: () => Promise.resolve([]) }));+// The catalogue is not loaded in specs, and the sample diagrams translate their names as they load.+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));describe("buildTaskItemInsert", () => {it("prepends a bullet when not already in a list item", () => {@@ -150,6 +152,97 @@ describe("codeFenceCompletionSource", () => {});});+describe("slashCommandAt", () => {+ /** What is found with the caret at `pos`, or at the end. */+ function at(doc: string, pos = doc.length) {+ const state = EditorState.create({ doc, extensions: [ markdown() ], selection: { anchor: pos } });+ ensureSyntaxTree(state, doc.length);+ const line = state.doc.lineAt(pos);+ return slashCommandAt(line.text.slice(0, pos - line.from), false, state);+ }++ it("finds a command at the start of a line or after whitespace, from its slash", () => {+ expect(at("/")).toEqual({ from: 0, query: "/" });+ expect(at("some text /todo:in-progress")).toEqual({ from: 10, query: "/todo:in-progress" });+ expect(at("first\n /ta")).toEqual({ from: 2, query: "/ta" });+ });++ it("finds none inside a word, past a space, or in code", () => {+ expect(at("and/or")).toBeNull();+ expect(at("/table ")).toBeNull();+ expect(at("```js\nconst a = 1 /")).toBeNull();+ expect(at("text `a /` b", 9)).toBeNull();+ });+});++describe("buildSlashCommands", () => {+ let editor: VanillaCodeMirror;+ const triggerCommand = vi.fn();++ beforeEach(() => {+ triggerCommand.mockReset();+ const parent = document.createElement("div");+ document.body.append(parent);+ editor = new VanillaCodeMirror({ parent });+ });++ afterEach(() => editor.destroy());++ const todo = (name: string, markdownSymbol: string): TaskStateDef => ({ name, title: name, markdownSymbol, isCompleted: false, icon: `bx bx-${name}` });++ function commands(taskStates: TaskStateDef[] = []) {+ return buildSlashCommands({+ parentComponent: { triggerCommand } as unknown as TypeWidgetProps["parentComponent"],+ note: {} as FNote,+ editorView: editor,+ taskStates,+ snippets: [ { noteId: "s1", title: "Greeting", description: "Says hello", content: "Hello!" } ]+ });+ }++ /** Puts `doc` in the editor and runs `title` on the command typed at its end. */+ function run(title: string, doc: string, taskStates: TaskStateDef[] = []) {+ editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: doc }, selection: { anchor: doc.length } });+ const entry = commands(taskStates).find((candidate) => candidate.title === title);+ if (!entry) throw new Error(`no command ${title}`);+ entry.apply(editor, doc.lastIndexOf("/"), doc.length);+ return editor.state.doc.toString();+ }++ it("lists each command with its icon, setting each group apart", () => {+ const entries = commands([ todo("done", "x") ]);+ const byTitle = (title: string) => entries.find((entry) => entry.title === title);++ expect(byTitle("/table")?.icon).toBe("bx bx-table");+ expect(byTitle("/todo:done")).toMatchObject({ icon: "bx bx-done", startsGroup: true });+ expect(byTitle("/snippet:Greeting")).toMatchObject({ description: "Says hello", icon: "bx bx-code-curly", startsGroup: true });+ expect(byTitle("/date")?.startsGroup).toBeUndefined();+ expect(byTitle("/tip")?.startsGroup).toBeUndefined();+ expect(byTitle("/note")?.startsGroup).toBe(true);+ });++ it("replaces the typed command with what it inserts", () => {+ expect(run("/snippet:Greeting", "Hi /snip")).toBe("Hi Hello!");+ expect(run("/todo:done", "- /todo", [ todo("done", "x") ])).toBe("- [x] ");+ expect(run("/todo:done", "/todo", [ todo("done", "x") ])).toBe("- [x] ");+ expect(run("/tip", "/tip")).toBe("> [!TIP]\n> ");+ });++ it("numbers a footnote past the highest one, and selects what to type over", () => {+ expect(run("/footnote", "a[^2] b /foot")).toBe("a[^2] b [^3]\n\n[^3]: ");+ expect(editor.state.selection.main.head).toBe(editor.state.doc.length);++ run("/table", "/table");+ const { from, to } = editor.state.selection.main;+ expect(editor.state.sliceDoc(from, to)).toBe("markdown_slash_commands.placeholders.table_column");+ });++ it("removes the typed command before running one of the text editor's commands", () => {+ expect(run("/date", "On /date")).toBe("On ");+ expect(triggerCommand).toHaveBeenCalledExactlyOnceWith("insertDateTimeToText");+ });+});+describe("useSlashCommands", () => {let container: HTMLElement;@@ -163,33 +256,47 @@ describe("useSlashCommands", () => {container.remove();});- /** Mounts the hook against an editor that only records what it is asked to register. */- function mount() {- const setCompletionSource = vi.fn();- const editorView = { setCompletionSource } as unknown as VanillaCodeMirror;-+ /** Mounts the hook against `editorView`. */+ function mount(editorView: VanillaCodeMirror) {function Probe() {- useSlashCommands({} as TypeWidgetProps["parentComponent"], editorView, {} as FNote);+ useSlashCommands({} as TypeWidgetProps["parentComponent"], editorView, { noteId: "n1" } as FNote);return null;}act(() => render(h(Probe, {}), container));- return setCompletionSource;}- it("contributes both sources to the editor's shared aggregate", () => {- const setCompletionSource = mount();+ it("registers the list and the fence languages with the editor, and withdraws both on unmount", () => {+ const setNamedExtension = vi.fn();+ const setCompletionSource = vi.fn();+ mount({ setNamedExtension, setCompletionSource } as unknown as VanillaCodeMirror);++ expect(setNamedExtension).toHaveBeenCalledExactlyOnceWith("slashCommands", expect.anything());+ expect(setCompletionSource).toHaveBeenCalledExactlyOnceWith("markdownCodeFence", expect.any(Function));- expect(setCompletionSource.mock.calls.map(([ name ]) => name)).toEqual([ "slashCommands", "markdownCodeFence" ]);- for (const [ , source ] of setCompletionSource.mock.calls) expect(source).toBeTypeOf("function");+ act(() => render(null, container));+ expect(setNamedExtension).toHaveBeenLastCalledWith("slashCommands", []);+ expect(setCompletionSource).toHaveBeenLastCalledWith("markdownCodeFence", null);});- it("withdraws both sources on unmount, so a later editor does not inherit them", () => {- const setCompletionSource = mount();- setCompletionSource.mockClear();+ it("lists the commands for what follows a slash, as the text editor does, and runs the one picked", async () => {+ const parent = document.createElement("div");+ document.body.append(parent);+ const editor = new VanillaCodeMirror({ parent });+ mount(editor);+ editor.focus();- act(() => render(null, container));+ editor.dispatch({ changes: { from: 0, insert: "/tab" }, selection: { anchor: 4 } });+ const rows = () => [ ...document.querySelectorAll(".note-autocomplete-menu [role=option]") ];+ await vi.waitFor(() => expect(rows().map((row) => row.textContent)).toEqual([ expect.stringContaining("/table") ]));+ expect(rows()[0]?.querySelector("b")?.textContent).toBe("/tab");- expect(setCompletionSource.mock.calls).toEqual([ [ "slashCommands", null ], [ "markdownCodeFence", null ] ]);+ // Opened on the best match, so Enter runs it.+ editor.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));+ await vi.waitFor(() => expect(editor.state.doc.toString()).toMatch(/^\| /));+ await vi.waitFor(() => expect(rows()).toEqual([]));++ act(() => render(null, container));+ editor.destroy();});});diff --git a/apps/client/src/widgets/type_widgets/markdown/completions.ts b/apps/client/src/widgets/type_widgets/markdown/completions.tsdeleted file mode 100644index 878c1c73a7..0000000000--- a/apps/client/src/widgets/type_widgets/markdown/completions.ts+++ /dev/null@@ -1,315 +0,0 @@-import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";-import { syntaxTree } from "@codemirror/language";-import type { EditorState } from "@codemirror/state";-import type { SyntaxNode } from "@lezer/common";-import type VanillaCodeMirror from "@triliumnext/codemirror";-import { isAnchorState, type TaskStateDef } from "@triliumnext/commons";-import { useEffect, useRef } from "preact/hooks";--import type FNote from "../../../entities/fnote";-import { t } from "../../../services/i18n";-import mime_types from "../../../services/mime_types";-import { getTaskStateDefinitions } from "../../../services/task_states";-import { buildSnippetCompletions, SLASH_COMMAND_REGEX, useCodeSnippets } from "../code/snippets";-import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams";-import type { TypeWidgetProps } from "../type_widget";-import { uploadImageAndInsert } from "./editor_utils";--/**- * Adds `/`-triggered autocomplete to the CodeMirror editor.- * Typing `/` at the start of a line (or after whitespace) shows a menu of commands.- */-export function useSlashCommands(parentComponent: TypeWidgetProps["parentComponent"], editorView: VanillaCodeMirror | null, note: FNote) {- // Held in refs so the slash-command closures always read the current note- // and parent component without re-registering the autocomplete extension —- // `appendConfig` would otherwise stack a duplicate extension on each switch.- const noteRef = useRef(note);- const parentRef = useRef(parentComponent);- // The user-configured todo task states (from the `_taskStates` subtree), loaded once.- // Read inside the autocomplete closure, so `/todo:*` commands reflect the current config.- const taskStatesRef = useRef<TaskStateDef[]>([]);- // Markdown snippets (#snippet code notes with a markdown MIME) plus generic plain-text snippets,- // inserted via `/snippet:<name>`. useCodeSnippets keeps the ref fresh so the menu reads the latest.- const snippetsRef = useCodeSnippets(- (candidate) => candidate.isMarkdown() || (candidate.type === "code" && candidate.mime === "text/plain"),- "markdown"- );- useEffect(() => { noteRef.current = note; }, [note]);- useEffect(() => { parentRef.current = parentComponent; }, [parentComponent]);- useEffect(() => { void getTaskStateDefinitions().then((states) => { taskStatesRef.current = states; }); }, []);-- useEffect(() => {- if (!editorView) return;-- const slashCommands = (ctx: CompletionContext): CompletionResult | null => {- // `:` and `-` are allowed so `/todo:<state>` (e.g. `/todo:in-progress`) matches as one token.- const match = ctx.matchBefore(SLASH_COMMAND_REGEX);- if (!match) return null;-- // Suppress slash menu inside fenced/indented code blocks and inline code spans —- // a leading `/` there is part of the code, not a command trigger.- for (let node: SyntaxNode | null = syntaxTree(ctx.state).resolveInner(ctx.pos, -1); node; node = node.parent) {- if (node.name.includes("Code")) return null;- }-- return {- from: match.from,- options: [- {- label: "/date",- detail: t("markdown_slash_commands.date"),- apply(view, _completion, from, to) {- view.dispatch({ changes: { from, to } });- parentRef.current?.triggerCommand("insertDateTimeToText");- }- },- {- label: "/include",- detail: t("markdown_slash_commands.include"),- apply(view, _completion, from, to) {- view.dispatch({ changes: { from, to } });- parentRef.current?.triggerCommand("addIncludeNoteToText");- }- },- {- label: "/image",- detail: t("markdown_slash_commands.image"),- apply(view, _completion, from, to) {- view.dispatch({ changes: { from, to } });- const input = document.createElement("input");- input.type = "file";- input.accept = "image/*";- input.addEventListener("change", () => {- const file = input.files?.[0];- if (file) uploadImageAndInsert(editorView, noteRef.current, file);- });- input.click();- }- },- {- label: "/link",- detail: t("markdown_slash_commands.link"),- apply(view, _completion, from, to) {- view.dispatch({ changes: { from, to } });- parentRef.current?.triggerCommand("addLinkToText");- }- },- {- label: "/math",- detail: t("markdown_slash_commands.math"),- apply(view, _completion, from, to) {- const placeholder = `\\text{${t("markdown_slash_commands.placeholders.math")}}`;- const template = `$$\n${placeholder}\n$$`;- view.dispatch({- changes: { from, to, insert: template },- selection: { anchor: from + 3, head: from + 3 + placeholder.length }- });- }- },- {- label: "/footnote",- detail: t("markdown_slash_commands.footnote"),- apply(view, _completion, from, to) {- const doc = view.state.doc.toString();- let maxFootnote = 0;- for (const m of doc.matchAll(/\[\^(\d+)\]/g)) {- maxFootnote = Math.max(maxFootnote, parseInt(m[1], 10));- }- const n = maxFootnote + 1;- const ref = `[^${n}]`;- const def = `\n\n[^${n}]: `;- const docEnd = view.state.doc.length;- const newDocEnd = docEnd - (to - from) + ref.length + def.length;- view.dispatch({- changes: [- { from, to, insert: ref },- { from: docEnd, insert: def }- ],- selection: { anchor: newDocEnd }- });- }- },- {- label: "/mermaid",- detail: t("markdown_slash_commands.mermaid"),- apply(view, _completion, from, to) {- const placeholder = "graph TD\n A --> B";- const template = `\`\`\`mermaid\n${placeholder}\n\`\`\``;- view.dispatch({- changes: { from, to, insert: template },- selection: { anchor: from + 11, head: from + 11 + placeholder.length }- });- }- },- // One `/mermaid:<type>` per sample diagram (e.g. `/mermaid:flowchart`),- // pre-filling the fenced block with that template's source.- ...SAMPLE_DIAGRAMS.map((sample) => ({- label: `/mermaid:${sample.name.toLowerCase().replace(/\s+/g, "-")}`,- detail: t("markdown_slash_commands.mermaid_template", { name: sample.name }),- apply(view: import("@codemirror/view").EditorView, _c: unknown, from: number, to: number) {- const template = `\`\`\`mermaid\n${sample.content.trimEnd()}\n\`\`\``;- view.dispatch({- changes: { from, to, insert: template },- selection: { anchor: from + 11 }- });- }- })),- {- label: "/collapsible",- detail: t("markdown_slash_commands.collapsible"),- apply(view, _completion, from, to) {- // No native markdown syntax — round-trips through the- // importer as raw <details>/<summary> HTML (see markdown.ts).- const placeholder = t("markdown_slash_commands.placeholders.collapsible_summary");- const open = `<details class="trilium-collapsible">\n<summary>`;- const close = `</summary>\n\n${t("markdown_slash_commands.placeholders.collapsible_details")}\n\n</details>`;- const anchor = from + open.length;- view.dispatch({- changes: { from, to, insert: open + placeholder + close },- selection: { anchor, head: anchor + placeholder.length }- });- }- },- {- label: "/page-break",- detail: t("markdown_slash_commands.page_break"),- apply(view, _completion, from, to) {- // No native markdown syntax — round-trips through the- // importer as raw HTML and drives the print/PDF page break (see print.css).- // The trailing blank line terminates the raw-HTML block; without it the- // text on the next line is swallowed into the <div> and never rendered.- const insert = `<div class="page-break"></div>\n\n`;- view.dispatch({- changes: { from, to, insert },- selection: { anchor: from + insert.length }- });- }- },- {- label: "/table",- detail: t("markdown_slash_commands.table"),- apply(view, _completion, from, to) {- // GFM table skeleton. The trailing blank line terminates the table block- // so following text isn't absorbed into it (see page break above).- const header = t("markdown_slash_commands.placeholders.table_column", { number: 1 });- const table = [- `| ${header} | ${t("markdown_slash_commands.placeholders.table_column", { number: 2 })} |`,- `| -------- | -------- |`,- `| | |`- ].join("\n");- // Select the first header cell so the user can type the first column name.- const anchor = from + 2; // skip the leading "| "- view.dispatch({- changes: { from, to, insert: `${table}\n\n` },- selection: { anchor, head: anchor + header.length }- });- }- },- ...["note", "tip", "important", "caution", "warning"].map((admonitionType) => ({- label: `/${admonitionType}`,- detail: t("markdown_slash_commands.admonition", { type: admonitionType }),- apply(view: import("@codemirror/view").EditorView, _c: unknown, from: number, to: number) {- const template = `> [!${admonitionType.toUpperCase()}]\n> `;- view.dispatch({- changes: { from, to, insert: template },- selection: { anchor: from + template.length }- });- }- })),- // One `/todo:<state>` per configured task state that has a markdown marker —- // the ` ` (unchecked) and `x` (checked) anchors are markers too, so both are covered.- ...taskStatesRef.current- .filter((state) => state.markdownSymbol)- .map((state) => {- // Anchors (`none`/`done`) are the standard `[ ]`/`[x]`; custom states- // use non-standard markers (e.g. `[/]`), so flag those in the description.- const detailKey = isAnchorState(state.name)- ? "markdown_slash_commands.todo"- : "markdown_slash_commands.todo_nonstandard";- return {- label: `/todo:${state.name}`,- detail: t(detailKey, { title: state.title }),- apply(view: import("@codemirror/view").EditorView, _c: unknown, from: number, to: number) {- const precededByBullet = from >= 2 && view.state.doc.sliceString(from - 2, from) === "- ";- const insert = buildTaskItemInsert(state.markdownSymbol, precededByBullet);- view.dispatch({ changes: { from, to, insert } });- }- };- }),- ...buildSnippetCompletions(snippetsRef.current.filter((snippet) => snippet.noteId !== noteRef.current.noteId))- ]- };- };-- // CodeMirror allows one `override` config per editor, so sources go through- // `setCompletionSource` instead of each adding its own `autocompletion()`.- // Bridges the codemirror package's own @codemirror/autocomplete identity, as code/snippets.ts does.- type CmCompletionSource = Parameters<VanillaCodeMirror["setCompletionSource"]>[1];- editorView.setCompletionSource("slashCommands", slashCommands as unknown as CmCompletionSource);- editorView.setCompletionSource("markdownCodeFence", codeFenceCompletionSource as unknown as CmCompletionSource);-- return () => {- editorView.setCompletionSource("slashCommands", null);- editorView.setCompletionSource("markdownCodeFence", null);- };- }, [editorView]);-}--/**- * Builds the markdown a `/todo:<state>` command inserts. Omits the leading `- `- * bullet when the slash was typed right after an existing one (e.g. `- /todo:doing`),- * so the existing bullet is reused instead of producing a doubled `- - [ ] ` marker.- */-export function buildTaskItemInsert(symbol: string, precededByBullet: boolean): string {- return `${precededByBullet ? "" : "- "}[${symbol}] `;-}--/**- * Parses the text of a line up to the cursor to detect a fenced code block opener being typed- * (e.g. "```", "```py", or an indented " ```js"). Returns the offset within the line where the- * language token starts (right after the run of backticks) and the partial language already typed,- * or `null` when the text isn't a fence opener. Pure helper, unit-tested.- */-export function parseCodeFencePrefix(lineBeforeCursor: string): { langStart: number; typed: string } | null {- const match = /^(\s*)(`{3,})([A-Za-z0-9+#._-]*)$/.exec(lineBeforeCursor);- if (!match) return null;- return { langStart: match[1].length + match[2].length, typed: match[3] };-}--/**- * Whether the fence on the line starting at `lineFrom` closes an already-open code block rather than- * opening a new one. A bare ``` is both opener and closer in Markdown, so language completions are- * only offered on openers: inside a `FencedCode` node that began on an earlier line, the ``` closes it.- */-export function isClosingFence(state: EditorState, lineFrom: number): boolean {- for (let node: SyntaxNode | null = syntaxTree(state).resolveInner(lineFrom, 1); node; node = node.parent) {- if (node.name === "FencedCode") return node.from < lineFrom;- }- return false;-}--/** Builds the fence-language completions from the user's enabled code-note languages. */-export function buildCodeFenceOptions(): Completion[] {- const seen = new Set<string>();- const options: Completion[] = [];- for (const mimeType of mime_types.getMimeTypes()) {- const code = mimeType.mdLanguageCode;- if (!mimeType.enabled || !code || seen.has(code)) continue;- seen.add(code);- options.push({ label: code, detail: mimeType.title });- }- return options;-}--/**- * Completion source for code-fence languages: triggers only right after a ``` fence opener and lists- * the user's enabled languages. Returns `null` everywhere else, so it never pollutes the slash menu.- */-export function codeFenceCompletionSource(context: CompletionContext): CompletionResult | null {- const line = context.state.doc.lineAt(context.pos);- const parsed = parseCodeFencePrefix(line.text.slice(0, context.pos - line.from));- if (!parsed || isClosingFence(context.state, line.from)) return null;-- const options = buildCodeFenceOptions();- return options.length ? { from: line.from + parsed.langStart, options } : null;-}diff --git a/apps/client/src/widgets/type_widgets/markdown/completions.tsx b/apps/client/src/widgets/type_widgets/markdown/completions.tsxnew file mode 100644index 0000000000..81909b0387--- /dev/null+++ b/apps/client/src/widgets/type_widgets/markdown/completions.tsx@@ -0,0 +1,350 @@+import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";+import { syntaxTree } from "@codemirror/language";+import type { EditorState } from "@codemirror/state";+import type { SyntaxNode } from "@lezer/common";+import type VanillaCodeMirror from "@triliumnext/codemirror";+import { hostedCompletion, type HostedCompletionApply, type HostedCompletionState } from "@triliumnext/codemirror/src/extensions/hosted_completion";+import { isAnchorState, NOTE_TYPE_ICONS, type TaskStateDef } from "@triliumnext/commons";+import { useEffect, useRef } from "preact/hooks";++import type FNote from "../../../entities/fnote";+import { t } from "../../../services/i18n";+import mime_types from "../../../services/mime_types";+import { getTaskStateDefinitions } from "../../../services/task_states";+import { type CommandEntry, CommandMentionList, createHostedList, filterCommandEntries } from "../../react/NoteAutocomplete";+import { type CodeSnippet, SLASH_COMMAND_REGEX, useCodeSnippets } from "../code/snippets";+import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams";+import type { TypeWidgetProps } from "../type_widget";+import { uploadImageAndInsert } from "./editor_utils";++/** A `/` command of the Markdown editor, listed as the text editor lists its own. */+export interface SlashCommand extends CommandEntry {+ /** Runs the command on the typed `/command`, which starts at `from` and ends at the caret, `to`. */+ apply: HostedCompletionApply;+}++/** The `/command` typed before the caret, which the list filters its commands by. */+export interface SlashCommandMatch {+ from: number;+ query: string;+}++/** What the commands are built from, read again each time the list looks them up. */+export interface SlashCommandContext {+ parentComponent: TypeWidgetProps["parentComponent"];+ note: FNote;+ editorView: VanillaCodeMirror;+ /** The user's task states, one `/todo:<state>` each where it has a Markdown marker. */+ taskStates: TaskStateDef[];+ snippets: CodeSnippet[];+}++/**+ * Lists the `/` commands typed at the start of a line or after whitespace in the shared command+ * list, as the text editor does, through `hostedCompletion()`. The code-fence languages stay with+ * CodeMirror's own completion.+ */+export function useSlashCommands(parentComponent: TypeWidgetProps["parentComponent"], editorView: VanillaCodeMirror | null, note: FNote) {+ // Held in refs so the commands read the current note and parent component without registering+ // the extension again.+ const noteRef = useRef(note);+ const parentRef = useRef(parentComponent);+ // The user-configured todo task states (from the `_taskStates` subtree), loaded once.+ const taskStatesRef = useRef<TaskStateDef[]>([]);+ // Markdown snippets (#snippet code notes with a markdown MIME) plus generic plain-text snippets,+ // inserted via `/snippet:<name>`. useCodeSnippets keeps the ref fresh so the list reads the latest.+ const snippetsRef = useCodeSnippets(+ (candidate) => candidate.isMarkdown() || (candidate.type === "code" && candidate.mime === "text/plain"),+ "markdown"+ );+ useEffect(() => { noteRef.current = note; }, [note]);+ useEffect(() => { parentRef.current = parentComponent; }, [parentComponent]);+ useEffect(() => { void getTaskStateDefinitions().then((states) => { taskStatesRef.current = states; }); }, []);++ useEffect(() => {+ if (!editorView) return;++ const commands = () => buildSlashCommands({+ parentComponent: parentRef.current,+ note: noteRef.current,+ editorView,+ taskStates: taskStatesRef.current,+ snippets: snippetsRef.current.filter((snippet) => snippet.noteId !== noteRef.current.noteId)+ });+ // Bridges the codemirror package's own @codemirror/state identity, as for the sources below.+ type CmSlashCommandMatcher = Parameters<typeof hostedCompletion<SlashCommandMatch>>[0]["match"];+ editorView.setNamedExtension("slashCommands", hostedCompletion({+ match: slashCommandAt as unknown as CmSlashCommandMatcher,+ list: () => createSlashCommandList(commands)+ }));+ // CodeMirror allows one `override` config per editor, so sources go through+ // `setCompletionSource` instead of each adding its own `autocompletion()`.+ // Bridges the codemirror package's own @codemirror/autocomplete identity, as code/snippets.ts does.+ type CmCompletionSource = Parameters<VanillaCodeMirror["setCompletionSource"]>[1];+ editorView.setCompletionSource("markdownCodeFence", codeFenceCompletionSource as unknown as CmCompletionSource);++ return () => {+ editorView.setNamedExtension("slashCommands", []);+ editorView.setCompletionSource("markdownCodeFence", null);+ };+ }, [editorView]);+}++/**+ * The `/command` typed before the caret, at the start of a line or after whitespace, or `null` in a+ * code block or a code span, where a `/` is part of the code.+ */+export function slashCommandAt(before: string, _explicit: boolean, state: EditorState): SlashCommandMatch | null {+ const typed = new RegExp(`${SLASH_COMMAND_REGEX.source}$`).exec(before);+ 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 { from: typed.index, query: typed[0] };+}++/** The commands the `/` list offers, in groups: the inserts, the diagrams, the blocks, the callouts, the tasks and the snippets. */+export function buildSlashCommands({ parentComponent, note, editorView, taskStates, snippets }: SlashCommandContext): SlashCommand[] {+ /** Removes the typed command, then runs one of the text editor's commands in its place. */+ const runCommand = (name: Parameters<NonNullable<typeof parentComponent>["triggerCommand"]>[0]): HostedCompletionApply =>+ (view, from, to) => {+ view.dispatch({ changes: { from, to } });+ parentComponent?.triggerCommand(name);+ };++ return [+ command("/date", t("markdown_slash_commands.date"), "bx bx-calendar", runCommand("insertDateTimeToText")),+ command("/include", t("markdown_slash_commands.include"), "bx bx-file", runCommand("addIncludeNoteToText")),+ command("/image", t("markdown_slash_commands.image"), "bx bx-image", (view, from, to) => {+ view.dispatch({ changes: { from, to } });+ const input = document.createElement("input");+ input.type = "file";+ input.accept = "image/*";+ input.addEventListener("change", () => {+ const file = input.files?.[0];+ if (file) uploadImageAndInsert(editorView, note, file);+ });+ input.click();+ }),+ command("/link", t("markdown_slash_commands.link"), "bx bx-link", runCommand("addLinkToText")),+ command("/math", t("markdown_slash_commands.math"), "bx bx-math", (view, from, to) => {+ const placeholder = `\\text{${t("markdown_slash_commands.placeholders.math")}}`;+ const template = `$$\n${placeholder}\n$$`;+ view.dispatch({+ changes: { from, to, insert: template },+ selection: { anchor: from + 3, head: from + 3 + placeholder.length }+ });+ }),+ command("/footnote", t("markdown_slash_commands.footnote"), "bx bx-comment-detail", (view, from, to) => {+ let maxFootnote = 0;+ for (const m of view.state.doc.toString().matchAll(/\[\^(\d+)\]/g)) {+ maxFootnote = Math.max(maxFootnote, parseInt(m[1], 10));+ }+ const n = maxFootnote + 1;+ const ref = `[^${n}]`;+ const def = `\n\n[^${n}]: `;+ const docEnd = view.state.doc.length;+ const newDocEnd = docEnd - (to - from) + ref.length + def.length;+ view.dispatch({+ changes: [+ { from, to, insert: ref },+ { from: docEnd, insert: def }+ ],+ selection: { anchor: newDocEnd }+ });+ }),+ command("/mermaid", t("markdown_slash_commands.mermaid"), NOTE_TYPE_ICONS.mermaid, (view, from, to) => {+ const placeholder = "graph TD\n A --> B";+ const template = `\`\`\`mermaid\n${placeholder}\n\`\`\``;+ view.dispatch({+ changes: { from, to, insert: template },+ selection: { anchor: from + 11, head: from + 11 + placeholder.length }+ });+ }),+ // One `/mermaid:<type>` per sample diagram (e.g. `/mermaid:flowchart`), pre-filling the+ // fenced block with that template's source.+ ...grouped(SAMPLE_DIAGRAMS.map((sample) => command(+ `/mermaid:${sample.name.toLowerCase().replace(/\s+/g, "-")}`,+ t("markdown_slash_commands.mermaid_template", { name: sample.name }),+ NOTE_TYPE_ICONS.mermaid,+ (view, from, to) => {+ const template = `\`\`\`mermaid\n${sample.content.trimEnd()}\n\`\`\``;+ view.dispatch({+ changes: { from, to, insert: template },+ selection: { anchor: from + 11 }+ });+ }+ ))),+ ...grouped([+ command("/collapsible", t("markdown_slash_commands.collapsible"), "bx bx-collapse-vertical", (view, from, to) => {+ // No native markdown syntax — round-trips through the importer as raw+ // <details>/<summary> HTML (see markdown.ts).+ const placeholder = t("markdown_slash_commands.placeholders.collapsible_summary");+ const open = `<details class="trilium-collapsible">\n<summary>`;+ const close = `</summary>\n\n${t("markdown_slash_commands.placeholders.collapsible_details")}\n\n</details>`;+ const anchor = from + open.length;+ view.dispatch({+ changes: { from, to, insert: open + placeholder + close },+ selection: { anchor, head: anchor + placeholder.length }+ });+ }),+ command("/page-break", t("markdown_slash_commands.page_break"), "bx bx-cut", (view, from, to) => {+ // No native markdown syntax — round-trips through the importer as raw HTML and+ // drives the print/PDF page break (see print.css). The trailing blank line ends the+ // raw-HTML block; without it the text on the next line is swallowed into the <div>.+ const insert = `<div class="page-break"></div>\n\n`;+ view.dispatch({+ changes: { from, to, insert },+ selection: { anchor: from + insert.length }+ });+ }),+ command("/table", t("markdown_slash_commands.table"), "bx bx-table", (view, from, to) => {+ // GFM table skeleton. The trailing blank line ends the table block so following text+ // isn't absorbed into it.+ const header = t("markdown_slash_commands.placeholders.table_column", { number: 1 });+ const table = [+ `| ${header} | ${t("markdown_slash_commands.placeholders.table_column", { number: 2 })} |`,+ `| -------- | -------- |`,+ `| | |`+ ].join("\n");+ // Selects the first header cell, past the leading "| ", for the first column's name.+ const anchor = from + 2;+ view.dispatch({+ changes: { from, to, insert: `${table}\n\n` },+ selection: { anchor, head: anchor + header.length }+ });+ })+ ]),+ ...grouped(Object.entries(ADMONITION_ICONS).map(([ admonitionType, icon ]) => command(+ `/${admonitionType}`,+ t("markdown_slash_commands.admonition", { type: admonitionType }),+ icon,+ (view, from, to) => {+ const template = `> [!${admonitionType.toUpperCase()}]\n> `;+ view.dispatch({+ changes: { from, to, insert: template },+ selection: { anchor: from + template.length }+ });+ }+ ))),+ // One `/todo:<state>` per configured task state that has a markdown marker — the ` `+ // (unchecked) and `x` (checked) anchors are markers too, so both are covered.+ ...grouped(taskStates+ .filter((state) => state.markdownSymbol)+ .map((state) => {+ // Anchors (`none`/`done`) are the standard `[ ]`/`[x]`; custom states use+ // non-standard markers (e.g. `[/]`), so the description flags those.+ const detailKey = isAnchorState(state.name)+ ? "markdown_slash_commands.todo"+ : "markdown_slash_commands.todo_nonstandard";+ return command(`/todo:${state.name}`, t(detailKey, { title: state.title }), state.icon, (view, from, to) => {+ const precededByBullet = from >= 2 && view.state.doc.sliceString(from - 2, from) === "- ";+ const insert = buildTaskItemInsert(state.markdownSymbol, precededByBullet);+ view.dispatch({ changes: { from, to, insert } });+ });+ })),+ ...grouped(snippets.map((snippet) => command(+ `/snippet:${snippet.title}`,+ snippet.description,+ "bx bx-code-curly",+ (view, from, to) => {+ view.dispatch({+ changes: { from, to, insert: snippet.content },+ selection: { anchor: from + snippet.content.length }+ });+ }+ )))+ ];+}++/** The callouts GitHub's Markdown knows, each with the icon of what it marks. */+const ADMONITION_ICONS: Record<string, string> = {+ note: "bx bx-info-circle",+ tip: "bx bx-bulb",+ important: "bx bx-message-square-error",+ caution: "bx bx-error-alt",+ warning: "bx bx-error"+};++function command(title: string, description: string | undefined, icon: string, apply: HostedCompletionApply): SlashCommand {+ return { id: title, title, description, icon, apply };+}++/** Sets `commands` apart from those before them with a divider. */+function grouped(commands: SlashCommand[]) {+ return commands.map((entry, index) => (index === 0 ? { ...entry, startsGroup: true } : entry));+}++/** The `/` list, which runs the command picked on the typed `/command`. */+function createSlashCommandList(commands: () => SlashCommand[]) {+ return createHostedList<HostedCompletionState<SlashCommandMatch>>((state, list) => (+ <CommandMentionList<SlashCommand>+ key={state.match.from}+ {...list}+ query={state.match.query}+ source={async (query) => filterCommandEntries(commands(), query)}+ onPick={(entry) => state.commit(entry.apply)}+ />+ ));+}++/**+ * Builds the markdown a `/todo:<state>` command inserts. Omits the leading `- `+ * bullet when the slash was typed right after an existing one (e.g. `- /todo:doing`),+ * so the existing bullet is reused instead of producing a doubled `- - [ ] ` marker.+ */+export function buildTaskItemInsert(symbol: string, precededByBullet: boolean): string {+ return `${precededByBullet ? "" : "- "}[${symbol}] `;+}++/**+ * Parses the text of a line up to the cursor to detect a fenced code block opener being typed+ * (e.g. "```", "```py", or an indented " ```js"). Returns the offset within the line where the+ * language token starts (right after the run of backticks) and the partial language already typed,+ * or `null` when the text isn't a fence opener. Pure helper, unit-tested.+ */+export function parseCodeFencePrefix(lineBeforeCursor: string): { langStart: number; typed: string } | null {+ const match = /^(\s*)(`{3,})([A-Za-z0-9+#._-]*)$/.exec(lineBeforeCursor);+ if (!match) return null;+ return { langStart: match[1].length + match[2].length, typed: match[3] };+}++/**+ * Whether the fence on the line starting at `lineFrom` closes an already-open code block rather than+ * opening a new one. A bare ``` is both opener and closer in Markdown, so language completions are+ * only offered on openers: inside a `FencedCode` node that began on an earlier line, the ``` closes it.+ */+export function isClosingFence(state: EditorState, lineFrom: number): boolean {+ for (let node: SyntaxNode | null = syntaxTree(state).resolveInner(lineFrom, 1); node; node = node.parent) {+ if (node.name === "FencedCode") return node.from < lineFrom;+ }+ return false;+}++/** Builds the fence-language completions from the user's enabled code-note languages. */+export function buildCodeFenceOptions(): Completion[] {+ const seen = new Set<string>();+ const options: Completion[] = [];+ for (const mimeType of mime_types.getMimeTypes()) {+ const code = mimeType.mdLanguageCode;+ if (!mimeType.enabled || !code || seen.has(code)) continue;+ seen.add(code);+ options.push({ label: code, detail: mimeType.title });+ }+ return options;+}++/**+ * Completion source for code-fence languages: triggers only right after a ``` fence opener and lists+ * the user's enabled languages. Returns `null` everywhere else, so it never pollutes the slash menu.+ */+export function codeFenceCompletionSource(context: CompletionContext): CompletionResult | null {+ const line = context.state.doc.lineAt(context.pos);+ const parsed = parseCodeFencePrefix(line.text.slice(0, context.pos - line.from));+ if (!parsed || isClosingFence(context.state, line.from)) return null;++ const options = buildCodeFenceOptions();+ return options.length ? { from: line.from + parsed.langStart, options } : null;+}diff --git a/packages/codemirror/src/extensions/hosted_completion.spec.ts b/packages/codemirror/src/extensions/hosted_completion.spec.tsindex cbc877dfe8..cb0985b85a 100644--- a/packages/codemirror/src/extensions/hosted_completion.spec.ts+++ b/packages/codemirror/src/extensions/hosted_completion.spec.ts@@ -1,4 +1,4 @@-import { EditorSelection } from "@codemirror/state";+import { EditorSelection, type EditorState } from "@codemirror/state";import { afterEach, describe, expect, it, vi } from "vitest";import { createFieldEditor, type FieldEditor, type FieldEditorConfig } from "../field_editor.js";@@ -16,21 +16,24 @@ interface TestMatch {from: number;query: string;explicit: boolean;+ /** Where the caret is, read from the state `match` is given. */+ at: number;}/*** An `@` where a value can stand, the query running to whitespace, as the search field has it; and* when asked explicitly, the word before the caret, empty as it can be.*/-function match(before: string, explicit: boolean): TestMatch | null {+function match(before: string, explicit: boolean, state: EditorState): TestMatch | null {+ const at = state.selection.main.head;const mention = /(?:^|\s)@([^\s@]*)$/.exec(before);if (mention) {const from = before.length - mention[1].length - 1;- return { from, query: mention[1], explicit };+ return { from, query: mention[1], explicit, at };}const word = /\w*$/.exec(before)?.[0] ?? "";- return explicit ? { from: before.length - word.length, query: word, explicit } : null;+ return explicit ? { from: before.length - word.length, query: word, explicit, at } : null;}describe("hostedCompletion", () => {@@ -44,6 +47,7 @@ describe("hostedCompletion", () => {type("Fo");await vi.waitFor(() => expect(shown()?.match.query).toBe("Fo"));expect(list.show).toHaveBeenCalledTimes(2);+ expect(shown()?.match.at).toBe(9);// Neither a selection change that keeps the text before the caret nor an empty update shows// it again.@@ -84,6 +88,16 @@ describe("hostedCompletion", () => {shown()?.commit("def456");expect(editor?.state.doc.toString()).toBe("#book\nabc123");+ // A function commits whatever it does to the text between the match and the caret.+ type(" @x");+ await vi.waitFor(() => expect(shown()?.match.query).toBe("x"));+ shown()?.commit((view, from, to) => {+ view.dispatch({ changes: { from, to, insert: "[1]" }, selection: { anchor: from } });+ });+ expect(editor?.state.doc.toString()).toBe("#book\nabc123 [1]");+ expect(editor?.state.selection.main.head).toBe(13);+ editor?.dispatch({ changes: { from: 12, to: 16 }, selection: EditorSelection.cursor(12) });+// A commit that leaves something to complete opens the list on it.type(" @Ba");await vi.waitFor(() => expect(shown()?.match.query).toBe("Ba"));@@ -158,7 +172,7 @@ describe("hostedCompletion", () => {expect(list.show).not.toHaveBeenCalled();expect(press(" ", { ctrlKey: true })).toBe(true);- await vi.waitFor(() => expect(shown()?.match).toEqual({ from: 6, query: "bo", explicit: true }));+ await vi.waitFor(() => expect(shown()?.match).toEqual({ from: 6, query: "bo", explicit: true, at: 8 }));// Asked for while the list is open, or closed with Escape, it shows the list again.expect(press("`", { altKey: true })).toBe(true);@@ -176,6 +190,15 @@ describe("hostedCompletion", () => {expect(list.show).toHaveBeenCalledTimes(3);});+ it("leaves Ctrl-Space to the editor where nothing can be completed", async () => {+ const { list } = build({}, () => null);++ type("#book");+ expect(press(" ", { ctrlKey: true })).toBe(false);+ await settle();+ expect(list.show).not.toHaveBeenCalled();+ });+it("closes as the editor loses the focus, and takes the list down with it", async () => {const { list, shown } = build();@@ -235,7 +258,7 @@ describe("hostedCompletion", () => {});});-function build(config: Partial<FieldEditorConfig> = {}) {+function build(config: Partial<FieldEditorConfig> = {}, matchAt: typeof match = match) {let element: HTMLElement | null = null;let state: HostedCompletionState<TestMatch> | undefined;let placed: unknown;@@ -260,7 +283,7 @@ function build(config: Partial<FieldEditorConfig> = {}) {editor = createFieldEditor({parent,...config,- extensions: [ hostedCompletion({ match, list: () => list }) ]+ extensions: [ hostedCompletion({ match: matchAt, list: () => list }) ]});editor.focus();editor.dispatch({ selection: EditorSelection.cursor(editor.state.doc.length) });diff --git a/packages/codemirror/src/extensions/hosted_completion.ts b/packages/codemirror/src/extensions/hosted_completion.tsindex 0c743a619e..1d09f1c75c 100644--- a/packages/codemirror/src/extensions/hosted_completion.ts+++ b/packages/codemirror/src/extensions/hosted_completion.ts@@ -7,6 +7,12 @@ export interface HostedCompletionMatch {from: number;}+/**+ * What a pick does in place of inserting text: changes the document between `from`, where the match+ * starts, and `to`, the caret, or runs something else, as a command does.+ */+export type HostedCompletionApply = (view: EditorView, from: number, to: number) => void;+/** What a {@link HostedCompletionList} is shown for, each time the text before the caret changes. */export interface HostedCompletionState<M extends HostedCompletionMatch> {match: M;@@ -14,8 +20,11 @@ export interface HostedCompletionState<M extends HostedCompletionMatch> {caretRect(): DOMRect;/** The editor's element. A list anchored at {@link caretRect} watches the containers around it. */editable: HTMLElement;- /** Replaces what stands between the match's `from` and the caret with `text`, as a pick does. */- commit(text: string): void;+ /**+ * Replaces what stands between the match's `from` and the caret with `insert`, as a pick does,+ * or runs `insert` on that range.+ */+ commit(insert: string | HostedCompletionApply): void;/*** Points the editor at the list's highlighted entry through `aria-activedescendant`, by the id* of the entry's element, or at none for `null`. Once the list closes, it points at none.@@ -41,9 +50,9 @@ export interface HostedCompletionConfig<M extends HostedCompletionMatch> {/*** What can be completed at the caret, read from the text of the line before it, or `null` where* nothing can. `explicit` is set after Ctrl-Space, which asks for completions where typing alone- * offers none.+ * offers none. `state` is there for what the text alone does not tell, such as the syntax tree.*/- match(before: string, explicit: boolean): M | null;+ match(before: string, explicit: boolean, state: EditorState): M | null;/** Creates the list, once per editor. */list(view: EditorView): HostedCompletionList<M>;}@@ -96,6 +105,10 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, listthis.dismissedAt = -1;this.from = -1;this.sync();+ // Nothing to complete here, so the key goes on to the editor's own completion.+ if (this.from < 0) {+ return false;+ }} else if (this.from < 0) {return false;} else if (event.key === "Escape") {@@ -150,7 +163,7 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, listmatch: found.match,caretRect: () => (showing ? measured : caretRect(this.view)),editable: this.view.dom,- commit: (text) => this.commit(found.from, text),+ commit: (insert) => this.commit(found.from, insert),setActiveDescendant: (id) => {if (this.from === found.from) {this.setActiveDescendant(id);@@ -162,12 +175,18 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, list});}- private commit(from: number, text: string) {+ private commit(from: number, insert: string | HostedCompletionApply) {if (this.from !== from) {return;}this.explicit = false;+ if (typeof insert === "function") {+ insert(this.view, from, this.view.state.selection.main.head);+ return;+ }++ const text = insert;this.view.dispatch({changes: { from, to: this.view.state.selection.main.head, insert: text },selection: { anchor: from + text.length },@@ -221,7 +240,7 @@ function matchAt<M extends HostedCompletionMatch>(state: EditorState, match: Hosconst line = state.doc.lineAt(main.head);const before = line.text.slice(0, main.head - line.from);- const found = match(before, explicit);+ const found = match(before, explicit, state);return found && { match: found, from: line.from + found.from, before };}