Skip to content

Build your personal knowledge base with Trilium Notes

client/snippets/code notes: add support for snippets in the slash commands

Adorian Doran1d4f9361a7be
diff --git a/apps/client/src/widgets/type_widgets/code/Code.tsx b/apps/client/src/widgets/type_widgets/code/Code.tsx
index 30517f0297..44c2ab6b76 100644
--- a/apps/client/src/widgets/type_widgets/code/Code.tsx
+++ b/apps/client/src/widgets/type_widgets/code/Code.tsx
@@ -14,6 +14,7 @@ import { refToJQuerySelector } from "../../react/react_utils";
import { CODE_THEME_DEFAULT_PREFIX as DEFAULT_PREFIX } from "../constants";
import { TypeWidgetProps } from "../type_widget";
import CodeMirror, { CodeMirrorProps } from "./CodeMirror";
+import { useSnippetSlashCommands } from "./snippets";
interface CodeEditorProps {
/** By default, the code editor will try to match the color of the scrolling container to match the one from the theme for a full-screen experience. If the editor is embedded, it makes sense not to have this behaviour. */
@@ -87,8 +88,10 @@ function formatViewSource(note: FNote, content: string) {
export function EditableCode({ note, ntxId, noteContext, debounceUpdate, parentComponent, updateInterval, noteType = "code", onContentChanged, dataSaved, placeholder, editorRef: externalEditorRef, ...editorProps }: EditableCodeProps) {
const editorRef = useRef<VanillaCodeMirror>(null);
const containerRef = useRef<HTMLPreElement>(null);
+ const [ editorView, setEditorView ] = useState<VanillaCodeMirror | null>(null);
const combinedEditorRef = (view: VanillaCodeMirror | null) => {
editorRef.current = view;
+ setEditorView(view);
if (typeof externalEditorRef === "function") externalEditorRef(view);
else if (externalEditorRef) externalEditorRef.current = view;
};
@@ -126,6 +129,15 @@ export function EditableCode({ note, ntxId, noteContext, debounceUpdate, parentC
useKeyboardShortcuts("code-detail", containerRef, parentComponent, ntxId);
+ // Code snippets (#snippet notes with a matching MIME) as `/snippet:<name>` slash commands.
+ // Disabled for Markdown notes, whose editor provides its own combined slash-command menu.
+ useSnippetSlashCommands(
+ editorView,
+ (candidate) => candidate.type === "code" && candidate.mime === note.mime,
+ note.mime,
+ !note.isMarkdown()
+ );
+
return (
<CodeEditor
ntxId={ntxId} parentComponent={parentComponent}
diff --git a/apps/client/src/widgets/type_widgets/code/Markdown.tsx b/apps/client/src/widgets/type_widgets/code/Markdown.tsx
index 23d267165b..9c19582c88 100644
--- a/apps/client/src/widgets/type_widgets/code/Markdown.tsx
+++ b/apps/client/src/widgets/type_widgets/code/Markdown.tsx
@@ -30,7 +30,7 @@ import SplitEditor from "../helpers/SplitEditor";
import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams";
import { ReadOnlyTextContent } from "../text/ReadOnlyText";
import { TypeWidgetProps } from "../type_widget";
-import { type CodeSnippet, getCodeSnippets, isCodeSnippetChange } from "./snippets";
+import { buildSnippetCompletions, SLASH_COMMAND_REGEX, useCodeSnippets } from "./snippets";
const marked = new Marked({ breaks: true, gfm: true });
@@ -510,31 +510,19 @@ function useSlashCommands(parentComponent: TypeWidgetProps["parentComponent"], e
// 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), inserted via `/snippet:<name>`.
- // Held in a ref and refreshed on entity changes so the slash menu reads the latest list when it
- // opens, without re-registering the autocomplete extension.
- const snippetsRef = useRef<CodeSnippet[]>([]);
+ // useCodeSnippets keeps the ref fresh so the slash menu reads the latest list when it opens.
+ const snippetsRef = useCodeSnippets((candidate) => candidate.isMarkdown(), "markdown");
useEffect(() => { noteRef.current = note; }, [note]);
useEffect(() => { parentRef.current = parentComponent; }, [parentComponent]);
useEffect(() => { void getTaskStateDefinitions().then((states) => { taskStatesRef.current = states; }); }, []);
- const reloadSnippets = useCallback(() => {
- void getCodeSnippets((candidate) => candidate.isMarkdown()).then((snippets) => { snippetsRef.current = snippets; });
- }, []);
- useEffect(() => { reloadSnippets(); }, [reloadSnippets]);
- useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
- const knownNoteIds = new Set(snippetsRef.current.map((snippet) => snippet.noteId));
- if (isCodeSnippetChange(loadResults, knownNoteIds)) {
- reloadSnippets();
- }
- });
-
useEffect(() => {
if (!editorView) return;
const ext = autocompletion({
override: [(ctx) => {
// `:` and `-` are allowed so `/todo:<state>` (e.g. `/todo:in-progress`) matches as one token.
- const match = ctx.matchBefore(/(?:^|(?<=\s))\/[\w:-]*/);
+ const match = ctx.matchBefore(SLASH_COMMAND_REGEX);
if (!match) return null;
// Suppress slash menu inside fenced/indented code blocks and inline code spans —
@@ -692,17 +680,7 @@ function useSlashCommands(parentComponent: TypeWidgetProps["parentComponent"], e
}
};
}),
- ...snippetsRef.current.map((snippet) => ({
- label: snippet.description
- ? `/snippet:${snippet.title} - ${snippet.description}`
- : `/snippet:${snippet.title}`,
- apply(view: import("@codemirror/view").EditorView, _c: unknown, from: number, to: number) {
- view.dispatch({
- changes: { from, to, insert: snippet.content },
- selection: { anchor: from + snippet.content.length }
- });
- }
- }))
+ ...buildSnippetCompletions(snippetsRef.current)
]
};
}],
diff --git a/apps/client/src/widgets/type_widgets/code/snippets.ts b/apps/client/src/widgets/type_widgets/code/snippets.ts
index 3d301dd2a1..44fa815619 100644
--- a/apps/client/src/widgets/type_widgets/code/snippets.ts
+++ b/apps/client/src/widgets/type_widgets/code/snippets.ts
@@ -1,6 +1,15 @@
+import { autocompletion, type Completion, type CompletionContext } from "@codemirror/autocomplete";
+import type { EditorView } from "@codemirror/view";
+import type VanillaCodeMirror from "@triliumnext/codemirror";
+import { useCallback, useEffect, useRef } from "preact/hooks";
+
import type FNote from "../../../entities/fnote.js";
import type LoadResults from "../../../services/load_results.js";
import search from "../../../services/search.js";
+import { useTriliumEvent } from "../../react/hooks";
+
+/** Matches a `/command` token at the start of a line or after whitespace. Shared by every editor. */
+export const SLASH_COMMAND_REGEX = /(?:^|(?<=\s))\/[\w:-]*/;
export interface CodeSnippet {
noteId: string;
@@ -44,3 +53,82 @@ export function isCodeSnippetChange(loadResults: LoadResults, knownNoteIds: Set<
return attributeChanged || loadResults.getNoteIds().some((noteId) => knownNoteIds.has(noteId));
}
+
+/**
+ * Builds the `/snippet:<title> - <description>` CodeMirror completions; applying one replaces the
+ * typed `/snippet:…` token with the snippet's content and moves the caret to its end.
+ */
+export function buildSnippetCompletions(snippets: CodeSnippet[]): Completion[] {
+ return snippets.map((snippet) => ({
+ label: snippet.description
+ ? `/snippet:${snippet.title} - ${snippet.description}`
+ : `/snippet:${snippet.title}`,
+ apply(view: EditorView, _completion: Completion, from: number, to: number) {
+ view.dispatch({
+ changes: { from, to, insert: snippet.content },
+ selection: { anchor: from + snippet.content.length }
+ });
+ }
+ }));
+}
+
+/**
+ * Loads the snippets accepted by `matches` into a ref and keeps it fresh: reloaded on mount, when
+ * `reloadKey` changes (e.g. the editor note's MIME), and when relevant entities change. Held in a
+ * ref so consumers (a slash menu) read the latest list when invoked, without re-registering anything.
+ * When `enabled` is false the ref stays empty and nothing is loaded.
+ */
+export function useCodeSnippets(matches: (note: FNote) => boolean, reloadKey: string, enabled = true) {
+ const snippetsRef = useRef<CodeSnippet[]>([]);
+ // Keep the latest predicate without making it a dependency (it's a fresh closure each render);
+ // `reloadKey` is the stable trigger for filter changes.
+ const matchesRef = useRef(matches);
+ useEffect(() => { matchesRef.current = matches; });
+
+ const reload = useCallback(() => {
+ if (!enabled) {
+ snippetsRef.current = [];
+ return;
+ }
+ void getCodeSnippets((note) => matchesRef.current(note)).then((snippets) => {
+ snippetsRef.current = snippets;
+ });
+ }, [enabled]);
+
+ useEffect(() => { reload(); }, [reload, reloadKey]);
+
+ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
+ if (!enabled) return;
+ const knownNoteIds = new Set(snippetsRef.current.map((snippet) => snippet.noteId));
+ if (isCodeSnippetChange(loadResults, knownNoteIds)) {
+ reload();
+ }
+ });
+
+ return snippetsRef;
+}
+
+/**
+ * Registers a `/snippet:<name>` slash command on a CodeMirror code editor, listing the snippets
+ * accepted by `matches` (e.g. those whose MIME equals the editor note's). Inserting one drops its
+ * content at the cursor. No-op when `enabled` is false (e.g. the Markdown editor, which builds its
+ * own combined slash-command menu instead).
+ */
+export function useSnippetSlashCommands(editorView: VanillaCodeMirror | null, matches: (note: FNote) => boolean, reloadKey: string, enabled: boolean) {
+ const snippetsRef = useCodeSnippets(matches, reloadKey, enabled);
+
+ useEffect(() => {
+ if (!editorView || !enabled) return;
+
+ const extension = autocompletion({
+ override: [(context: CompletionContext) => {
+ const match = context.matchBefore(SLASH_COMMAND_REGEX);
+ if (!match) return null;
+ return { from: match.from, options: buildSnippetCompletions(snippetsRef.current) };
+ }],
+ activateOnTyping: true
+ });
+
+ editorView.setNamedExtension("snippetCommands", extension);
+ }, [editorView, enabled]);
+}