Skip to content

Build your personal knowledge base with Trilium Notes

feat(markdown): title the slash commands as the text editor does

Elian Doranbd8e13802b1f
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 328e4ae366..b519c05972 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -376,6 +376,25 @@
"admonition": "Insert {{type}} admonition",
"todo": "Insert a \"{{title}}\" task item",
"todo_nonstandard": "Insert a \"{{title}}\" task item (non-standard)",
+ "titles": {
+ "date": "Insert date/time",
+ "include": "Include note",
+ "image": "Upload image",
+ "link": "Internal link",
+ "math": "Math equation",
+ "footnote": "Footnote",
+ "mermaid": "Mermaid diagram",
+ "mermaid_template": "Mermaid diagram: {{name}}",
+ "collapsible": "Collapsible block",
+ "page_break": "Page break",
+ "table": "Table",
+ "note": "Note",
+ "tip": "Tip",
+ "important": "Important",
+ "caution": "Caution",
+ "warning": "Warning",
+ "todo": "Task: {{title}}"
+ },
"placeholders": {
"math": "equation",
"collapsible_summary": "Summary",
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
index 721048150b..cebb262ecf 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
@@ -1308,3 +1308,21 @@ describe("filterCommandEntries", () => {
expect(filterCommandEntries(entries, "")).toEqual(entries);
});
});
+
+describe("filterCommandEntries with aliases", () => {
+ it("ranks title prefixes, then alias prefixes, then titles and aliases holding the query", () => {
+ const entries = [
+ { id: "toc", title: "Table of contents", aliases: [ "outline" ] },
+ { id: "rule", title: "Horizontal line", aliases: [ "divider", "rule" ] },
+ { id: "table", title: "Table", aliases: [ "grid" ] },
+ { id: "code", title: "Code block", aliases: [ "snippet", "pre" ] },
+ { id: "quote", title: "Block quote", aliases: [ "citation" ] }
+ ];
+ const ids = (query: string) => filterCommandEntries(entries, query).map((entry) => entry.id);
+
+ expect(ids("ta")).toEqual([ "toc", "table", "rule", "quote" ]);
+ expect(ids("r")).toEqual([ "rule", "table", "code" ]);
+ expect(ids("GRID")).toEqual([ "table" ]);
+ expect(ids("tline")).toEqual([ "toc" ]);
+ });
+});
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsx
index 77670e32f2..6bf49496da 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx
@@ -500,6 +500,8 @@ export interface CommandEntry {
iconText?: string;
/** Draws a divider above the entry, setting it and those after it apart from the ones before. */
startsGroup?: boolean;
+ /** Further words the entry is found by, ranked below its title, as the text editor's `/` palette does. */
+ aliases?: string[];
}
/**
@@ -556,15 +558,29 @@ 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.
+ * The entries of a {@link CommandMentionList} whose title or aliases hold `query`, ignoring case,
+ * ranked as the text editor's `/` palette ranks its commands: a title starting with it, then an
+ * alias starting with it, then a title holding it, then an alias holding it. Each rank keeps the
+ * order the entries 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));
+ const rankOf = ({ title, aliases = [] }: T) => {
+ const words = aliases.map((alias) => alias.toLowerCase());
+ const name = title.toLowerCase();
+ if (name.startsWith(typed)) return 0;
+ if (words.some((word) => word.startsWith(typed))) return 1;
+ if (name.includes(typed)) return 2;
+ if (words.some((word) => word.includes(typed))) return 3;
+ return null;
+ };
- return [ ...starting, ...containing ];
+ const ranked: T[][] = [ [], [], [], [] ];
+ for (const entry of entries) {
+ const rank = rankOf(entry);
+ if (rank !== null) ranked[rank].push(entry);
+ }
+ return ranked.flat();
}
/** What a list drawn by {@link createHostedList} is given to draw itself with. */
diff --git a/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts b/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts
index ad1d618a4e..86d3c51e37 100644
--- a/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts
+++ b/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts
@@ -20,7 +20,10 @@ vi.mock("../code/snippets", async (importOriginal) => ({
}));
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 }));
+vi.mock("../../../services/i18n", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../../../services/i18n")>(),
+ t: (key: string) => key
+}));
describe("buildTaskItemInsert", () => {
it("prepends a bullet when not already in a list item", () => {
@@ -161,10 +164,10 @@ describe("slashCommandAt", () => {
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 a command at the start of a line or after whitespace, from its slash, by what follows it", () => {
+ 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", () => {
@@ -200,45 +203,47 @@ describe("buildSlashCommands", () => {
});
}
- /** Puts `doc` in the editor and runs `title` on the command typed at its end. */
- function run(title: string, doc: string, taskStates: TaskStateDef[] = []) {
+ /** Puts `doc` in the editor and runs the command `id` on the command typed at its end. */
+ function run(id: 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}`);
+ const entry = commands(taskStates).find((candidate) => candidate.id === id);
+ if (!entry) throw new Error(`no command ${id}`);
entry.apply(editor, doc.lastIndexOf("/"), doc.length);
return editor.state.doc.toString();
}
- it("lists each command with its icon, setting each group apart", () => {
+ it("titles and draws each command as the text editor does, found by what is typed after the slash too", () => {
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);
+ const byId = (id: string) => entries.find((entry) => entry.id === id);
+
+ expect(byId("table")).toMatchObject({ title: "markdown_slash_commands.titles.table", aliases: [ "table", "grid" ] });
+ expect(byId("table")?.iconSvg).toContain("<svg");
+ expect(byId("tip")?.iconSvg).toContain("<svg");
+ expect(byId("todo:done")).toMatchObject({ aliases: expect.arrayContaining([ "todo:done", "done" ]), icon: "bx bx-done", startsGroup: true });
+ expect(byId("snippet:Greeting")).toMatchObject({ title: "Greeting", description: "Says hello", icon: "bx bx-code-curly", startsGroup: true });
+ expect(byId("date")?.startsGroup).toBeUndefined();
+ expect(byId("tip")?.startsGroup).toBeUndefined();
+ expect(byId("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> ");
+ 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(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");
+ 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(run("date", "On /date")).toBe("On ");
expect(triggerCommand).toHaveBeenCalledExactlyOnceWith("insertDateTimeToText");
});
});
@@ -286,14 +291,15 @@ describe("useSlashCommands", () => {
mount(editor);
editor.focus();
- editor.dispatch({ changes: { from: 0, insert: "/tab" }, selection: { anchor: 4 } });
+ editor.dispatch({ changes: { from: 0, insert: "/tip" }, 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");
+ // Found by its title, without the slash.
+ await vi.waitFor(() => expect(rows().map((row) => row.textContent)).toEqual([ expect.stringContaining("titles.tip") ]));
+ expect(rows()[0]?.querySelector("b")?.textContent).toBe("tip");
// 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(editor.state.doc.toString()).toBe("> [!TIP]\n> "));
await vi.waitFor(() => expect(rows()).toEqual([]));
act(() => render(null, container));
diff --git a/apps/client/src/widgets/type_widgets/markdown/completions.tsx b/apps/client/src/widgets/type_widgets/markdown/completions.tsx
index 81909b0387..36095eefb6 100644
--- a/apps/client/src/widgets/type_widgets/markdown/completions.tsx
+++ b/apps/client/src/widgets/type_widgets/markdown/completions.tsx
@@ -1,10 +1,23 @@
+import { IconImage, IconPageBreak, IconTable } from "@ckeditor/ckeditor5-icons";
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 collapsibleIcon from "@triliumnext/ckeditor5/src/icons/collapsible.svg?raw";
+import dateTimeIcon from "@triliumnext/ckeditor5/src/icons/date-time.svg?raw";
+import insertFootnoteIcon from "@triliumnext/ckeditor5/src/icons/insert-footnote.svg?raw";
+import mathIcon from "@triliumnext/ckeditor5/src/icons/math.svg?raw";
+import noteIcon from "@triliumnext/ckeditor5/src/icons/note.svg?raw";
+import internalLinkIcon from "@triliumnext/ckeditor5/src/icons/trilium.svg?raw";
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 { isAnchorState, type TaskStateDef } from "@triliumnext/commons";
+import bxBulb from "boxicons/svg/regular/bx-bulb.svg?raw";
+import bxCommentError from "boxicons/svg/regular/bx-comment-error.svg?raw";
+import bxError from "boxicons/svg/regular/bx-error.svg?raw";
+import bxErrorCircle from "boxicons/svg/regular/bx-error-circle.svg?raw";
+import bxInfoCircle from "boxicons/svg/regular/bx-info-circle.svg?raw";
+import bxNetworkChart from "boxicons/svg/regular/bx-network-chart.svg?raw";
import { useEffect, useRef } from "preact/hooks";
import type FNote from "../../../entities/fnote";
@@ -23,9 +36,10 @@ export interface SlashCommand extends CommandEntry {
apply: HostedCompletionApply;
}
-/** The `/command` typed before the caret, which the list filters its commands by. */
+/** The `/command` typed before the caret, from its `/`. */
export interface SlashCommandMatch {
from: number;
+ /** What follows the `/`, which the list filters its commands by, as the text editor's does. */
query: string;
}
@@ -102,10 +116,15 @@ export function slashCommandAt(before: string, _explicit: boolean, state: Editor
if (node.name.includes("Code")) return null;
}
- return { from: typed.index, query: typed[0] };
+ return { from: typed.index, query: typed[0].slice(1) };
}
-/** The commands the `/` list offers, in groups: the inserts, the diagrams, the blocks, the callouts, the tasks and the snippets. */
+/**
+ * The commands the `/` list offers, titled, described, found by the same words and drawn with the same
+ * icons as the text editor's, where it has the command too. Each is found by the word typed after the
+ * `/` as well, such as `todo:done`. 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 =>
@@ -115,9 +134,23 @@ export function buildSlashCommands({ parentComponent, note, editorView, taskStat
};
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) => {
+ command("date", {
+ title: t("markdown_slash_commands.titles.date"),
+ description: t("markdown_slash_commands.date"),
+ aliases: [ "time", "now", "today", "timestamp" ],
+ iconSvg: dateTimeIcon
+ }, runCommand("insertDateTimeToText")),
+ command("include", {
+ title: t("markdown_slash_commands.titles.include"),
+ description: t("markdown_slash_commands.include"),
+ iconSvg: noteIcon
+ }, runCommand("addIncludeNoteToText")),
+ command("image", {
+ title: t("markdown_slash_commands.titles.image"),
+ description: t("markdown_slash_commands.image"),
+ aliases: [ "upload", "picture" ],
+ iconSvg: IconImage
+ }, (view, from, to) => {
view.dispatch({ changes: { from, to } });
const input = document.createElement("input");
input.type = "file";
@@ -128,8 +161,18 @@ export function buildSlashCommands({ parentComponent, note, editorView, taskStat
});
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) => {
+ command("link", {
+ title: t("markdown_slash_commands.titles.link"),
+ description: t("markdown_slash_commands.link"),
+ aliases: [ "internal link", "trilium link", "reference link" ],
+ iconSvg: internalLinkIcon
+ }, runCommand("addLinkToText")),
+ command("math", {
+ title: t("markdown_slash_commands.titles.math"),
+ description: t("markdown_slash_commands.math"),
+ aliases: [ "latex", "equation" ],
+ iconSvg: mathIcon
+ }, (view, from, to) => {
const placeholder = `\\text{${t("markdown_slash_commands.placeholders.math")}}`;
const template = `$$\n${placeholder}\n$$`;
view.dispatch({
@@ -137,7 +180,11 @@ export function buildSlashCommands({ parentComponent, note, editorView, taskStat
selection: { anchor: from + 3, head: from + 3 + placeholder.length }
});
}),
- command("/footnote", t("markdown_slash_commands.footnote"), "bx bx-comment-detail", (view, from, to) => {
+ command("footnote", {
+ title: t("markdown_slash_commands.titles.footnote"),
+ description: t("markdown_slash_commands.footnote"),
+ iconSvg: insertFootnoteIcon
+ }, (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));
@@ -155,7 +202,12 @@ export function buildSlashCommands({ parentComponent, note, editorView, taskStat
selection: { anchor: newDocEnd }
});
}),
- command("/mermaid", t("markdown_slash_commands.mermaid"), NOTE_TYPE_ICONS.mermaid, (view, from, to) => {
+ command("mermaid", {
+ title: t("markdown_slash_commands.titles.mermaid"),
+ description: t("markdown_slash_commands.mermaid"),
+ aliases: [ "diagram", "flowchart" ],
+ iconSvg: bxNetworkChart
+ }, (view, from, to) => {
const placeholder = "graph TD\n A --> B";
const template = `\`\`\`mermaid\n${placeholder}\n\`\`\``;
view.dispatch({
@@ -165,20 +217,25 @@ export function buildSlashCommands({ parentComponent, note, editorView, taskStat
}),
// 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(SAMPLE_DIAGRAMS.map((sample) => command(`mermaid:${sample.name.toLowerCase().replace(/\s+/g, "-")}`, {
+ title: t("markdown_slash_commands.titles.mermaid_template", { name: sample.name }),
+ description: t("markdown_slash_commands.mermaid_template", { name: sample.name }),
+ aliases: [ "mermaid", "diagram", sample.name ],
+ iconSvg: bxNetworkChart
+ }, (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) => {
+ command("collapsible", {
+ title: t("markdown_slash_commands.titles.collapsible"),
+ description: t("markdown_slash_commands.collapsible"),
+ aliases: [ "details", "fold", "toggle", "collapse", "expand", "accordion", "spoiler", "summary", "disclosure", "hide" ],
+ iconSvg: collapsibleIcon
+ }, (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");
@@ -190,7 +247,11 @@ export function buildSlashCommands({ parentComponent, note, editorView, taskStat
selection: { anchor, head: anchor + placeholder.length }
});
}),
- command("/page-break", t("markdown_slash_commands.page_break"), "bx bx-cut", (view, from, to) => {
+ command("page-break", {
+ title: t("markdown_slash_commands.titles.page_break"),
+ description: t("markdown_slash_commands.page_break"),
+ iconSvg: IconPageBreak
+ }, (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>.
@@ -200,7 +261,12 @@ export function buildSlashCommands({ parentComponent, note, editorView, taskStat
selection: { anchor: from + insert.length }
});
}),
- command("/table", t("markdown_slash_commands.table"), "bx bx-table", (view, from, to) => {
+ command("table", {
+ title: t("markdown_slash_commands.titles.table"),
+ description: t("markdown_slash_commands.table"),
+ aliases: [ "grid" ],
+ iconSvg: IconTable
+ }, (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 });
@@ -217,18 +283,18 @@ export function buildSlashCommands({ parentComponent, note, editorView, taskStat
});
})
]),
- ...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 }
- });
- }
- ))),
+ ...grouped(admonitions().map(({ type, title, icon }) => command(type, {
+ title,
+ description: t("markdown_slash_commands.admonition", { type }),
+ aliases: [ "admonition", "box" ],
+ iconSvg: icon
+ }, (view, from, to) => {
+ const template = `> [!${type.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
@@ -239,37 +305,48 @@ export function buildSlashCommands({ parentComponent, note, editorView, taskStat
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) => {
+ return command(`todo:${state.name}`, {
+ title: t("markdown_slash_commands.titles.todo", { title: state.title }),
+ description: t(detailKey, { title: state.title }),
+ aliases: [ "todo", "task", "checkbox", state.title ],
+ icon: 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 }
- });
- }
- )))
+ ...grouped(snippets.map((snippet) => command(`snippet:${snippet.title}`, {
+ title: snippet.title,
+ description: snippet.description,
+ aliases: [ "snippet", "template" ],
+ icon: "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"
-};
+/**
+ * GitHub's callouts, titled and drawn as the text editor's admonitions are. Built on each call,
+ * as the catalogue loads after this module.
+ */
+function admonitions() {
+ return [
+ { type: "note", title: t("markdown_slash_commands.titles.note"), icon: bxInfoCircle },
+ { type: "tip", title: t("markdown_slash_commands.titles.tip"), icon: bxBulb },
+ { type: "important", title: t("markdown_slash_commands.titles.important"), icon: bxCommentError },
+ { type: "caution", title: t("markdown_slash_commands.titles.caution"), icon: bxErrorCircle },
+ { type: "warning", title: t("markdown_slash_commands.titles.warning"), icon: bxError }
+ ];
+}
-function command(title: string, description: string | undefined, icon: string, apply: HostedCompletionApply): SlashCommand {
- return { id: title, title, description, icon, apply };
+/** A command typed as `/name`, which `name` finds as well as its title and aliases. */
+function command(name: string, entry: Omit<SlashCommand, "id" | "apply">, apply: HostedCompletionApply): SlashCommand {
+ return { ...entry, id: name, aliases: [ name, ...(entry.aliases ?? []) ], apply };
}
/** Sets `commands` apart from those before them with a divider. */
@@ -277,7 +354,7 @@ 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`. */
+/** The `/` list, drawn as the text editor's, which runs the command picked on the typed `/command`. */
function createSlashCommandList(commands: () => SlashCommand[]) {
return createHostedList<HostedCompletionState<SlashCommandMatch>>((state, list) => (
<CommandMentionList<SlashCommand>
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.html
index b2a9125424..870596a34f 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
@@ -207,6 +207,9 @@
<li>Inserting code snippets (<code>/snippet:&lt;name&gt;</code>) from your
Markdown/plain-text snippet notes.</li>
</ul>
+<p>The list shows each command by its title, as in Text notes. Typing a command's
+ title, its keyword (as listed above) or a related word such as <code>latex</code> or <code>grid</code> finds
+ it.</p>
<p>Note that slash commands only work outside of 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 automatically
diff --git a/docs/User Guide/User Guide/Note Types/Markdown.md b/docs/User Guide/User Guide/Note Types/Markdown.md
index 040631dda3..8c90d50e41 100644
--- a/docs/User Guide/User Guide/Note Types/Markdown.md
+++ b/docs/User Guide/User Guide/Note Types/Markdown.md
@@ -171,6 +171,8 @@ Just like <a class="reference-link" href="Text.md">Text</a> notes, Markdown no
* Inserting task items (`/todo:<state>`, e.g. `/todo:done`), one per configured task state.
* Inserting code snippets (`/snippet:<name>`) from your Markdown/plain-text snippet notes.
+The list shows each command by its title, as in Text notes. Typing a command's title, its keyword (as listed above) or a related word such as `latex` or `grid` finds it.
+
Note that slash commands only work outside of code blocks and inline code.
#### Code block language auto-completion