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(code): list code completions as the text editor's / palette does
Elian Doran640e50c215f6
diff --git a/apps/client/src/widgets/type_widgets/code/Code.tsx b/apps/client/src/widgets/type_widgets/code/Code.tsxindex a60e863a50..91ad219837 100644--- a/apps/client/src/widgets/type_widgets/code/Code.tsx+++ b/apps/client/src/widgets/type_widgets/code/Code.tsx@@ -16,7 +16,7 @@ import { CODE_THEME_DEFAULT_PREFIX as DEFAULT_PREFIX } from "../constants";import { TypeWidgetProps } from "../type_widget";import ApiLog from "./ApiLog";import CodeMirror, { CodeMirrorProps } from "./CodeMirror";-import { useSnippetSlashCommands } from "./snippets";+import { useCodeSnippets } from "./snippets";export interface EditableCodeProps extends TypeWidgetProps {// if true, the update will be debounced to prevent excessive updates. Especially useful if the editor is linked to a live preview.@@ -97,10 +97,8 @@ 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 = useCallback((view: VanillaCodeMirror | null) => {editorRef.current = view;- setEditorView(view);if (typeof externalEditorRef === "function") externalEditorRef(view);else if (externalEditorRef) externalEditorRef.current = view;}, [externalEditorRef]);@@ -148,16 +146,16 @@ export function EditableCode({ note, ntxId, noteContext, debounceUpdate, parentCuseKeyboardShortcuts("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. On- // script notes the snippet source co-exists with the TypeScript language service's source via- // the editor's shared completion-source registry.- useSnippetSlashCommands(- editorView,+ // Code snippets (#snippet notes of the note's MIME type or plain text) for the editor's `/`+ // list. A Markdown note's editor lists them in its own `/` list.+ const snippetsRef = useCodeSnippets((candidate) => candidate.type === "code" && (candidate.mime === note.mime || candidate.mime === "text/plain"),note.mime,- !note.isMarkdown(),- note.noteId+ !note.isMarkdown()+ );+ const getSnippets = useCallback(+ () => snippetsRef.current.filter((snippet) => snippet.noteId !== note.noteId),+ [ snippetsRef, note.noteId ]);return (@@ -167,6 +165,7 @@ export function EditableCode({ note, ntxId, noteContext, debounceUpdate, parentCeditorRef={combinedEditorRef} containerRef={containerRef}mime={mime ?? "text/plain"}customRequestHandler={customRequestHandler != null}+ getSnippets={getSnippets}className="note-detail-code-editor"placeholder={placeholder ?? t("editable_code.placeholder")}vimKeybindings={vimKeymapEnabled}@@ -209,7 +208,7 @@ export function CodeEditor({ ntxId, containerRef: externalContainerRef, editorRe// React to theme changes.useEffect(() => {- if (codeEditorRef.current && effectiveTheme.startsWith(DEFAULT_PREFIX)) {+ if (codeEditorRef.current && effectiveTheme?.startsWith(DEFAULT_PREFIX)) {const theme = getThemeById(effectiveTheme.substring(DEFAULT_PREFIX.length));if (theme) {codeEditorRef.current.setTheme(theme);diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsxindex df5e313a62..b21b1bcb63 100644--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx@@ -25,7 +25,8 @@ const renderCodePreview = vi.hoisted(() => vi.fn(async (content: string, _mime:return pre;}));vi.mock("../../../services/content_renderer", () => ({ renderCodePreview }));-vi.mock("../../../services/i18n", () => ({+vi.mock("../../../services/i18n", async (importOriginal) => ({+ ...(await importOriginal<object>()),t: (key: string, values?: Record<string, unknown>) =>values ? `${key} ${Object.values(values).join(" ")}` : key}));diff --git a/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx b/apps/client/src/widgets/type_widgets/code/CodeMirror.tsxindex 740b41237f..0025963f5d 100644--- a/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx+++ b/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx@@ -1,7 +1,10 @@-import { useEffect, useRef } from "preact/hooks";import { EditorConfig, default as VanillaCodeMirror } from "@triliumnext/codemirror";-import { useSyncedRef } from "../../react/hooks";import { Ref } from "preact";+import { useEffect, useRef } from "preact/hooks";++import { useSyncedRef } from "../../react/hooks";+import { codeCompletions } from "./code_completions";+import type { CodeSnippet } from "./snippets";export interface CodeMirrorProps extends Omit<EditorConfig, "parent"> {content?: string;@@ -17,11 +20,15 @@ export interface CodeMirrorProps extends Omit<EditorConfig, "parent"> {customRequestHandler?: boolean;/** Whether the script is a bulk action's, which runs with the processed note as `note`. */bulkActionNote?: boolean;+ /** The snippets the completion list offers after a `/`, read each time the list opens. */+ getSnippets?: () => CodeSnippet[];}-export default function CodeMirror({ className, content, mime, editorRef: externalEditorRef, containerRef: externalContainerRef, onInitialized, lineWrapping, customRequestHandler, bulkActionNote, allowKeyboardSuggestions, ...extraOpts }: CodeMirrorProps) {+export default function CodeMirror({ className, content, mime, editorRef: externalEditorRef, containerRef: externalContainerRef, onInitialized, lineWrapping, customRequestHandler, bulkActionNote, allowKeyboardSuggestions, getSnippets, ...extraOpts }: CodeMirrorProps) {const parentRef = useSyncedRef(externalContainerRef);const codeEditorRef = useRef<VanillaCodeMirror | undefined>(undefined);+ const getSnippetsRef = useRef(getSnippets);+ getSnippetsRef.current = getSnippets;// Create CodeMirror instance.useEffect(() => {@@ -33,6 +40,7 @@ export default function CodeMirror({ className, content, mime, editorRef: extern...extraOpts});codeEditorRef.current = codeEditor;+ codeEditor.setNamedExtension("codeCompletions", codeCompletions(codeEditor, () => getSnippetsRef.current?.() ?? []));if (typeof externalEditorRef === "function") externalEditorRef(codeEditor);else if (externalEditorRef) externalEditorRef.current = codeEditor;onInitialized?.();diff --git a/apps/client/src/widgets/type_widgets/code/code_completions.spec.tsx b/apps/client/src/widgets/type_widgets/code/code_completions.spec.tsxnew file mode 100644index 0000000000..1b48a83841--- /dev/null+++ b/apps/client/src/widgets/type_widgets/code/code_completions.spec.tsx@@ -0,0 +1,101 @@+import { EditorSelection } from "@codemirror/state";+import VanillaCodeMirror, { type TypeCompletionEntry } from "@triliumnext/codemirror";+import { afterEach, describe, expect, it, vi } from "vitest";++import { codeCompletionAt, codeCompletions } from "./code_completions";+import type { CodeSnippet } from "./snippets";++describe("codeCompletionAt", () => {+ it("matches a /command where there are snippets, and an identifier or a member where there are type completions", () => {+ const both = { snippets: true, types: true };+ expect(codeCompletionAt("x = /hea", false, both)).toEqual({ kind: "snippets", from: 4, query: "hea", explicit: false });+ expect(codeCompletionAt("a/b", false, both)).toMatchObject({ kind: "types", from: 2, query: "b" });+ expect(codeCompletionAt("/hea", false, { snippets: false, types: false })).toBe(null);++ expect(codeCompletionAt("const x = api.get", false, both)).toMatchObject({ kind: "types", from: 14, query: "get" });+ expect(codeCompletionAt("api.", false, both)).toMatchObject({ kind: "types", from: 4, query: "" });+ expect(codeCompletionAt("x = ", false, both)).toBe(null);+ expect(codeCompletionAt("x = ", true, both)).toMatchObject({ kind: "types", from: 4, query: "", explicit: true });+ expect(codeCompletionAt("x = 12", false, both)).toBe(null);+ expect(codeCompletionAt("api.get", false, { snippets: true, types: false })).toBe(null);+ });+});++describe("codeCompletions", () => {+ let editor: VanillaCodeMirror | undefined;++ afterEach(() => {+ editor?.destroy();+ editor = undefined;+ });++ it("lists the type completions with the icon of their kind, asking the language service once per place", async () => {+ const completions: TypeCompletionEntry[] = [+ { label: "getNote", type: "method" },+ { label: "getNotes", type: "method" },+ { label: "log", type: "function" },+ { label: "dayjs" }+ ];+ const view = build([]);+ vi.spyOn(view, "hasTypeCompletions").mockReturnValue(true);+ const lookUp = vi.spyOn(view, "getTypeCompletions").mockResolvedValue(completions);++ type("api.");+ await vi.waitFor(() => expect(rows()).toEqual([ "getNote", "getNotes", "log", "dayjs" ]));+ expect(document.querySelector(".slash-command-menu [role=option] .bx-math")).not.toBe(null);+ expect(document.querySelector(".slash-command-menu [role=option] .bx-code-alt")).not.toBe(null);++ type("getN");+ await vi.waitFor(() => expect(rows()).toEqual([ "getNote", "getNotes" ]));+ expect(lookUp).toHaveBeenCalledOnce();++ await press("ArrowDown");+ await press("Enter");+ await vi.waitFor(() => expect(view.getText()).toBe("api.getNotes"));+ });++ it("lists the snippets after a /, and puts the content of the one picked in place of the command", async () => {+ const view = build([ { noteId: "s1", title: "Header", description: "Page header", content: "// header\n" } ]);++ type("x;\n/hea");+ await vi.waitFor(() => expect(rows()).toEqual([ "HeaderPage header" ]));+ await press("Enter");+ await vi.waitFor(() => expect(view.getText()).toBe("x;\n// header\n"));+ });++ it("offers nothing in a read-only editor", async () => {+ const view = build([ { noteId: "s1", title: "Header", content: "// header\n" } ], true);+ vi.spyOn(view, "hasTypeCompletions").mockReturnValue(true);+ const lookUp = vi.spyOn(view, "getTypeCompletions");++ view.dispatch({ changes: { from: 0, insert: "/hea api." }, selection: EditorSelection.cursor(9) });+ await press(" ", { ctrlKey: true });+ expect(lookUp).not.toHaveBeenCalled();+ });++ function build(snippets: CodeSnippet[], readOnly = false) {+ const parent = document.createElement("div");+ document.body.append(parent);+ const view = new VanillaCodeMirror({ parent, readOnly });+ view.setNamedExtension("codeCompletions", codeCompletions(view, () => snippets));+ view.focus();+ editor = view;+ return view;+ }++ function type(inserted: string) {+ if (!editor) throw new Error("expected an editor");+ const at = editor.state.selection.main.head;+ editor.dispatch({ changes: { from: at, insert: inserted }, selection: EditorSelection.cursor(at + inserted.length) });+ }++ /** Presses a key, and lets the list render what it did before the next one. */+ async function press(key: string, init: KeyboardEventInit = {}) {+ editor?.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...init }));+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+});++function rows() {+ return [ ...document.querySelectorAll(".slash-command-menu [role=option]") ].map((row) => row.textContent ?? "");+}diff --git a/apps/client/src/widgets/type_widgets/code/code_completions.tsx b/apps/client/src/widgets/type_widgets/code/code_completions.tsxnew file mode 100644index 0000000000..6d39f4e8cf--- /dev/null+++ b/apps/client/src/widgets/type_widgets/code/code_completions.tsx@@ -0,0 +1,141 @@+import type VanillaCodeMirror from "@triliumnext/codemirror";+import type { TypeCompletionEntry } from "@triliumnext/codemirror";+import { hostedCompletion, type HostedCompletionInsert, type HostedCompletionState } from "@triliumnext/codemirror/src/extensions/hosted_completion";++import { type CommandEntry, CommandMentionList, createHostedList, filterCommandEntries } from "../../react/NoteAutocomplete";+import { type CodeSnippet, SLASH_COMMAND_REGEX, snippetCommand } from "./snippets";++/** What a code editor completes before the caret: a snippet after `/`, or a TypeScript symbol. */+export interface CodeCompletionMatch {+ kind: "snippets" | "types";+ from: number;+ /** What the list filters by: the text after the `/`, or the identifier typed so far. */+ query: string;+ /** Asked for with Ctrl-Space. */+ explicit: boolean;+}++/** An entry of the code completion list, and what picking it puts in place of the match. */+export interface CodeCompletionEntry extends CommandEntry {+ apply: HostedCompletionInsert;+}++/**+ * Completes code in the text editor's command list, as its `/` palette does: the code snippets+ * after a `/`, and in a script note the completions of the TypeScript language service. Nothing is+ * offered in a read-only editor.+ */+export function codeCompletions(editor: VanillaCodeMirror, getSnippets: () => CodeSnippet[]) {+ return hostedCompletion<CodeCompletionMatch>({+ match: (before, explicit) => (editor.state.readOnly ? null : codeCompletionAt(before, explicit, {+ snippets: getSnippets().length > 0,+ types: editor.hasTypeCompletions()+ })),+ list: () => createCodeCompletionList(editor, getSnippets)+ });+}++/**+ * The `/command` typed at the start of a line or after whitespace where there are snippets, or+ * where there are type completions, the identifier typed before the caret. An identifier opens the+ * list from its first character, a `.` before the caret opens it on the members, and Ctrl-Space+ * opens it anywhere.+ */+export function codeCompletionAt(before: string, explicit: boolean, available: { snippets: boolean; types: boolean }): CodeCompletionMatch | null {+ const command = available.snippets ? COMMAND_TYPED.exec(before) : null;+ if (command) {+ return { kind: "snippets", from: command.index, query: command[0].slice(1), explicit };+ }+ if (!available.types) {+ return null;+ }++ const word = IDENTIFIER_TYPED.exec(before)?.[0] ?? "";+ if (!word && !explicit && !before.endsWith(".")) {+ return null;+ }+ return { kind: "types", from: before.length - word.length, query: word, explicit };+}++const COMMAND_TYPED = new RegExp(`${SLASH_COMMAND_REGEX.source}$`);+/** An identifier, which a digit cannot start. */+const IDENTIFIER_TYPED = /[A-Za-z_$][\w$]*$/;+/** As many rows as CodeMirror's own completion renders, since a script's globals run to hundreds. */+const MAX_ENTRIES = 100;++/**+ * The completions of the TypeScript language service as rows: each symbol with the icon of its kind,+ * picked as its name.+ */+export function typeCompletionEntries(completions: TypeCompletionEntry[]): CodeCompletionEntry[] {+ return completions.map(({ label, type }, index) => ({+ id: `${index}:${label}`,+ title: label,+ icon: `bx ${(type && TYPE_ICONS[type]) ?? "bx-code-alt"}`,+ apply: label+ }));+}++/** The icon of each kind of symbol CodeMirror names (see `DEFAULT_CODEMIRROR_TYPE_ICONS`). */+const TYPE_ICONS: Record<string, string> = {+ class: "bx-cube",+ constant: "bx-lock-alt",+ enum: "bx-list-ol",+ function: "bx-math",+ interface: "bx-shape-square",+ keyword: "bx-key",+ method: "bx-math",+ namespace: "bx-package",+ property: "bx-wrench",+ text: "bx-text",+ type: "bx-category",+ variable: "bx-box"+};++/**+ * The list of {@link codeCompletions}. The language service is asked once per place the list opens+ * at, and the entries it gives are filtered as the identifier is typed further.+ */+function createCodeCompletionList(editor: VanillaCodeMirror, getSnippets: () => CodeSnippet[]) {+ let cached: { key: string; entries: Promise<CodeCompletionEntry[]> } | undefined;++ const list = createHostedList<HostedCompletionState<CodeCompletionMatch>>((state, props) => {+ const { match } = state;+ const key = `${match.kind}:${match.from}`;+ if (cached?.key !== key) {+ cached = { key, entries: entriesFor(match) };+ }+ const { entries } = cached;++ return (+ <CommandMentionList<CodeCompletionEntry>+ key={key}+ {...props}+ query={match.query}+ source={async (query) => filterCommandEntries(await entries, query).slice(0, MAX_ENTRIES)}+ className="slash-command-menu"+ onPick={(entry) => state.commit(entry.apply)}+ />+ );+ });++ async function entriesFor(match: CodeCompletionMatch): Promise<CodeCompletionEntry[]> {+ if (match.kind === "snippets") {+ return getSnippets().map(snippetCommand);+ }+ return typeCompletionEntries(await editor.getTypeCompletions(match.explicit) ?? []);+ }++ return {+ show: list.show,+ hide() {+ cached = undefined;+ list.hide();+ },+ handleKeyDown: list.handleKeyDown,+ get element() {+ return list.element;+ },+ destroy: list.destroy+ };+}diff --git a/apps/client/src/widgets/type_widgets/code/snippets.spec.ts b/apps/client/src/widgets/type_widgets/code/snippets.spec.tsindex 78d6434d24..aea1d09b6a 100644--- a/apps/client/src/widgets/type_widgets/code/snippets.spec.ts+++ b/apps/client/src/widgets/type_widgets/code/snippets.spec.ts@@ -1,5 +1,3 @@-import type { Completion } from "@codemirror/autocomplete";-import type { EditorView } from "@codemirror/view";import { beforeEach, describe, expect, it, vi } from "vitest";import type FNote from "../../../entities/fnote";@@ -10,7 +8,7 @@ vi.mock("../../../services/search.js", () => ({}));import search from "../../../services/search.js";-import { buildSnippetCompletions, getCodeSnippets, isCodeSnippetChange } from "./snippets.js";+import { getCodeSnippets, isCodeSnippetChange, snippetCommand } from "./snippets.js";const logErrorMock = vi.fn();@@ -49,24 +47,24 @@ function makeLoadResults(opts: {} as unknown as LoadResults;}-describe("buildSnippetCompletions", () => {- it("formats labels with/without a description and inserts content on apply", () => {- const [withDesc, withoutDesc] = buildSnippetCompletions([- { noteId: "a", title: "Header", description: "Page header", content: "# Header\n" },- { noteId: "b", title: "Footer", content: "the footer" }- ]);+describe("snippetCommand", () => {+ it("lists a snippet by title and description, and inserts its content for the command", () => {+ const command = snippetCommand({+ noteId: "b", title: "Footer", description: "Page footer", content: "the footer"+ });- expect(withDesc?.label).toBe("/snippet:Header - Page header");- expect(withoutDesc?.label).toBe("/snippet:Footer");+ expect(command).toMatchObject({+ id: "snippet:Footer",+ title: "Footer",+ description: "Page footer",+ aliases: [ "snippet:Footer", "snippet", "template" ]+ });// Applying replaces the typed [from, to] token with the content, caret at its end.- const apply = withoutDesc?.apply;- expect(typeof apply).toBe("function");- if (typeof apply !== "function") return;-const dispatched: unknown[] = [];- const view = { dispatch: (tx: unknown) => dispatched.push(tx) } as unknown as EditorView;- apply(view, {} as Completion, 3, 11);+ const view = { dispatch: (tx: unknown) => dispatched.push(tx) } as unknown as+ Parameters<typeof command.apply>[0];+ command.apply(view, 3, 11);expect(dispatched).toEqual([{changes: { from: 3, to: 11, insert: "the footer" },diff --git a/apps/client/src/widgets/type_widgets/code/snippets.ts b/apps/client/src/widgets/type_widgets/code/snippets.tsindex 64a2317663..3241fea629 100644--- a/apps/client/src/widgets/type_widgets/code/snippets.ts+++ b/apps/client/src/widgets/type_widgets/code/snippets.ts@@ -1,12 +1,13 @@-import { type Completion, type CompletionContext, type CompletionSource } from "@codemirror/autocomplete";-import type { EditorView } from "@codemirror/view";-import type VanillaCodeMirror from "@triliumnext/codemirror";+import type {+ HostedCompletionApply+} from "@triliumnext/codemirror/src/extensions/hosted_completion";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";+import type { CommandEntry } from "../../react/NoteAutocomplete";/** Matches a `/command` token at the start of a line or after whitespace. Shared by every editor. */export const SLASH_COMMAND_REGEX = /(?:^|(?<=\s))\/[\w:-]*/;@@ -63,23 +64,29 @@ export function isCodeSnippetChange(loadResults: LoadResults, knownNoteIds: Set<}/**- * 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.+ * A snippet as an entry of a `/` list, found by its title or by `snippet:<title>`. Picking it puts+ * the snippet's content in place of the typed `/command` 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) {+export function snippetCommand(snippet: CodeSnippet): SnippetCommand {+ const name = `snippet:${snippet.title}`;++ return {+ id: name,+ title: snippet.title,+ description: snippet.description,+ aliases: [ name, "snippet", "template" ],+ icon: "bx bx-code-curly",+ apply(view, from, to) {view.dispatch({changes: { from, to, insert: snippet.content },selection: { anchor: from + snippet.content.length }});}- }));+ };}+export type SnippetCommand = CommandEntry & { apply: HostedCompletionApply };+/*** 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@@ -120,48 +127,3 @@ export function useCodeSnippets(matches: (note: FNote) => boolean, reloadKey: streturn 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, currentNoteId: string) {- const snippetsRef = useCodeSnippets(matches, reloadKey, enabled);- // The note being edited, kept in a ref so the once-registered completion source always excludes- // the current snippet from its own menu — even when the editor is reused for a different note.- const currentNoteIdRef = useRef(currentNoteId);- useEffect(() => { currentNoteIdRef.current = currentNoteId; });-- useEffect(() => {- if (!editorView) return;- if (!enabled) {- editorView.setCompletionSource("snippets", null);- return;- }-- // Contribute the snippet `/snippet:` source to the editor's shared- // autocompletion. Registering a source (rather than a whole- // autocompletion) lets it co-exist with other sources — e.g. the- // TypeScript language service on backend/frontend script notes.- const source: CompletionSource = (context: CompletionContext) => {- const match = context.matchBefore(SLASH_COMMAND_REGEX);- if (!match) return null;- const options = buildSnippetCompletions(- snippetsRef.current.filter((snippet) => snippet.noteId !== currentNoteIdRef.current)- );- // No matching snippets (e.g. none for this MIME, or only the current note) → no source,- // so an empty completion popup never appears when the user types "/".- return options.length ? { from: match.from, options } : null;- };-- // `setCompletionSource` types its argument via the codemirror package's own copy of- // @codemirror/autocomplete. Under TypeScript project references that is a distinct type- // identity from the client's copy, even though it is the same package at runtime, so bridge- // the two here. (CodeMirror requires a single physical @codemirror/state, which holds.)- type CmCompletionSource = Parameters<VanillaCodeMirror["setCompletionSource"]>[1];- editorView.setCompletionSource("snippets", source as unknown as CmCompletionSource);- return () => editorView.setCompletionSource("snippets", null);- }, [editorView, enabled]);-}\ No newline at end of filediff --git a/apps/client/src/widgets/type_widgets/markdown/completions.tsx b/apps/client/src/widgets/type_widgets/markdown/completions.tsxindex d4ab2efcec..eba3d7987e 100644--- a/apps/client/src/widgets/type_widgets/markdown/completions.tsx+++ b/apps/client/src/widgets/type_widgets/markdown/completions.tsx@@ -26,7 +26,7 @@ import { t } from "../../../services/i18n";import mime_types from "../../../services/mime_types";import { getTaskStateDefinitions } from "../../../services/task_states";import { type CommandEntry, CommandMentionList, createHostedList, filterCommandEntries, NoteMentionList } from "../../react/NoteAutocomplete";-import { type CodeSnippet, SLASH_COMMAND_REGEX, useCodeSnippets } from "../code/snippets";+import { type CodeSnippet, SLASH_COMMAND_REGEX, snippetCommand, useCodeSnippets } from "../code/snippets";import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams";import type { TypeWidgetProps } from "../type_widget";import { uploadImageAndInsert } from "./editor_utils";@@ -361,17 +361,7 @@ export function buildSlashCommands({ parentComponent, getNote, editorView, taskSview.dispatch({ changes: { from, to, insert } });});}),- ...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 }- });- }))+ ...snippets.map(snippetCommand)];}diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.jsonindex 1705976f30..ce918fc600 100644--- a/apps/server/src/assets/help/help_content.json+++ b/apps/server/src/assets/help/help_content.json@@ -205,7 +205,7 @@"_help_KC1HB96bqqHX": "<p>A template in Trilium serves as a predefined structure for other notes, referred to as instance notes. Assigning a template to a note brings three main effects:</p><ol><li><strong>Attribute Inheritance</strong>: All attributes from the template note are <a href=\"#root/_help_bwZpz2ajCEwO\">inherited</a> by the instance notes. Even attributes with <code>#isInheritable=false</code> are inherited by the instance notes, although only inheritable attributes are further inherited by the children of the instance notes.</li><li><strong>Content Duplication</strong>: The content of the template note is copied to the instance note, provided the instance note is empty at the time of template assignment.</li><li><strong>Child Note Duplication</strong>: All child notes of the template are deep-duplicated to the instance note.</li></ol><h2>Example</h2><p>A typical example would be a \"Book\" template note, which might include:</p><ul><li><strong>Promoted Attributes</strong>: Such as publication year, author, etc. (see <a href=\"#root/_help_OFXdgB2nNk1F\">promoted attributes</a>).</li><li><strong>Outline</strong>: An outline for a book review, including sections like themes, conclusion, etc.</li><li><strong>Child Notes</strong>: Additional notes for highlights, summary, etc.</li></ul><p><img src=\"{{helpAssets}}/User%20Guide/Advanced%20Usage/Templates_template.png\" alt=\"Template Example\"></p><h2>Instance Note</h2><p>An instance note is a note related to a template note. This relationship means the instance note's content is initialized from the template, and all attributes from the template are inherited.</p><p>To create an instance note through the UI:</p><p><img src=\"{{helpAssets}}/User%20Guide/Advanced%20Usage/Templates_template-create-instance-note.png\" alt=\"show child note templates\"></p><p>For the template to appear in the menu, the template note must have the <code>#template</code> label. Do not confuse this with the <code>~template</code> relation, which links the instance note to the template note. If you use <a href=\"#root/_help_9sRHySam5fXb\">workspaces</a>, you can also mark templates with <code>#workspaceTemplate</code> to display them only in the workspace.</p><p>Templates can also be added or changed after note creation by creating a <code>~template</code> relation pointing to the desired template note. </p><p>To specify a template for child notes, you can use a <code>~child:template</code> relation pointing to the appropriate template note. There is no limit to the depth of the hierarchy — you can use <code>~child:child:template</code>, <code>~child:child:child:template</code>, and so on.</p><aside class=\"admonition important\"><p>Changing the template hierarchy after the parent note is created will not retroactively apply to newly created child notes.<br>For example, if you initially use <code>~child:template</code> and later switch to <code>~child:child:template</code>, it will not automatically apply the new template to the grandchild notes. Only the structure present at the time of note creation is considered.</p></aside><h2>Default parent for new notes</h2><p>A template can gather the notes created from it in one place, instead of having them land wherever they happen to be created. To do so, add a <code>~template:newNoteDefaultParent</code> relation to the template note, pointing at the note that should hold the instances, for example a <em>Person</em> template pointing to a <em>People</em> note. The relation can also be set by clicking the template badge next to the note title and selecting <em>Template properties...</em>, then picking a note under <em>Default location of created notes</em>.</p><p>Adding the relation several times places the new note in every target, as <a class=\"reference-link\" href=\"#root/_help_IakOLONlIfGI\">Cloning Notes</a>. The relation can also be inherited (e.g. from a folder holding several templates), in which case a relation owned by the template itself replaces the inherited one. The default parent is only inherited from the template's ancestors in the tree: a template created from another template does not adopt that template's default parent.</p><p>The default parent is used whenever a note is created from the template through the <em>Choose note type</em> dialog:</p><ul><li>Via <code>@</code>-completion in a <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a> note</li><li>Via the <em>Create note</em> or <em>Create child note</em> options of the note search (new tab or <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a>), but only if the default/empty location is set.</li></ul><p>Creating an instance note from the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a> context menu (<em>Insert child note</em>, <em>Insert note after</em>) still creates it at the chosen place.</p><p>Unlike the <a class=\"reference-link\" href=\"#root/_help_S0Fos78ZfcY7\">Note Inbox</a>, which holds quickly captured notes until they are sorted, the default parent is meant as the instances' permanent location.</p><h2>Regarding note types</h2><p>By default, newly created notes are <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a> notes. If a parent note defines a <code>child:template</code> pointing to a template of a different type (e.g. a Code note), the behavior depends on how the new note is created:</p><ul><li>If no note type is explicitly chosen (e.g. the + button in the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>), the template is applied and the new note takes the type and content of the template.</li><li>If a note type is explicitly selected (e.g. <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a> → <em>Insert note after</em> / <em>Insert child note</em>):<ul><li>If the selected type matches the template's type, the template is applied.</li><li>If the selected type differs, the template is disregarded entirely — the new note is an empty note of the selected type.</li></ul></li></ul><p>Selecting a specific template from the creation menu always takes precedence over <code>child:template</code>.</p><h2>Default title for new notes</h2><p>A template can also give its instances a default title, using the <code>#template:titleTemplate</code> label. To set it without editing the label by hand, click the template badge next to the note title and select <em>Template properties...</em>, which checks the expressions as you type and previews the resulting title. See <a class=\"reference-link\" href=\"#root/_help_47ZrP6FNuoG8\">Default Note Title</a> for details.</p><h2>Additional Notes</h2><p>From a visual perspective, templates can define <code>#iconClass</code> and <code>#cssClass</code> attributes, allowing all instance notes (e.g., books) to display a specific icon and CSS style.</p><p>Explore the concept further in the <a class=\"reference-link\" href=\"#root/_help_6tZeKvSHEUiB\">Demo Notes</a>, including examples like the <a class=\"reference-link\" href=\"#root/_help_iRwzGnHPzonm\">Relation Map</a>, <a class=\"reference-link\" href=\"#root/_help_xYjQUYhpbUEW\">Task Manager</a>, and <a class=\"reference-link\" href=\"#root/_help_l0tKav7yLHGF\">Day Notes</a>.</p><p>Additionally, see <a class=\"reference-link\" href=\"#root/_help_47ZrP6FNuoG8\">Default Note Title</a> for creating title templates. A <code>#titleTemplate</code> on a template note is passed on to its instances like any other label, so it names the children of each instance rather than the instances themselves; to name the instances, use <code>#template:titleTemplate</code>.</p>","_help_B2ORr7OVEZtc": "<p>Snippets let you define reusable pieces of text, Markdown or code that can be quickly inserted into your notes.</p>","_help_VQjhl61rlWh9": "<p>Markdown Snippets are closely related to <a class=\"reference-link\" href=\"#root/_help_KC1HB96bqqHX\">Templates</a>, but instead of defining the content of an entire note, a snippet is a reusable piece of Markdown text that can easily be inserted into a <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> note.</p><h2>Creating a Markdown snippet</h2><p>In the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>: </p><ol><li>Right-click the note where you want to place the snippet.</li><li>Select <em>Insert child note</em>.</li><li>Select <em>More</em> → <em>Markdown snippet</em>.</li></ol><p>Then simply type the desired content into the note.</p><p>The note's title becomes the title of the snippet. Optionally, you can add a description in the <a class=\"reference-link\" href=\"#root/_help_OFXdgB2nNk1F\">Promoted Attributes</a> section.</p><h2>Inserting a snippet</h2><p>To insert a snippet, type <code>/snippet</code> and select its title from the dropdown.</p><p><a class=\"reference-link\" href=\"#root/_help_IEgsWp5hHH35\">Code Snippets</a> with their language mode set to \"Plain text\" are also listed here.</p><h2>Limitations</h2><ul><li>Unlike <a class=\"reference-link\" href=\"#root/_help_KC1HB96bqqHX\">Templates</a>, snippets cannot be limited to a particular <a href=\"#root/_help_9sRHySam5fXb\">workspace</a>.</li></ul>",- "_help_IEgsWp5hHH35": "<p>Code Snippets are closely related to <a class=\"reference-link\" href=\"#root/_help_KC1HB96bqqHX\">Templates</a>, but instead of defining the content of an entire note, a snippet is a reusable piece of code that can easily be inserted into a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note.</p><h2>Creating a Code snippet</h2><p>In the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>: </p><ol><li>Right-click the note where you want to place the snippet.</li><li>Select <em>Insert child note</em>.</li><li>Select <em>More</em> → <em>Code snippet</em>.</li></ol><p>Then simply type the desired code into the note and set the correct language mode.</p><p>The note's title becomes the title of the snippet. Optionally, you can add a description in the <a class=\"reference-link\" href=\"#root/_help_OFXdgB2nNk1F\">Promoted Attributes</a> section.</p><h2>Inserting a snippet</h2><p>To insert a snippet, type <code>/snippet</code> and select its title from the dropdown.</p><aside class=\"admonition important\"><p>Only code snippets whose language mode matches the current code note are listed. For example, a CSS code note shows only CSS snippets, not JavaScript ones. The exception is snippets set to \"Plain text\", which are available in <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> notes and any code note regardless of its language mode.</p></aside><h2>Limitations</h2><ul><li>Unlike <a class=\"reference-link\" href=\"#root/_help_KC1HB96bqqHX\">Templates</a>, snippets cannot be limited to a particular <a href=\"#root/_help_9sRHySam5fXb\">workspace</a>.</li></ul>",+ "_help_IEgsWp5hHH35": "<p>Code Snippets are closely related to <a class=\"reference-link\" href=\"#root/_help_KC1HB96bqqHX\">Templates</a>, but instead of defining the content of an entire note, a snippet is a reusable piece of code that can easily be inserted into a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note.</p><h2>Creating a Code snippet</h2><p>In the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>: </p><ol><li>Right-click the note where you want to place the snippet.</li><li>Select <em>Insert child note</em>.</li><li>Select <em>More</em> → <em>Code snippet</em>.</li></ol><p>Then simply type the desired code into the note and set the correct language mode.</p><p>The note's title becomes the title of the snippet. Optionally, you can add a description in the <a class=\"reference-link\" href=\"#root/_help_OFXdgB2nNk1F\">Promoted Attributes</a> section.</p><h2>Inserting a snippet</h2><p>To insert a snippet, type <kbd>/</kbd> followed by the first letters of its title, then select it from the list. Typing <code>/snippet</code> lists every snippet available in the note.</p><aside class=\"admonition important\"><p>Only code snippets whose language mode matches the current code note are listed. For example, a CSS code note shows only CSS snippets, not JavaScript ones. The exception is snippets set to \"Plain text\", which are available in <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> notes and any code note regardless of its language mode.</p></aside><h2>Limitations</h2><ul><li>Unlike <a class=\"reference-link\" href=\"#root/_help_KC1HB96bqqHX\">Templates</a>, snippets cannot be limited to a particular <a href=\"#root/_help_9sRHySam5fXb\">workspace</a>.</li></ul>","_help_BCkXAVs63Ttv": "<p>Note map is a visualization of connections between notes. This provides an insight into a structure (\"web\") of notes.</p><p>There are two types of note map:</p><ul><li>Link Map, which shows relations between notes.</li><li>Note Map, which shows the hierarchical tree structure.</li></ul><h2>Accessing the note map</h2><p>The note map comes into multiple flavors:</p><ul><li>The note map is available in the <a class=\"reference-link\" href=\"#root/_help_KRlZFoIH0j6p\">Connections tab</a> in the <a class=\"reference-link\" href=\"#root/_help_RnaPdbciOfeq\">Right Sidebar</a>, in the <em>Note map</em> section.<ul><li>It can also be accessed by going to <a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a> → <em>Note map</em>, which will focus the sidebar at the right section.</li></ul></li><li>To display a full-screen note map, there is a <a href=\"#root/_help_bdUJEHsAPYQR\">dedicated note type</a> with the same name.</li><li>To view the global note map (of all the notes in the knowledge base), there is a dedicated <em>Note map</em> button in the <a class=\"reference-link\" href=\"#root/_help_xYmIYSP6wE3F\">Launch Bar</a>.</li></ul><h2>Terminology and structure</h2><ul><li>Each note is represented as a <em>node</em> in the graph, with the title displayed underneath.<ul><li>When the map is zoomed out, the title can still be viewed by hovering over the node.</li><li>The <a href=\"#root/_help_p9kXRFAkwN4o\">icon and color</a> of the note are respected.</li></ul></li><li>The root node is the reference point for which the relations and hierarchical structure are displayed.<ul><li>When accessing the note map through the <a class=\"reference-link\" href=\"#root/_help_RnaPdbciOfeq\">Right Sidebar</a>, the root node is the current note.</li><li>When using a dedicated <a class=\"reference-link\" href=\"#root/_help_bdUJEHsAPYQR\">Note Map</a> note, the root note can be either the parent note, the currently <a href=\"#root/_help_OR8WJ7Iz9K4U\">hoisted</a> note or a specific note. See the note type documentation for more information.</li></ul></li></ul><h2>Interaction</h2><ul><li>Nodes can be dragged around, but they will return to their original position once released.<ul><li>To have the notes remain in the same position as they were dragged, press the <em>Fix nodes</em> button. The position of the notes is not saved, so it will return to normal once you navigate to another note or restart the application.</li></ul></li><li>When hovering over a node, the adjacent relations and nodes are highlighted.</li><li>The distance between nodes can be adjusted via the slider in the bottom-left. Similarly, this value is not saved.</li><li>To zoom, use the mouse wheel, pinch on a touch screen, or press the <span class=\"tn-icon bx bx-plus-circle\"></span> and <span class=\"tn-icon bx bx-minus-circle\"></span> buttons in the bottom-right corner.<ul><li>To bring the whole map back into view, press the <span class=\"tn-icon bx bx-scan\"></span> <em>Fit to view</em> button next to them.</li><li>The zoom buttons are not shown on mobile, where pinching zooms instead. The <em>Fit to view</em> button is always shown.</li></ul></li><li><a class=\"reference-link\" href=\"#root/_help_MKmLg5x6xkor\">Archived Notes</a> are generally ignored by the note map in order to reduce clutter. There is one exception: if the root note is also archived, then all archived notes are displayed too.</li></ul><h2>Link Map</h2><img src=\"{{helpAssets}}/User%20Guide/Advanced%20Usage/Note%20Map%20(Link%20map%2C%20Tree%20map)_image.png\" width=\"1425\" height=\"1093\"><p>The link map is a visualization of links and <a class=\"reference-link\" href=\"#root/_help_Cq5X6iKQop6R\">Relations</a> incoming to and outgoing from a particular note.</p><p>The map indicates the following types of relations:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> between notes.</li><li><a class=\"reference-link\" href=\"#root/_help_Cq5X6iKQop6R\">Relations</a></li></ul><p>The link map will also show unlinked notes that are part of the hierarchy as a cloud of unconnected dots. On the <a class=\"reference-link\" href=\"#root/_help_RnaPdbciOfeq\">Right Sidebar</a> deliberately omits this in order to save some space, but they will be revealed once the map is maximized.</p><h2>Tree Map</h2><p>Shows hierarchical map of notes:</p><figure class=\"image\"><img style=\"aspect-ratio:1420/1490;\" src=\"{{helpAssets}}/User%20Guide/Advanced%20Usage/1_Note%20Map%20(Link%20map%2C%20Tree%20map)_image.png\" width=\"1420\" height=\"1490\"></figure><h2>See also</h2><ul><li>Apart from the note map feature which can be accessed from any note, it is also possible to create a dedicated note which will display the relations in full screen. See <a class=\"reference-link\" href=\"#root/_help_bdUJEHsAPYQR\">Note Map</a> for more information.</li><li><a class=\"reference-link\" href=\"#root/_help_iRwzGnHPzonm\">Relation Map</a> is a similar concept, with some differences:<ul><li>note map is automatically generated while relation map must be created manually</li><li>relation map is a type of note while a link map is just virtual visualization</li></ul></li></ul>","_help_R9pX4DGra2Vt": "<p>Trilium allows you to share selected notes as <strong>publicly accessible</strong> read-only documents. This feature is particularly useful for publishing content directly from your Trilium notes, making it accessible to others online.</p><figure class=\"image\"><img style=\"aspect-ratio:1144/660;\" src=\"{{helpAssets}}/User%20Guide/Advanced%20Usage/Sharing_image.png\" width=\"1144\" height=\"660\"></figure><h2>Features, interaction and limitations</h2><ul><li>Searching by note title.</li><li>Light and dark mode, following the visitor's system setting by default, also while the page is open. The visitor can pick <em>Light</em>, <em>Dark</em> or <em>System</em> with the buttons at the top of the navigation pane; the choice is remembered by the browser.</li><li>A layout centered on wide screens, with the navigation tree and the table of contents at either side of the content, and a mobile-friendly layout on narrow ones. There, the navigation tree slides in from the menu button in the header, and lists the headings of the current page below its entry (at the top of the pane, for a page the tree does not show).</li><li>Collapsible tree with the same note icons as the application. It keeps the sections the visitor expanded and its scroll position while they move between the pages of the site, and shows the current note.</li><li>Customizable logo.</li><li>Quick navigation buttons (previous and next note).</li><li>Notes that hide their children from the tree with <code>#subtreeHidden</code> (such as a <a class=\"reference-link\" href=\"#root/_help_CtBQqbwXDx1w\">Kanban Board</a>) show a badge counting them in place of listing them. The page of one of those children shows only that child below its parent, and the previous and next buttons skip them.</li><li>The subpages of a text or code note shown below its content as cards, as in the application. Each card shows the icon of the subpage and the start of its text (or its <code>#shareDescription</code>), or, for a subpage without text, links to its own first subpages. The cards can be hidden with <code>#hideChildrenOverview</code>.</li><li>Displaying the date of the last update of the note, written out in the application's language.</li><li>Marking the page with the application's language and its text direction, and the content of the note with its own <a href=\"#root/_help_veGu4faJErEM\">content language</a>, for screen readers and right-to-left text.</li></ul><h3>By note type</h3><figure class=\"table\"><table class=\"ck-table-resized\"><colgroup><col style=\"width:19.92%;\"><col style=\"width:41.66%;\"><col style=\"width:38.42%;\"></colgroup><thead><tr><th> </th><th>Supported features</th><th>Limitations</th></tr></thead><tbody><tr><th><a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a></th><td><ul><li>Table of contents.</li><li>A link next to each heading, shown while the pointer is over the heading. Clicking it shows the address of the section in the address bar of the browser and copies it, to share a link to the section.</li><li>Syntax highlight of code blocks, in the language selected for each block and in the colors of the VS Code light or dark theme, following the page's mode. For “Auto-detected” blocks, the language is guessed among the ones enabled in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em>; a language not enabled there is not highlighted.</li><li>Rendering for math equations.</li><li><a href=\"#root/_help_nBAXQFj20hS1\">Including notes</a> (only if the included notes are also shared).</li><li>Drawing canvases, shown as pictures at their own size.</li><li>Mermaid diagrams in code blocks, drawn in the page's light or dark mode and redrawn when the visitor switches it.</li></ul></td><td> </td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a></th><td><ul><li>Basic support (displaying the contents of the note in a monospace font).</li></ul></td><td><ul><li>No syntax highlight.</li></ul></td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a></th><td>Not supported.</td><td> </td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_iRwzGnHPzonm\">Relation Map</a></th><td>Not supported.</td><td> </td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_bdUJEHsAPYQR\">Note Map</a></th><td>Not supported.</td><td> </td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_HcABDtFCkbFN\">Render Note</a></th><td>Not supported.</td><td> </td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a></th><td><ul><li>The child notes are shown as cards, or as a list when the view type of the collection is <em>List</em>. Each shows its icon and the start of its text (or its <code>#shareDescription</code>), or, for a child note without text, links to its own first child notes.</li></ul></td><td><ul><li>The calendar, table, board, geo map, dashboard and presentation view types are shown as in the app, but read-only.</li></ul></td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a></th><td><ul><li>The diagram is drawn in the page's light or dark mode and redrawn when the visitor switches it. In browsers with JavaScript disabled, the image saved when the note was last edited is shown instead, and the source of the diagram can be expanded below it.</li><li>The diagram fills the page and can be zoomed with the <span class=\"tn-icon bx bx-minus-circle\"></span> and <span class=\"tn-icon bx bx-plus-circle\"></span> buttons in its bottom corner or with the mouse wheel, between 50% and 1000% of its fitted size, and on touch screens by pinching. Clicking the percentage between the buttons, or double-clicking the diagram, shows it whole again. The diagram can be panned by dragging it.</li></ul></td><td> </td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a></th><td><ul><li>The diagram is displayed as a vector image.</li></ul></td><td><ul><li>No further interaction supported.</li></ul></td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a></th><td>Not supported.</td><td> </td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_gBbsAeiuUxI5\">Mind Map</a></th><td>The diagram is displayed as a vector image.</td><td><ul><li>No further interaction supported.</li></ul></td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_81SGnPGMk7Xc\">Geo Map</a></th><td>Not supported.</td><td> </td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_W8vYD3Q1zjCR\">File</a></th><td>Basic interaction (downloading the file).</td><td><ul><li>No further interaction supported.</li></ul></td></tr></tbody></table></figure><p>While the sharing feature is powerful, it has some limitations:</p><ul><li><strong>Code Notes</strong>: No syntax highlighting.</li><li><strong>Static Note Tree</strong></li><li><strong>Protected Notes</strong>: Cannot be shared.</li><li><strong>Include Notes</strong>: Not supported.</li></ul><p>Some of these limitations may be addressed in future updates.</p><h2>Prerequisites</h2><p>To use the sharing feature, you must have a <a class=\"reference-link\" href=\"#root/_help_WOcw2SLH6tbX\">Server Installation</a> of Trilium. This is necessary because the notes will be hosted from the server.</p><h2>Sharing a note</h2><ol><li><p><strong>Enable Sharing</strong>: To share a note, toggle the <code>Shared</code> switch within the note's interface. Once sharing is enabled, an URL will appear, which you can click to access the shared note.</p><p><img src=\"{{helpAssets}}/User%20Guide/Advanced%20Usage/Sharing_share-single-note.png\" alt=\"Share Note\"></p></li><li><p><strong>Access the Shared Note</strong>: The link provided will open the note in your browser. If your server is not configured with a public IP, the URL will refer to <code>localhost (127.0.0.1)</code>.</p></li></ol><h2>Sharing a note subtree</h2><p>When you share a note, you actually share the entire subtree of notes beneath it. If the note has child notes, they will also be included in the shared content. For example, sharing the \"Formatting\" subtree will display a page with basic navigation for exploring all the notes within that subtree.</p><h2>Viewing and managing shared notes</h2><p>You can view a list of all shared notes by clicking on \"Show Shared Notes Subtree\" in the <a class=\"reference-link\" href=\"#root/_help_x3i7MxGccDuM\">Global menu</a>. This allows you to manage and navigate through all the notes you have made public.</p><h2>Security considerations</h2><ul><li>Shared notes are published on the open internet and can be accessed by anyone with the URL unless the notes are password-protected.</li><li>The URL's randomness does not provide security, so it is crucial not to share sensitive information through this feature.</li><li>Trilium takes precautions to protect your publicly shared instance from leaking information for non-shared notes, including opening a separate read-only connection to the <a class=\"reference-link\" href=\"#root/_help_wX4HbRucYSDD\">Database</a>. Depending on your threat model, it might make more sense to use <a class=\"reference-link\" href=\"#root/_help_ycBFjKrrwE9p\">Exporting static HTML for web publishing</a> and use battle-tested web servers such as Nginx or Apache to serve static content.</li></ul><h3>Password protection</h3><p>To protect shared notes with a username and password, you can use the <code>#shareCredentials</code> attribute. Add this label to the note with the format <code>#shareCredentials=\"username:password\"</code>. To protect an entire subtree, make sure the label is <a href=\"#root/_help_bwZpz2ajCEwO\">inheritable</a>.</p><h2>Advanced sharing options</h2><h3>Customizing the appearance of shared notes</h3><p>The default design should be a good starting point, but you can customize it using your own CSS:</p><ul><li><strong>Custom CSS</strong>: Link a CSS <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note to the shared page by adding a <code>~shareCss</code> relation to the note. If you want this style to apply to the entire subtree, make the label inheritable. You can hide the CSS code note from the tree navigation by adding the <code>#shareHiddenFromTree</code> label.</li><li><strong>Omitting Default CSS</strong>: For extensive styling changes, use the <code>#shareOmitDefaultCss</code> label to avoid conflicts with Trilium's <a href=\"#root/_help_Wy267RK4M69c\">default stylesheet</a>.</li></ul><h3>Adding JavaScript</h3><p>You can inject custom JavaScript into the shared note using the <code>~shareJs</code> relation. This allows you to access note attributes or traverse the note tree using the <code>fetchNote()</code> API, which retrieves note data based on its ID.</p><h3>Adding custom HTML</h3><p>You can inject custom HTML snippets into specific locations of the shared page using the <code>~shareHtml</code> relation. The HTML note should contain the raw HTML content you want to inject, and you can control where it appears by adding the <code>#shareHtmlLocation</code> label to the HTML snippet note itself.</p><p>The <code>#shareHtmlLocation</code> label accepts values in the format <code>location:position</code>:</p><ul><li><strong>Locations</strong>: <code>head</code>, <code>body</code>, <code>content</code></li><li><strong>Positions</strong>: <code>start</code>, <code>end</code></li></ul><p>For example:</p><ul><li><code>#shareHtmlLocation=head:start</code> - Injects HTML at the beginning of the <code><head></code> section</li><li><code>#shareHtmlLocation=head:end</code> - Injects HTML at the end of the <code><head></code> section (default)</li><li><code>#shareHtmlLocation=body:start</code> - Injects HTML at the beginning of the <code><body></code> section</li><li><code>#shareHtmlLocation=content:start</code> - Injects HTML at the beginning of the content area</li><li><code>#shareHtmlLocation=content:end</code> - Injects HTML at the end of the content area</li></ul><p>If no location is specified, the HTML will be injected at <code>content:end</code> by default.</p><p>Example:</p><pre><code class=\"language-text-javascript\">const currentNote = await fetchNote();\nconst parentNote = await fetchNote(currentNote.parentNoteIds[0]);\n\nfor (const attr of parentNote.attributes) {\n console.log(attr.type, attr.name, attr.value);\n}</code></pre><h3>Custom share templates</h3><p>To completely redesign the share, it is possible to create or use an existing <a href=\"#root/_help_Ad7Ku5gOHrDU\">custom share template</a>.</p><h3>Creating human-readable URL aliases</h3><p>Shared notes typically have URLs like <code>http://domain.tld/share/knvU8aJy4dJ7</code>, where the last part is the note's ID. You can make these URLs more user-friendly by adding the <code>#shareAlias</code> label to individual notes (e.g., <code>#shareAlias=highlighting</code>). This will change the URL to <code>http://domain.tld/share/highlighting</code>. The URL with the note's ID keeps working and redirects to the alias.</p><p><strong>Important</strong>:</p><ol><li>Ensure that aliases are unique.</li><li>Using slashes (<code>/</code>) within aliases to create subpaths is not supported.</li></ol><aside class=\"admonition tip\"><ul><li>To easily identify pages that don't have a share alias, run a <a class=\"reference-link\" href=\"#root/_help_eIg8jdvaoNNd\">Search</a> with <code>#!shareAlias</code>.</li><li>To be able to enter the share alias faster, consider using <a class=\"reference-link\" href=\"#root/_help_OFXdgB2nNk1F\">Promoted Attributes</a> (for example <code>#label:shareAlias(inheritable)=\"promoted,alias=Slug,single,text\"</code>).</li></ul></aside><h3>Setting a custom favicon</h3><p>To customize the favicon for your shared pages, create a relation <code>~shareFavicon</code> pointing to a file note containing the favicon (e.g., in <code>.ico</code> format).</p><h3>Sharing a note as the root</h3><p>You can designate a specific note or folder as the root of your shared content by adding the <code>#shareRoot</code> label. This note will be linked when visiting <code>[http://domain.tld/share](http://domain/share)</code>, making it easier to use Trilium as a fully-fledged website.</p><aside class=\"admonition tip\"><p>Consider combining this with the <code>#shareIndex</code> label, which will display a list of all shared notes.</p></aside><h3>Displaying an index of shared notes</h3><p>When accessing a share, the sub-notes will be displayed in a tree on the left. But since multiple note trees can be shared, it might be useful to display a list of all the different share trees.</p><p>To do so, create a shared text note and apply the <code>shareIndex</code> label. When viewed, the list of shared roots will be displayed at the bottom of the note.</p><h3>Linking to an external website</h3><p>Sometimes it's useful to include a link to an external website alongside your shared notes — for example in the shared navigation or in an index. To do so, add the <code>#shareExternalLink</code> label to a note, with the target URL as its value (e.g. <code>#shareExternalLink=\"https://example.com\"</code>).</p><p>Any link pointing to this note will then redirect to the external website and open in a new browser tab, instead of opening the note's own shared page. Opening the note's shared URL by its ID also redirects to the external website. This applies to:</p><ul><li>the listing produced by the <code>#shareIndex</code> label;</li><li>the navigation tree of the shared site;</li><li>the \"Subpages\" list shown under a parent note;</li><li>inline links to this note from within other shared notes.</li></ul><p>The URL must be absolute and include the scheme (e.g. <code>https://</code>).</p><aside class=\"admonition note\"><p>The note still exists in the share tree and its own page remains reachable by its direct URL — the label only changes how links to it behave.</p></aside><h2>Attribute reference</h2><figure class=\"table\"><table class=\"ck-table-resized\"><colgroup><col style=\"width:18.38%;\"><col style=\"width:81.62%;\"></colgroup><thead><tr><th>Attribute</th><th>Description</th></tr></thead><tbody><tr><td><code>#shareHiddenFromTree</code></td><td>this note is hidden from the left navigation tree, from its parent's list of subpages, from shared note maps and from the share's search, but still accessible with its URL</td></tr><tr><td><code>#shareExternalLink</code></td><td>when a link points to this note (from the share index, a subpage list, or an inline link in another shared note), it redirects to the given external URL in a new tab instead of the note's shared page. Value is the absolute URL, e.g. <code>https://example.com</code>.</td></tr><tr><td><code>#shareAlias</code></td><td>define an alias using which the note will be available under <code>https://your_trilium_host/share/[your_alias]</code></td></tr><tr><td><code>#shareOmitDefaultCss</code></td><td>default share page CSS will be omitted. Use when you make extensive styling changes.</td></tr><tr><td><code>#shareRoot</code></td><td>marks note which is served on /share root.</td></tr><tr><td><code>#shareDescription</code></td><td>define text to be added to the HTML meta tag for description. It also describes the note in the list of subpages of its parent, in place of the start of its text.</td></tr><tr><td><code>#shareRaw</code></td><td>Note will be served in its raw format, without HTML wrapper. See also <a class=\"reference-link\" href=\"#root/_help_Qjt68inQ2bRj\">Serving directly the content of a note</a> for an alternative method without setting an attribute.</td></tr><tr><td><code>#shareDisallowRobotIndexing</code></td><td><p>Indicates to web crawlers that the page should not be indexed of this note by:</p><ul><li>Setting the <code>X-Robots-Tag: noindex</code> HTTP header.</li><li>Setting the <code>noindex, follow</code> meta tag.</li></ul></td></tr><tr><td><code>#shareCredentials</code></td><td>require credentials to access this shared note. Value is expected to be in format <code>username:password</code>. Don't forget to make this inheritable to apply to child-notes/images.</td></tr><tr><td><code>#shareIndex</code></td><td>Note with this label will list all roots of shared notes.</td></tr><tr><td><code>#shareHtmlLocation</code></td><td>defines where custom HTML injected via <code>~shareHtml</code> relation should be placed. Applied to the HTML snippet note itself. Format: <code>location:position</code> where location is <code>head</code>, <code>body</code>, or <code>content</code> and position is <code>start</code> or <code>end</code>. Defaults to <code>content:end</code>.</td></tr></tbody></table></figure><h3>Customizing logo</h3><p>It's possible to adjust the logo which is displayed above the navigation tree (in the header, on a narrow screen).</p><figure class=\"table\"><table><thead><tr><th>Attribute</th><th>Description</th></tr></thead><tbody><tr><td><code>~shareLogo</code></td><td>Relation set to an image to use as logo. The image must be part of the share tree (it can be hidden if needed). Without it, the logo is the icon of the shared root note.</td></tr><tr><td><code>#shareLogoWidth</code></td><td>The width of the logo, as a number without unit. With <code>#shareLogoHeight</code>, it sets the proportions of the logo, which is shown 32 pixels wide. Default is <code>53</code>.</td></tr><tr><td><code>#shareLogoHeight</code></td><td>The height of the logo, as a number without unit. With <code>#shareLogoWidth</code>, it sets the proportions of the logo. Default is <code>40</code>.</td></tr><tr><td><code>#shareRootLink</code></td><td>URL to navigate to when the logo is pressed.</td></tr></tbody></table></figure><h3>Customizing OpenGraph</h3><p>A meta-property is left out of the page when its attribute is not set. Without an image, link previews use a small card.</p><figure class=\"table\"><table><thead><tr><th>Attribute</th><th>Description</th></tr></thead><tbody><tr><td><code>#shareOpenGraphColor</code></td><td>This adjusts the <code>theme-color</code> meta-property.</td></tr><tr><td><code>#shareOpenGraphURL</code></td><td>This adjusts the <code>og:url</code> and <code>twitter:url</code> meta-properties. It is also the address a relative <code>og:image</code> is completed with, so it should be the public address of the shared site, such as <code>https://example.com/share/</code>.</td></tr><tr><td><code>#shareOpenGraphDomain</code></td><td>Adjusts the <code>twitter:domain</code> meta-property.</td></tr><tr><td><code>#shareOpenGraphImage</code> <br><code>~shareOpenGraphImage</code></td><td>Can be either a label with the address of an image, or a relation to an image <a class=\"reference-link\" href=\"#root/_help_W8vYD3Q1zjCR\">File</a>. This controls the <code>og:image</code> meta-property. Sites that show a preview of the link load the image from their own servers, so a relative address, which the relation always gives, is completed with <code>#shareOpenGraphURL</code>; without it, the image does not show in such previews.</td></tr></tbody></table></figure><h2>Credits</h2><p>Since v0.95.0, a new theme was introduced (and enabled by default) which greatly improves the visual aspect of the Share feature, as well as its functionality (such as mobile support, dark/light mode, collapsible tree, etc.). This theme is an adaptation of the <a href=\"https://github.com/zerebos/trilium.rocks\">Trilium Rocks!</a> by <a href=\"https://github.com/zerebos\">zerebos</a>.</p>","_help_Qjt68inQ2bRj": "<p>When accessing a shared note, Trilium will render it as a web page. Sometimes it's desirable to serve the content directly so that it can be used in a script or downloaded by the user.</p><figure class=\"table\"><table><thead><tr><th>A note displayed as a web page (HTML)</th><th>A note displayed as a raw format</th></tr></thead><tbody><tr><td><figure class=\"image\"><img style=\"aspect-ratio:738/275;\" src=\"{{helpAssets}}/User%20Guide/Advanced%20Usage/Sharing/Serving%20directly%20the%20content%20of%20a%20note_image.png\" width=\"738\" height=\"275\"></figure></td><td><img src=\"{{helpAssets}}/User%20Guide/Advanced%20Usage/Sharing/Serving%20directly%20the%20content%20of%20a%20note_image.jpg\"></td></tr></tbody></table></figure><h2>By adding an attribute to the note</h2><p>Simply add the <code>#shareRaw</code> attribute and the note will always be rendered <em>raw</em> when accessed from the share URL.</p><h2>By altering the URL</h2><p>Append <code>?raw</code> to the URL to display a note in its raw format regardless of whether the <code>#shareRaw</code> attribute is added on the note.</p><p><img src=\"{{helpAssets}}/User%20Guide/Advanced%20Usage/Sharing/Serving%20directly%20the%20content%20of%20a%20note_image.jpg\"></p>",@@ -246,7 +246,7 @@"_help_cRRrdZjgyhNc": "<p>Trilium sends nothing to an AI provider until you send a message. Enabling the integration, adding a provider or opening a chat transmits nothing on its own, the one exception is that listing a provider's models sends your API key to that provider, so the list can be fetched.</p><p>Once you send a message or run the <a class=\"reference-link\" href=\"#root/_help_VRoP0g1uHHc2\">In-editor AI assistant</a>, what leaves your machine depends on the provider you chose and on which context options are enabled.</p><h2>Where your notes go</h2><figure class=\"table\"><table><thead><tr><th>Provider type</th><th>Destination</th></tr></thead><tbody><tr><td>Cloud providers</td><td>The provider's servers (Anthropic, OpenAI, Google, DeepSeek)</td></tr><tr><td>Subscription-based</td><td>The provider's servers, via Claude Code running locally</td></tr><tr><td>Local / self-hosted</td><td>Nothing leaves the machine running the model</td></tr><tr><td>Custom endpoint</td><td>Wherever it was pointed, which may be your own hardware or a hosted service</td></tr></tbody></table></figure><p>This is the reason the provider list is grouped this way, and why Trilium pre-selects nothing: the choice of where your note content is sent is made explicitly by you, before anything is sent.</p><aside class=\"admonition note\"><p>The <a class=\"reference-link\" href=\"#root/_help_VRoP0g1uHHc2\">In-editor AI assistant</a> has a model selection of its own, so it may be answered by a different provider than the one in the chat. The row at the bottom of the assistant's menu always names the one being used.</p></aside><h2>What is actually sent</h2><ul><li><strong>Always, with every message</strong><ul><li>The conversation itself: your messages and the assistant's replies, including earlier turns</li><li>Trilium's system prompt describing how to format answers and use tools.</li></ul></li><li><strong>The current note, only when note context is enabled.</strong><ul><li>In the sidebar chat this is the file icon at the bottom; the dedicated chat note type never sends a current note.</li><li>What travels is a metadata block: the note's ID, title, type, creation and modification dates, its parent IDs, the titles of up to 20 children, up to 20 attributes, and a preview of the content.</li><li>Notes above a size threshold send a size hint instead of the text, and the model must call a tool to read further.</li></ul></li><li><strong>Any note the model asks for, when note access is enabled.</strong><ul><li>Tools let the model search your tree and read notes, attributes and attachments beyond the current one.</li><li>It decides what to fetch, and each call waits for you to allow it, unless the chat's permission mode lets reads or every call run on their own, or you allowed that tool for the chat. There is no per-note permission system, so the reachable scope is your whole tree.</li></ul></li><li><strong>Attachments and mentions</strong>, when you add them: images, PDFs and text files are sent to the provider, and an <code>@</code> mention makes that note fetchable.</li><li><strong>Your search query</strong>, when web search is enabled, the model's search terms reach the provider's own search infrastructure, or the search provider chosen in the <em>Tools</em> menu (Brave Search, Tavily, Exa, Serper, Perplexity or your SearXNG instance).</li><li><strong>The pages the model reads</strong>, when web search goes through a search provider: Trilium fetches each page the model asks for from the site itself, so the site sees a request from the machine running Trilium. The page's text is then sent to the model's provider.</li></ul><h2>The in-editor AI assistant</h2><p>A run of the <a class=\"reference-link\" href=\"#root/_help_VRoP0g1uHHc2\">In-editor AI assistant</a> sends a different set than a chat message. For quick actions, it sends it the moment you pick an action, there is no send button to reconsider at. For the free-form <em>Ask AI</em>, there is a dedicated send button and model selector.</p><ul><li><strong>The passage you selected</strong>, or the paragraph the cursor is in when you pick a quick action without selecting anything.</li><li><strong>Up to 1500 characters of the note on each side of that passage</strong>, as plain text. The assistant is told this is context only and must not be rewritten, but it is sent regardless of whether you selected it: a run on a single sentence still transmits the paragraphs around it.</li><li><strong>Where the note sits</strong>: its title and the titles of its parents, as a breadcrumb.</li><li><strong>Trilium's writing-assistant instructions</strong>, which describe the formatting it may produce.</li><li><strong>Earlier turns of the same exchange</strong>, once you follow up on a response.</li></ul><p>No note metadata block is sent, web search is never enabled, and the assistant has no note tools so it can read nothing beyond the text listed above.</p><h2>Protected notes</h2><p>While your <a href=\"#root/_help_bwg0e8ewQMak\">protected session</a> is locked, protected notes send neither title nor content. <strong>While it is unlocked they are treated like any other note,</strong> a note the model reads through a tool is sent to the provider in full. If you keep sensitive material in protected notes, be aware that unlocking them removes that boundary for the duration of the session.</p><p>The same applies to the <a class=\"reference-link\" href=\"#root/_help_VRoP0g1uHHc2\">In-editor AI assistant</a>: it works on whatever is open in the editor, so running it inside an unlocked protected note sends that note's text like any other.</p><h2>What you control</h2><ul><li><strong>Which provider</strong>: the single decision that determines whether anything leaves your machine at all.</li><li><strong>Note access</strong>: turn it off in the <span class=\"tn-icon bx bx-shield-quarter\"></span><em>Tools</em> menu at the bottom of the chat, and the model can read nothing beyond what you type.</li><li><strong>The current note:</strong> the file icon in the sidebar chat.</li><li><strong>Web search:</strong> also in the <em>Tools</em> menu.</li><li><strong>Which tool calls ask first:</strong> the <em>Permissions</em> submenu of the <em>Tools</em> menu. <em>Always ask</em> has every call wait for you, reads included. A new chat starts in the mode you picked last, so a chat after one set to <em>Don't ask</em> asks about nothing either. Until you pick a mode, chats start in <em>Ask before changes</em>, where the AI reads and searches your notes without asking.</li><li><strong>The editor assistant</strong>: it has no per-run toggles. What you control is whether you run it, what you select before you do and which model answers.</li></ul><p>With note access and note context both off, the provider receives only the words you typed.</p><h2>Keeping everything local</h2><p>Adding an Ollama or LM Studio provider keeps every message on the machine running the model, and Trilium marks their models as free because no metered API is involved. The trade-off is quality and hardware: a small local model may fail at tool calls that a cloud model handles, so a local setup that misbehaves is worth benchmarking against a cloud provider before reporting it as a bug.</p><h2>Telemetry & security</h2><p>Trilium itself collects no telemetry from the AI integration.</p><p>Your API key is stored in your database, sent only to the provider it belongs to, and is write-only through the options API so that a malevolent <a class=\"reference-link\" href=\"#root/_help_CdNpE2pqjmI6\">Scripting</a> cannot access it. If you have backend or SQL console access enabled, a malevolent script <strong>could potentially exfiltrate your API keys</strong>.</p><p>The built-in MCP server is off by default. When enabled, every request must carry an ETAPI token, which grants the same full read and write access to your notes as the REST API; treat one like a password. On desktop it is reachable only from <code>localhost</code> unless you turn on <a class=\"reference-link\" href=\"#root/_help_swSFivWk6KkA\">Network Access</a>.</p>","_help_KOWBFgsZXJAD": "<p><a href=\"https://en.wikipedia.org/wiki/Model_Context_Protocol\">Model Context Protocol</a> allows external chat applications such as Claude Code to have access to the Trilium database.</p><h2>Built-in MCP</h2><p>v0.103.0 comes with a built-in MCP server that is not active by default. To activate it, go to <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → AI/LLM and toggle the <em>MCP server</em> option.</p><p>Once the MCP is active, simply add the MCP server to your AI assistant. The URL to use is displayed in the <em>Endpoint</em> <em>URL</em> information underneath the MCP toggle.</p><p>Only the HTTP transport is supported, the <code>stdio</code> method is not supported. If that is a blocker, consider using a third-party alternative listed below.</p><p>The tools exposed to the MCP are the same tools that are supported by the internal chat (see the <em>Note access</em> section).</p><h3>Approving tool calls</h3><p>Trilium does not ask for approval of the calls an external assistant makes; that is left to the assistant's own permission settings. To help it decide, each tool tells the assistant whether it only reads your notes, only adds to them (creating a note, cloning it or appending to it), or can overwrite or remove something (editing, renaming, moving or deleting). An assistant that supports these hints can then run reads on their own and ask before changes, the way <em>Ask before changes</em> does in Trilium's chat.</p><h3>Authentication</h3><p>To protect your notes from unauthorized access, the MCP server requires authentication. Generally MCP servers need to support OAuth for authentication, but Trilium uses a simpler mechanism using Bearer tokens.</p><p>To configure authentication, first create an <a class=\"reference-link\" href=\"#root/_help_pgxEVkzLl1OP\">ETAPI (REST API)</a> token by going to <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>ETAPI</em>. Then follow the instructions in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>AI / LLM</em>, by looking at the <em>How to connect an assistant</em> section under MCP.</p><h2>Third-party alternatives</h2><p>The following are alternatives to Trilium's built-in MCP feature. Since Trilium's AI implementation is still experimental, its tooling might not be as mature as external tools.</p><ul><li><a href=\"https://github.com/perfectra1n/triliumnext-mcp\">perfectra1n/triliumnext-mcp</a></li><li><a href=\"https://github.com/tan-yong-sheng/triliumnext-mcp\">tan-yong-sheng/triliumnext-mcp</a></li><li><a href=\"https://github.com/eliassoares/trilium-fastmcp\">eliassoares/trilium-fastmcp</a></li></ul><aside class=\"admonition important\"><p>These solutions are third-party and thus not endorsed or supported directly by the Trilium Notes team. Please address questions and issues on their corresponding repository instead.</p></aside>","_help_Y84QCbArmK3z": "<aside class=\"admonition important\"><p><strong>Meeting transcription is in beta</strong></p><p>Meeting transcription is a new feature and is still in beta. It has not been tested on every operating system, audio setup and meeting application, so it might fail to capture the audio, miss part of a meeting or behave differently from what this page describes. Before relying on it for an important meeting, try it on a short call first.</p><p>If something does not work, please <a href=\"#root/_help_wy8So3yZZlH9\">report the issue</a>, mentioning your operating system and the meeting application you used. The <em>Keep recordings for troubleshooting</em> option described below keeps what is needed to reproduce a problem.</p></aside><p>Meeting transcription turns a meeting into text while it happens: Trilium listens to your microphone and to what the other participants say through your speakers, and writes down who said what in a new note. Recognition runs entirely on your device, so no audio leaves it.</p><p>Meeting transcription is available only in the desktop application. It is not available when Trilium is accessed through a browser, nor in the mobile application.</p><h2>Enabling meeting transcription</h2><p>Meeting transcription is off by default. To turn it on, go to <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Transcription</em> and turn on <em>Meeting transcription</em>. This adds the <span class=\"tn-icon bx bx-microphone\"></span> <em>Transcribe meeting</em> button to the <a class=\"reference-link\" href=\"#root/_help_xYmIYSP6wE3F\">Launch Bar</a>, marked with a <em>Beta</em> badge.</p><p>The speech recognition models are not part of Trilium. The first time you transcribe a meeting, Trilium asks to download them; see <a class=\"reference-link\" href=\"#root/_help_ebyr7ES2SwOW\">Downloaded resources</a> for the sizes and how to manage them. Each device downloads its own copy.</p><h2>Transcribing a meeting</h2><ol><li>Press the <span class=\"tn-icon bx bx-microphone\"></span> <em>Transcribe meeting</em> button in the <a class=\"reference-link\" href=\"#root/_help_xYmIYSP6wE3F\">Launch Bar</a>.</li><li>If the models are not downloaded yet, confirm the download and wait for it to finish.</li><li>Trilium creates a text note titled with the current date and time (for example <em>Meeting 2026-10-15 14:30</em>) in the <a class=\"reference-link\" href=\"#root/_help_S0Fos78ZfcY7\">Note Inbox</a>, opens it and starts transcribing. While it transcribes, the button turns into a <span class=\"tn-icon bx bx-stop-circle\"></span> <em>Stop transcribing</em> button and shows the time elapsed. Beside it, a reminder asks you to let everyone in the meeting know that it is being transcribed and to ask for their consent; it closes by itself after 10 seconds, or when you click it.</li><li>To end the transcription, press the <span class=\"tn-icon bx bx-stop-circle\"></span> <em>Stop transcribing</em> button. Trilium finishes transcribing what was already said before it stops.</li></ol><p>Only one meeting can be transcribed at a time. The note itself is an ordinary text note: you can take notes in it during the meeting, rename it or move it anywhere in the tree. It carries the <code>#meetingRecording</code> label.</p><p>Trilium tells you when your microphone or the meeting's audio is not being transcribed. It shows a message saying which one and why, the time on the button turns red and the button's tooltip says that some audio is not being transcribed:</p><ul><li><strong>Not captured</strong>: the transcription started without that audio, for example because there is no microphone or because Trilium was not allowed to record the screen and its audio. Connect the microphone or allow the recording, then stop the transcription and start it again.</li><li><strong>No audio</strong>: nothing has arrived from it for 10 seconds, as when its capture hangs. Stop the transcription and start it again; what was transcribed until then is kept.</li><li><strong>Only silence</strong>: it has delivered nothing but silence, for 15 seconds from your microphone or for a minute from the meeting. A microphone muted in your system's settings, or with a mute button of its own, does this. A meeting nobody speaks in for a minute does it too, so this message can be ignored when the others are just quiet.</li></ul><p>Each message shows once. <em>No audio</em> and <em>Only silence</em> clear by themselves once sound arrives again.</p><p>If the transcription stops on its own, for example because the audio could no longer be captured, Trilium shows a message and keeps everything transcribed until then. Closing Trilium during a meeting waits for the transcription to finish first.</p><h2>The transcript</h2><p>The transcript is stored as an <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> of the meeting note and is shown in a collapsible <em>Transcript</em> section above the note's content. It updates as the meeting goes on, one paragraph per speaker turn, each with the time it started. While the meeting is being transcribed, the header of the <em>Transcript</em> section shows the level of your microphone (<em>Me</em>) and of the meeting's audio (<em>Others</em>), so you can tell that both are being heard, even while the section is collapsed; a source that is not being transcribed is marked <em>Not captured</em>, <em>No audio</em> or <em>Only silence</em>. While someone is talking, <em>Speaking…</em> shows under their name until their words are transcribed. If you are reading the end of the transcript, it scrolls to follow new text.</p><ul><li>What you say into your microphone is labeled <em>Me</em>.</li><li>What the other participants say is labeled <em>Speaker 1</em>, <em>Speaker 2</em> and so on, while <em>Identify speakers</em> is on; otherwise it is labeled <em>Others</em>.</li><li>To name a speaker, click their name, type the new name and press <kbd>Enter</kbd>. The name changes on every turn of that speaker. Press <kbd>Esc</kbd> to cancel, or clear the name to restore the default one.</li><li>To show the transcript with or without hesitations such as \"uh\", \"um\" and stuttered words, press the <span class=\"tn-icon bx bx-eraser\"></span> <em>Hide filler words</em> button above it, which shows as pressed while they are hidden. While they are shown, they are grayed out, so you can see what hiding them would remove. This affects only what is shown; the stored transcript keeps every word.</li><li>To copy the transcript as plain text, press the <span class=\"tn-icon bx bx-copy\"></span> <em>Copy transcript</em> button above it. Each turn is copied with the speaker's name and the time it started, as shown, so the copy leaves out filler words while they are hidden.</li></ul><p>If the meeting note is <a href=\"#root/_help_bwg0e8ewQMak\">protected</a> and the protected session is locked during the meeting, the transcript cannot be saved. Trilium keeps it in memory and saves it once you enter the protected session again, as long as Trilium stays open.</p><h2>Configuration</h2><p>The settings are in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Transcription</em>, and are shown once <em>Meeting transcription</em> is on.</p><figure class=\"table\"><table><thead><tr><th>Option</th><th>Description</th></tr></thead><tbody><tr><td><em>European languages</em></td><td>The speech recognition model. Both recognize 25 European languages and work out which one is spoken. <em>Standard</em> is a smaller download and runs well on most computers. <em>High accuracy</em> makes fewer mistakes, but is a larger download and needs about 1.6 GB more memory while transcribing. A model is downloaded the first time you transcribe with it.</td></tr><tr><td><em>Identify speakers</em></td><td>Tells the other participants apart and labels each of them separately. Voices are compared only during the meeting: nothing about a voice is stored, and no one is recognized from one meeting to the next. Turn it off if it mixes up voices. The change applies from the next meeting.</td></tr><tr><td><em>Keep recordings for troubleshooting</em></td><td>Keeps the audio of the meeting, the settings used and the transcript as it was produced, so that a problem can be reported and reproduced. It takes about 230 MB per hour of meeting and is never deleted automatically. The folder where they are kept is shown below the option.</td></tr></tbody></table></figure><aside class=\"admonition warning\"><p>Before turning on <em>Keep recordings for troubleshooting</em>, ask everyone in the meeting to agree to being recorded. In several countries and US states, recording a conversation without everyone's consent is a criminal offense. The audio is stored unencrypted, even for protected notes. While the option is on, the tooltip of the <em>Transcribe meeting</em> button says so, and the reminder shown when the transcription starts mentions that the audio is kept.</p></aside><h2>Limitations</h2><ul><li>Meeting transcription needs a speech recognition engine that does not load on every computer, for example on Linux distributions older than Ubuntu 22.04 or Debian 12. Where it does not load, the <em>Transcribe meeting</em> button does not appear, the <em>Transcription</em> options say so, and the log records why.</li><li>The transcript is made from the audio played by your device. A participant whose voice does not come out of your speakers or headphones, for example someone in the same room, is transcribed only as far as your microphone picks them up, and is labeled <em>Me</em>.</li><li>Speaker identification works best with a few clearly distinct voices. Similar voices, many participants or poor call quality can lead to speakers being merged or split.</li><li>Accuracy is lower for languages other than English, and the model can switch to the wrong language for short passages.</li><li>Transcribing uses a noticeable amount of processor time and memory, especially with the <em>High accuracy</em> model.</li></ul>",- "_help_CdNpE2pqjmI6": "<p>Trilium supports creating <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> notes, i.e. notes which allow you to store some programming code and highlight it. Special case is JavaScript code notes which can also be executed inside Trilium which can in conjunction with <a class=\"reference-link\" href=\"#root/_help_GLks18SNjxmC\">Script API</a> provide extra functionality.</p><h2>Architecture Overview</h2><p>To go further I must explain basic architecture of Trilium - in its essence it is a classic web application - it has these two main components:</p><ul><li>frontend running in the browser (using HTML, CSS, JavaScript) - this is mainly used to interact with the user, display notes etc.</li><li>backend running JavaScript code in node.js runtime - this is responsible for e.g. storing notes, encrypting them etc.</li></ul><p>So we have frontend and backend, each with their own set of responsibilities, but their common feature is that they both run JavaScript code. Add to this the fact, that we're able to create JavaScript <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> and we're onto something.</p><h2>Use cases</h2><ul><li><a class=\"reference-link\" href=\"#root/_help_TjLYAo3JMO8X\">\"New Task\" launcher button</a></li></ul><h2>Action handler</h2><p>Saving the note to the database is backend's responsibility, so we immediately pass control to the backend and ask it to create a note. Once this is done, we show the newly created note so that the user can set the task title and maybe some attributes.</p><h2>Script execution</h2><p>So we have a script which will add the button to the toolbar. But how can we execute it? One possibility is to click on the <span class=\"tn-icon bx bx-play\"></span> <em>Execute script</em> button. The problem with this is that this UI change is time bound by Trilium runtime so when we restart Trilium, button won't be there.</p><p>We need to execute it every time Trilium starts up, but we probably don't want to have to manually click on play button on every start up.</p><p>The solution is to give the note the <a href=\"#root/_help_zEY4DaJG4YT5\">label</a> <code>#run=frontendStartup</code> - this is one of the \"system\" labels which Trilium understands. As you might guess, this will cause all such labeled script notes to be executed once Trilium frontend starts up.</p><p>(<code>#run=frontendStartup</code> does not work for <a href=\"#root/_help_RDslemsQ6gCp\">Mobile frontend</a> - if you want to have scripts running there, give the script <code>#run=mobileStartup</code> label).</p><h3>Execute button</h3><p>Runnable code notes (frontend or backend) and saved SQL consoles can optionally have a dedicated <span class=\"tn-icon bx bx-play\"></span> execute button alongside a description.</p><p>To do so, apply the following <a href=\"#root/_help_HI6GBBIduIgv\">labels</a>:</p><ul><li>A <code>#executeButton</code> with the value of the label being displayed as the label of the button.</li><li>An optional <code>#executeDescription</code> which adds explanatory text beside it.</li></ul><h2>Autocomplete & linting</h2><p>Starting with Trilium v0.104.0, frontend scripts, backend scripts and render notes benefit from an autocomplete system.</p><p>The autocomplete triggers automatically when typing <kbd>.</kbd> or manually by pressing <kbd>Ctrl</kbd>+<kbd>Space</kbd>.</p><p>In addition to that, the editor will also display syntax errors and warnings such as unreachable code.</p><aside class=\"admonition note\"><p>If you notice a false positive in regards with the errors/warnings reported or an incorrect or missing API, feel free to <a href=\"#root/_help_wy8So3yZZlH9\">open a issue</a> with a code sample.</p></aside><h2>More showcases</h2><p>You can see more scripting with explanation in <a class=\"reference-link\" href=\"#root/_help_5668rwcirq1t\">Advanced Showcases</a>.</p><h2>Events</h2><p>See <a class=\"reference-link\" href=\"#root/_help_GPERMystNGTB\">Events</a>.</p><h2>Script API</h2><p>See <a class=\"reference-link\" href=\"#root/_help_GLks18SNjxmC\">Script API</a>.</p>",+ "_help_CdNpE2pqjmI6": "<p>Trilium supports creating <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> notes, i.e. notes which allow you to store some programming code and highlight it. Special case is JavaScript code notes which can also be executed inside Trilium which can in conjunction with <a class=\"reference-link\" href=\"#root/_help_GLks18SNjxmC\">Script API</a> provide extra functionality.</p><h2>Architecture Overview</h2><p>To go further I must explain basic architecture of Trilium - in its essence it is a classic web application - it has these two main components:</p><ul><li>frontend running in the browser (using HTML, CSS, JavaScript) - this is mainly used to interact with the user, display notes etc.</li><li>backend running JavaScript code in node.js runtime - this is responsible for e.g. storing notes, encrypting them etc.</li></ul><p>So we have frontend and backend, each with their own set of responsibilities, but their common feature is that they both run JavaScript code. Add to this the fact, that we're able to create JavaScript <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> and we're onto something.</p><h2>Use cases</h2><ul><li><a class=\"reference-link\" href=\"#root/_help_TjLYAo3JMO8X\">\"New Task\" launcher button</a></li></ul><h2>Action handler</h2><p>Saving the note to the database is backend's responsibility, so we immediately pass control to the backend and ask it to create a note. Once this is done, we show the newly created note so that the user can set the task title and maybe some attributes.</p><h2>Script execution</h2><p>So we have a script which will add the button to the toolbar. But how can we execute it? One possibility is to click on the <span class=\"tn-icon bx bx-play\"></span> <em>Execute script</em> button. The problem with this is that this UI change is time bound by Trilium runtime so when we restart Trilium, button won't be there.</p><p>We need to execute it every time Trilium starts up, but we probably don't want to have to manually click on play button on every start up.</p><p>The solution is to give the note the <a href=\"#root/_help_zEY4DaJG4YT5\">label</a> <code>#run=frontendStartup</code> - this is one of the \"system\" labels which Trilium understands. As you might guess, this will cause all such labeled script notes to be executed once Trilium frontend starts up.</p><p>(<code>#run=frontendStartup</code> does not work for <a href=\"#root/_help_RDslemsQ6gCp\">Mobile frontend</a> - if you want to have scripts running there, give the script <code>#run=mobileStartup</code> label).</p><h3>Execute button</h3><p>Runnable code notes (frontend or backend) and saved SQL consoles can optionally have a dedicated <span class=\"tn-icon bx bx-play\"></span> execute button alongside a description.</p><p>To do so, apply the following <a href=\"#root/_help_HI6GBBIduIgv\">labels</a>:</p><ul><li>A <code>#executeButton</code> with the value of the label being displayed as the label of the button.</li><li>An optional <code>#executeDescription</code> which adds explanatory text beside it.</li></ul><h2>Autocomplete & linting</h2><p>Starting with Trilium v0.104.0, frontend scripts, backend scripts and render notes benefit from an autocomplete system.</p><p>The autocomplete opens automatically while typing a name or after a <kbd>.</kbd>, or manually by pressing <kbd>Ctrl</kbd>+<kbd>Space</kbd>. Its list looks and works like the <kbd>/</kbd> list of a text note: each entry has an icon for its kind (function, property, class…), <kbd>Enter</kbd> or <kbd>Tab</kbd> inserts the highlighted one and <kbd>Esc</kbd> closes it.</p><p>In addition to that, the editor will also display syntax errors and warnings such as unreachable code.</p><aside class=\"admonition note\"><p>If you notice a false positive in regards with the errors/warnings reported or an incorrect or missing API, feel free to <a href=\"#root/_help_wy8So3yZZlH9\">open a issue</a> with a code sample.</p></aside><h2>More showcases</h2><p>You can see more scripting with explanation in <a class=\"reference-link\" href=\"#root/_help_5668rwcirq1t\">Advanced Showcases</a>.</p><h2>Events</h2><p>See <a class=\"reference-link\" href=\"#root/_help_GPERMystNGTB\">Events</a>.</p><h2>Script API</h2><p>See <a class=\"reference-link\" href=\"#root/_help_GLks18SNjxmC\">Script API</a>.</p>","_help_yIhgI5H7A2Sm": "<p>Front-end scripts are custom JavaScript notes that are run on the client (browser environment)</p><p>There are four flavors of front-end scripts:</p><figure class=\"table\"><table><tbody><tr><td>Regular scripts</td><td>These are run with the current app and note context. These can be run either manually or automatically on start-up.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_MgibgPcfeuGz\">Custom Widgets</a></td><td>These can introduce new UI elements in various positions, such as near the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>, content area or even the <a class=\"reference-link\" href=\"#root/_help_RnaPdbciOfeq\">Right Sidebar</a>.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_4Gn3psZKsfSm\">Launch Bar Widgets</a></td><td>Similar to <a class=\"reference-link\" href=\"#root/_help_MgibgPcfeuGz\">Custom Widgets</a>, but dedicated to the <a class=\"reference-link\" href=\"#root/_help_xYmIYSP6wE3F\">Launch Bar</a>. These can simply introduce new buttons or graphical elements to the bar.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_HcABDtFCkbFN\">Render Note</a></td><td>This allows rendering custom content inside a note, using either HTML or Preact JSX.</td></tr></tbody></table></figure><p>For more advanced behaviors that do not require a user interface (e.g. batch modifying notes), see <a class=\"reference-link\" href=\"#root/_help_SPirpZypehBG\">Backend scripts</a>.</p><h2>Scripts</h2><p>Scripts don't have any special requirements. They can be run manually using the <em>Execute</em> button on the code note or they can be run automatically, see <a class=\"reference-link\" href=\"#root/_help_irkwjdNtjcxR\">Frontend Events</a>.</p><h2>Widgets</h2><p>Widgets require a certain format in order for Trilium to be able to integrate them into the UI.</p><ul><li>For legacy widgets, the script note must export a <code>BasicWidget</code> or a derived one (see <a class=\"reference-link\" href=\"#root/_help_GhurYZjh8e1V\">Note context aware widget</a> or <a class=\"reference-link\" href=\"#root/_help_M8IppdwVHSjG\">Right pane widget</a>).</li><li>For Preact widgets, a built-in helper called <code>defineWidget</code> needs to be used.</li></ul><p>For more information, see <a class=\"reference-link\" href=\"#root/_help_MgibgPcfeuGz\">Custom Widgets</a>.</p><h2>Script API</h2><p>The front-end API of Trilium is available to all scripts running in the front-end context as global variable <code>api</code>. For a reference of the API, see <a class=\"reference-link\" href=\"#root/_help_Q2z6av6JZVWm\">Frontend API</a>.</p><h3>Tutorial</h3><p>For more information on building widgets, take a look at <a href=\"#root/_help_SynTBQiBsdYJ\">Widget Basics</a>.</p>","_help_MgibgPcfeuGz": "<p>Custom widgets are a special subset of scripts that render graphical elements in certain parts of the application. These can be used to add new functionality to the Trilium application.</p><h2>Preact with JSX vs. vanilla jQuery</h2><p>In older versions of Trilium, custom widgets were exclusively written in a combination of jQuery with Trilium's internal widget architecture (e.g., <code>BasicWidget</code>, <code>NoteContextAwareWidget</code>).</p><p>Starting with v0.101.0, custom widgets can also be written in JSX using the <a class=\"reference-link\" href=\"#root/_help_KLsqhjaqh1QW\">Preact</a> framework. Both legacy and Preact widgets have the same capabilities, with a single difference:</p><ul><li>Preact widgets are content-sized by default whereas legacy widgets need <code>this.contentSized()</code> applied in the constructor. For more information, see the corresponding section in <a class=\"reference-link\" href=\"#root/_help_gMkgcLJ6jBkg\">Troubleshooting</a>.</li></ul><p>Wherever possible, widget examples will be both in the legacy and Preact format.</p><h2>Creating a custom widget</h2><p>The quickest way is <em>Insert child note</em> → <em>Code</em> → <em>Widget</em> in the <a class=\"reference-link\" href=\"#root/_help_YtSN43OrfzaA\">Note tree contextual menu</a>. It creates a JSX note with the <code>#widget</code> label and a minimal Preact widget to start from.</p><p>To set one up by hand instead:</p><ol><li>Create a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note.</li><li>Set the language to:<ol><li>JavaScript (frontend) for legacy widgets using jQuery.</li><li>JSX for Preact widgets. You might need to go to Options → Code to enable the language first.</li></ol></li><li>Apply the <code>#widget</code> <a href=\"#root/_help_HI6GBBIduIgv\">label</a>.</li></ol><h2>Getting started with a simple example</h2><p>Let's start by creating a widget that shows a message near the content area. Follow the previous section to create a code note, and use the following content.</p><div class=\"trilium-tabs\"><section class=\"trilium-tab\"><p class=\"trilium-tab-title\"><span class=\"tn-icon bx bxl-react\"></span> Preact</p><div class=\"trilium-tab-panel\"><pre><code class=\"language-text-x-trilium-auto\">import { defineWidget } from \"trilium:preact\";\n\nexport default defineWidget({\n parent: \"center-pane\",\n render: () => <span>Center pane from Preact.</span>\n});</code></pre></div></section><section class=\"trilium-tab\"><p class=\"trilium-tab-title\"><span class=\"tn-icon bx bxl-javascript\"></span> Legacy</p><div class=\"trilium-tab-panel\"><pre><code class=\"language-text-x-trilium-auto\">class HelloCenterPane extends api.BasicWidget {\n\n constructor() {\n super();\n this.contentSized();\n }\n\n get parentWidget() { return \"center-pane\" }\n\n doRender() {\n this.$widget = $(\"<span>Center pane</span>\");\n }\n \n}\n\nmodule.exports = new HelloCenterPane();</code></pre></div></section></div><p><a href=\"#root/_help_s8alTXmpFR61\">Refresh the application</a> and the widget should appear underneath the content area.</p><h2>Widget location (parent widget)</h2><p>A widget can be placed in one of the following sections of the applications:</p><figure class=\"table\"><table class=\"ck-table-resized\"><colgroup><col style=\"width:15.59%;\"><col style=\"width:30.42%;\"><col style=\"width:16.68%;\"><col style=\"width:37.31%;\"></colgroup><thead><tr><th>Value for <code>parentWidget</code></th><th>Description</th><th>Sample widget</th><th>Special requirements</th></tr></thead><tbody><tr><th><code>left-pane</code></th><td>Appears within the same pane that holds the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>.</td><td>Same as above, with only a different <code>parentWidget</code>.</td><td>None.</td></tr><tr><th><code>center-pane</code></th><td>In the content area. If a split is open, the widget will span all of the splits.</td><td>See example above.</td><td>None.</td></tr><tr><th><code>note-detail-pane</code></th><td><p>In the content area, inside the note detail area. If a split is open, the widget will be contained inside the split.</p><p>This is ideal if the widget is note-specific.</p></td><td><a class=\"reference-link\" href=\"#root/_help_GhurYZjh8e1V\">Note context aware widget</a></td><td><ul><li>The widget must export a <code>class</code> and not an instance of the class (e.g. <code>no new</code>) because it needs to be multiplied for each note, so that splits work correctly.</li><li>Since the <code>class</code> is exported instead of an instance, the <code>parentWidget</code> getter must be <code>static</code>, otherwise the widget is ignored.</li></ul></td></tr><tr><th><code>right-pane</code></th><td>In the <a class=\"reference-link\" href=\"#root/_help_RnaPdbciOfeq\">Right Sidebar</a>, as a dedicated section.</td><td><a class=\"reference-link\" href=\"#root/_help_M8IppdwVHSjG\">Right pane widget</a></td><td><ul><li>Although not mandatory, it's best to use a <code>RightPanelWidget</code> instead of a <code>BasicWidget</code> or a <code>NoteContextAwareWidget</code>.</li></ul></td></tr></tbody></table></figure><p>To position the widget somewhere else, just change the value passed to <code>get parentWidget()</code> for legacy widgets or the <code>parent</code> field for Preact. Do note that some positions such as <code>note-detail-pane</code> and <code>right-pane</code> have special requirements that need to be accounted for (see the table above).</p><h2>Multiple widgets in a single note</h2><p>A widget note usually returns one widget, but it can also return an array of them. This is useful when several widgets share code or state, since they can all live in the same note instead of being split across notes that need a shared module.</p><p>Each widget of the array is registered on its own, so they can have different parents and positions. A widget that is missing its <code>parentWidget</code> (or <code>parent</code> for Preact) is reported as an error without affecting the other widgets of the note.</p><div class=\"trilium-tabs\"><section class=\"trilium-tab\"><p class=\"trilium-tab-title\"><span class=\"tn-icon bx bxl-react\"></span> Preact</p><div class=\"trilium-tab-panel\"><pre><code class=\"language-text-x-trilium-auto\">import { defineWidget } from \"trilium:preact\";\n\nexport default [\n defineWidget({\n parent: \"left-pane\",\n render: () => <span>Left pane from Preact.</span>\n }),\n defineWidget({\n parent: \"right-pane\",\n render: () => <span>Right pane from Preact.</span>\n })\n];</code></pre></div></section><section class=\"trilium-tab\"><p class=\"trilium-tab-title\"><span class=\"tn-icon bx bxl-javascript\"></span> Legacy</p><div class=\"trilium-tab-panel\"><pre><code class=\"language-text-x-trilium-auto\">class TreeWidget extends api.BasicWidget {\n get parentWidget() { return \"left-pane\"; }\n doRender() { this.$widget = $(\"<span>Left pane</span>\"); }\n}\n\nclass SidebarWidget extends api.BasicWidget {\n get parentWidget() { return \"right-pane\"; }\n doRender() { this.$widget = $(\"<span>Right pane</span>\"); }\n}\n\nmodule.exports = [ new TreeWidget(), new SidebarWidget() ];</code></pre></div></section></div><h2>Launch bar widgets</h2><p>Launch bar widgets are similar to <em>Custom widgets</em> but are specific to the <a class=\"reference-link\" href=\"#root/_help_xYmIYSP6wE3F\">Launch Bar</a>. See <a class=\"reference-link\" href=\"#root/_help_4Gn3psZKsfSm\">Launch Bar Widgets</a> for more information.</p><h2>Custom position</h2><p>The position of a custom widget is defined via a <code>position</code> integer.</p><div class=\"trilium-tabs\"><section class=\"trilium-tab\"><p class=\"trilium-tab-title\"><span class=\"tn-icon bx bxl-react\"></span> Preact</p><div class=\"trilium-tab-panel\"><pre><code class=\"language-text-x-trilium-auto\">export default defineWidget({\n // [...]\n position: 10\n});</code></pre></div></section><section class=\"trilium-tab\"><p class=\"trilium-tab-title\"><span class=\"tn-icon bx bxl-javascript\"></span> Legacy</p><div class=\"trilium-tab-panel\"><pre><code class=\"language-text-x-trilium-auto\">class MyWidget extends api.BasicWidget {\n\t// [..\n\tget position() { return 10; }\n}</code></pre></div></section></div>","_help_SynTBQiBsdYJ": "<p>This guide will walk you through creating a basic widget inside Trilium. By following these steps, you'll learn how to build a simple UI element that interacts with the user.</p><h3>Step 1: The Basic Widget Structure</h3><p>To start, we'll create the most basic widget possible. Here's a simple example:</p><pre><code class=\"language-text-x-trilium-auto\">class MyWidget extends api.BasicWidget {\n get position() { return 1; }\n get parentWidget() { return \"left-pane\"; }\n \n doRender() {\n this.$widget = $(\"<div id='my-widget'>\");\n return this.$widget;\n }\n}\n\nmodule.exports = new MyWidget();</code></pre><p>To implement this widget:</p><ol><li>Create a new <code>JS Frontend</code> note in Trilium and paste in the code above.</li><li>Assign the <code>#widget</code> <a href=\"#root/_help_zEY4DaJG4YT5\">attribute</a> to the <a href=\"#root/_help_BFs8mudNFgCS\">note</a>.</li><li>Restart Trilium or reload the window.</li></ol><p>To verify that the widget is working, open the developer tools (<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>I</kbd>) and run <code>document.querySelector(\"#my-widget\")</code>. If the element is found, the widget is functioning correctly. If <code>undefined</code> is returned, double-check that the <a href=\"#root/_help_BFs8mudNFgCS\">note</a> has the <code>#widget</code> <a href=\"#root/_help_zEY4DaJG4YT5\">attribute</a>.</p><h3>Step 2: Adding an UI Element</h3><p>Next, let's improve the widget by adding a button to it.</p><pre><code class=\"language-text-x-trilium-auto\">const template = `<div id=\"my-widget\"><button>Click Me!</button></div>`;\n\nclass MyWidget extends api.BasicWidget {\n get position() {return 1;}\n get parentWidget() {return \"left-pane\"}\n\n doRender() {\n this.$widget = $(template);\n return this.$widget;\n }\n}\n\nmodule.exports = new MyWidget();</code></pre><p>After making this change, reload Trilium. You should now see a button in the top-left corner of the left pane.</p><h3>Step 3: Styling the Widget</h3><p>To make the button more visually appealing and position it correctly, we'll apply some custom styling. Trilium includes <a href=\"https://boxicons.com\">Box Icons</a>, which we'll use to replace the button text with an icon. For example the <span class=\"tn-icon bx bxs-magic-wand\"></span> <code>bx bxs-magic-wand</code> icon.</p><p>Here's the updated template:</p><pre><code class=\"language-text-x-trilium-auto\">const template = `<div id=\"my-widget\"><button class=\"tree-floating-button bx bxs-magic-wand tree-settings-button\"></button></div>`;</code></pre><p>Next, we'll adjust the button's position using CSS:</p><pre><code class=\"language-text-x-trilium-auto\">class MyWidget extends api.BasicWidget {\n get position() { return 1; }\n get parentWidget() { return \"left-pane\"; }\n \n doRender() {\n this.$widget = $(template);\n this.cssBlock(`#my-widget {\n position: absolute;\n bottom: 40px;\n left: 60px;\n z-index: 1;\n }`);\n return this.$widget;\n }\n}\n\nmodule.exports = new MyWidget();</code></pre><p>After reloading Trilium, the button should now appear at the bottom left of the left pane, alongside other action buttons.</p><h3>Step 4: Adding User Interaction</h3><p>Let’s make the button interactive by showing a message when it’s clicked. We'll use the <code>api.showMessage</code> method from the <a href=\"#root/_help_GLks18SNjxmC\">Script API</a>.</p><pre><code class=\"language-text-x-trilium-auto\">class MyWidget extends api.BasicWidget {\n get position() { return 1; }\n get parentWidget() { return \"left-pane\"; }\n \n doRender() {\n this.$widget = $(template);\n this.cssBlock(`#my-widget {\n position: absolute;\n bottom: 40px;\n left: 60px;\n z-index: 1;\n }`);\n this.$widget.find(\"button\").on(\"click\", () => api.showMessage(\"Hello World!\"));\n return this.$widget;\n }\n}\n\nmodule.exports = new MyWidget();</code></pre><p>For the list of possible values for <code>parentWidget()</code>, see <a class=\"reference-link\" href=\"#root/_help_MgibgPcfeuGz\">Custom Widgets</a>. </p><p><a href=\"#root/_help_s8alTXmpFR61\">Reload</a> the application one last time. When you click the button, a \"Hello World!\" message should appear, confirming that your widget is fully functional.</p>",diff --git a/docs/User Guide/User Guide/Advanced Usage/Snippets/Code Snippets.md b/docs/User Guide/User Guide/Advanced Usage/Snippets/Code Snippets.mdindex f546c3fd98..7076ed42fe 100644--- a/docs/User Guide/User Guide/Advanced Usage/Snippets/Code Snippets.md+++ b/docs/User Guide/User Guide/Advanced Usage/Snippets/Code Snippets.md@@ -15,7 +15,7 @@ The note's title becomes the title of the snippet. Optionally, you can add a des## Inserting a snippet-To insert a snippet, type `/snippet` and select its title from the dropdown.+To insert a snippet, type <kbd>/</kbd> followed by the first letters of its title, then select it from the list. Typing `/snippet` lists every snippet available in the note.> [!IMPORTANT]> Only code snippets whose language mode matches the current code note are listed. For example, a CSS code note shows only CSS snippets, not JavaScript ones. The exception is snippets set to "Plain text", which are available in <a class="reference-link" href="../../Note%20Types/Markdown.md">Markdown</a> notes and any code note regardless of its language mode.diff --git a/docs/User Guide/User Guide/Scripting.md b/docs/User Guide/User Guide/Scripting.mdindex ae7e74a1db..925aabd5c8 100644--- a/docs/User Guide/User Guide/Scripting.md+++ b/docs/User Guide/User Guide/Scripting.md@@ -41,7 +41,7 @@ To do so, apply the following [labels](Advanced%20Usage/Attributes/Labels.md):Starting with Trilium v0.104.0, frontend scripts, backend scripts and render notes benefit from an autocomplete system.-The autocomplete triggers automatically when typing <kbd>.</kbd> or manually by pressing <kbd>Ctrl</kbd>+<kbd>Space</kbd>.+The autocomplete opens automatically while typing a name or after a <kbd>.</kbd>, or manually by pressing <kbd>Ctrl</kbd>+<kbd>Space</kbd>. Its list looks and works like the <kbd>/</kbd> list of a text note: each entry has an icon for its kind (function, property, class…), <kbd>Enter</kbd> or <kbd>Tab</kbd> inserts the highlighted one and <kbd>Esc</kbd> closes it.In addition to that, the editor will also display syntax errors and warnings such as unreachable code.diff --git a/packages/codemirror/src/extensions/hosted_completion.ts b/packages/codemirror/src/extensions/hosted_completion.tsindex 44442720a7..2fb13d78ec 100644--- a/packages/codemirror/src/extensions/hosted_completion.ts+++ b/packages/codemirror/src/extensions/hosted_completion.ts@@ -91,6 +91,9 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, listconstructor(private readonly view: EditorView) {this.list = list(view);+ const lists = hostedLists.get(view) ?? new Set();+ lists.add(this.list);+ hostedLists.set(view, lists);}update(update: ViewUpdate) {@@ -148,6 +151,7 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, listdestroy() {this.destroyed = true;+ hostedLists.get(this.view)?.delete(this.list);this.setActiveDescendant(null);this.list.hide();this.list.destroy?.();@@ -277,6 +281,13 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, listreturn Prec.highest(plugin);}+/** Whether a list of {@link hostedCompletion} shows entries in `view` and takes the arrow keys. */+export function isHostedCompletionShown(view: EditorView) {+ return [ ...(hostedLists.get(view) ?? []) ].some((list) => list.element !== null);+}++const hostedLists = new WeakMap<EditorView, Set<HostedCompletionList<never>>>();+/** Ctrl-Space, or Alt-` as CodeMirror binds it on a Mac, where Ctrl-Space switches the input source. */function isExplicitRequest(event: KeyboardEvent) {return (event.ctrlKey && event.key === " ") || (event.altKey && event.key === "`");diff --git a/packages/codemirror/src/index.spec.ts b/packages/codemirror/src/index.spec.tsindex 0d3f3ac44a..8306598fbd 100644--- a/packages/codemirror/src/index.spec.ts+++ b/packages/codemirror/src/index.spec.ts@@ -9,7 +9,8 @@ vi.mock("./type_completion/index.js", async (importOriginal) => {return { ...original, buildTypeCompletion: vi.fn(original.buildTypeCompletion) };});-import CodeMirror, { type EditorConfig, getThemeById } from "./index.js";+import { hostedCompletion } from "./extensions/hosted_completion.js";+import CodeMirror, { type EditorConfig, getThemeById, SCRIPT_MIME_BACKEND } from "./index.js";import { buildTypeCompletion } from "./type_completion/index.js";let editor: CodeMirror | undefined;@@ -454,6 +455,30 @@ describe("CodeMirror", () => {closeCompletion(instance);expect(instance.getEdgeLeftBy(arrowDown)).toBe("end");});++ it("leaves the arrow keys to a hosted list while it shows entries", async () => {+ const instance = build();+ editor = instance;+ let element: HTMLElement | null = null;+ instance.setNamedExtension("test", hostedCompletion({+ match: () => ({ from: 0 }),+ list: () => ({+ show() { element = document.createElement("div"); },+ hide() { element = null; },+ handleKeyDown: () => false,+ get element() { return element; }+ })+ }));+ instance.focus();+ instance.setText("ab");+ instance.dispatch({ selection: EditorSelection.cursor(2) });+ await vi.waitFor(() => expect(element).not.toBe(null));++ const arrowDown = createKeydown("ArrowDown", instance.contentDOM);+ expect(instance.getEdgeLeftBy(arrowDown)).toBe(null);+ element = null;+ expect(instance.getEdgeLeftBy(arrowDown)).toBe("end");+ });});describe("find and replace", () => {@@ -591,6 +616,23 @@ describe("CodeMirror", () => {});});+ describe("type completions", () => {+ it("looks up the language service's completions at the caret of a script", async () => {+ editor = build();+ await editor.setMimeType("text/plain");+ expect(editor.hasTypeCompletions()).toBe(false);+ expect(await editor.getTypeCompletions(true)).toBe(null);++ editor.setText("api.");+ await editor.setMimeType(SCRIPT_MIME_BACKEND);+ editor.dispatch({ selection: EditorSelection.cursor(4) });+ expect(editor.hasTypeCompletions()).toBe(true);+ const completions = await editor.getTypeCompletions(false) ?? [];+ expect(completions).toContainEqual({ label: "getNote", type: "method" });+ expect(completions.map(({ label }) => label)).not.toContain("Array");+ }, 30_000);+ });+describe("script api context", () => {it("is safe to set before any MIME type is known", async () => {editor = build();@@ -607,7 +649,7 @@ describe("CodeMirror", () => {it("builds the completion once while the MIME type and context stay the same", async () => {const buildMock = vi.mocked(buildTypeCompletion);- buildMock.mockResolvedValue({ extensions: [], source: null });+ buildMock.mockResolvedValue({ extensions: [], complete: null });editor = build();// What a code note's effects request on mount.diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.tsindex 75281e8715..4901dad766 100644--- a/packages/codemirror/src/index.ts+++ b/packages/codemirror/src/index.ts@@ -10,10 +10,16 @@ import byMimeType, { MIME_ALIASES } from "./syntax_highlighting.js";import smartIndentWithTab from "./extensions/custom_tab.js";import type { ThemeDefinition } from "./color_themes.js";import { createSearchHighlighter, SearchHighlighter, searchMatchHighlightTheme } from "./find_replace.js";-import { buildTypeCompletion, type ScriptApiContext } from "./type_completion/index.js";+import { isHostedCompletionShown } from "./extensions/hosted_completion.js";+import {+ buildTypeCompletion, type ScriptApiContext, type TypeCompleter+} from "./type_completion/index.js";export { default as ColorThemes, type ThemeDefinition, type ThemeVariant, getThemeById } from "./color_themes.js";-export { isScriptMime, type ScriptApiContext, SCRIPT_MIME_BACKEND, SCRIPT_MIME_FRONTEND } from "./type_completion/index.js";+export {+ isScriptMime, type ScriptApiContext, SCRIPT_MIME_BACKEND, SCRIPT_MIME_FRONTEND,+ type TypeCompletionEntry+} from "./type_completion/index.js";export { triliumLogHighlighter } from "./extensions/trilium_log_highlighter.js";// Custom keymap to prevent Ctrl+Enter from inserting a newline@@ -103,6 +109,8 @@ export default class CodeMirror extends EditorView {private namedCompartments = new Map<string, Compartment>();/** Named completion sources aggregated into the editor's single autocompletion. */private completionSources = new Map<string, CompletionSource>();+ /** The language service's completions for the current MIME type, or null where it has none. */+ private typeCompleter: TypeCompleter | null = null;/** Monotonic token guarding against out-of-order async type-completion updates. */private typeCompletionToken = 0;/** The latest type-completion build, which a request for the same MIME type and context joins. */@@ -340,7 +348,8 @@ export default class CodeMirror extends EditorView {const { ranges, main } = this.state.selection;const hasModifier = event.shiftKey || event.ctrlKey || event.altKey || event.metaKey;if (event.target !== this.contentDOM || hasModifier || event.isComposing- || ranges.length > 1 || !main.empty || completionStatus(this.state) === "active") {+ || ranges.length > 1 || !main.empty || completionStatus(this.state) === "active"+ || isHostedCompletionShown(this)) {return null;}@@ -530,14 +539,27 @@ export default class CodeMirror extends EditorView {/** Guarded by a token so a slow build for a previous MIME type can't overwrite a newer one. */async #buildTypeCompletion(mime: string) {const token = ++this.typeCompletionToken;- const { extensions, source } = await buildTypeCompletion(mime, this.scriptApiContext);+ const { extensions, complete } = await buildTypeCompletion(mime, this.scriptApiContext);if (token !== this.typeCompletionToken) {return; // a newer setMimeType call superseded this one}this.dispatch({effects: this.typeCompletionCompartment.reconfigure(extensions)});- this.setCompletionSource("typescript", source);+ this.typeCompleter = complete;+ }++ /** Whether the MIME type has a TypeScript language service for `getTypeCompletions()`. */+ hasTypeCompletions() {+ return this.typeCompleter !== null;+ }++ /**+ * The language service's completions at the caret, best first, or null where it offers none+ * or the MIME type has no language service.+ */+ async getTypeCompletions(explicit: boolean) {+ return await this.typeCompleter?.(this.state.selection.main.head, explicit) ?? null;}/**diff --git a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.ts b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.tsindex 157f0d5165..d975569114 100644--- a/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.ts+++ b/packages/codemirror/src/type_completion/codemirror-ts/autocomplete.ts@@ -2,31 +2,11 @@ import type {Completion,CompletionContext,CompletionResult,- CompletionSource,} from "@codemirror/autocomplete";import ts from "typescript";import { type VirtualTypeScriptEnvironment } from "@typescript/vfs";-import { tsFacet } from "./environment.js";import { AUTOCOMPLETION_SYMBOLS } from "./symbols.js";-/**- * Create a `CompletionSource` that queries- * the _on-thread_ TypeScript environments for autocompletions- * at this character.- */-export function tsAutocomplete(): CompletionSource {- return async (- context: CompletionContext,- ): Promise<CompletionResult | null> => {- const config = context.state.facet(tsFacet);- if (!config) return null;- return getAutocompletion({- ...config,- context,- });- };-}-const TS_COMPLETE_BLOCKLIST: ts.ScriptElementKind[] = [ts.ScriptElementKind.warning,];diff --git a/packages/codemirror/src/type_completion/index.spec.ts b/packages/codemirror/src/type_completion/index.spec.tsindex 68a904c177..2cdc0d478c 100644--- a/packages/codemirror/src/type_completion/index.spec.ts+++ b/packages/codemirror/src/type_completion/index.spec.ts@@ -475,25 +475,24 @@ describe("buildTypeCompletion", () => {it("returns nothing for a MIME type that is not a script note", async () => {// Ordinary code notes are highlighted only; the TypeScript service is not built for them.for (const mime of [ "text/plain", "text/css", "application/json", "text/javascript" ]) {- expect(await buildTypeCompletion(mime)).toEqual({ extensions: [], source: null });+ expect(await buildTypeCompletion(mime)).toEqual({ extensions: [], complete: null });}});- it("builds the language-service extensions and a completion source for a script note", async () => {- const { extensions, source } = await buildTypeCompletion(SCRIPT_MIME_BACKEND);+ it("builds the language-service extensions and a completion lookup for a script", async () => {+ const { extensions, complete } = await buildTypeCompletion(SCRIPT_MIME_BACKEND);expect(Array.isArray(extensions)).toBe(true);expect(extensions.length).toBeGreaterThan(0);- // The source is handed to the editor's single autocompletion rather than adding its own.- expect(typeof source).toBe("function");+ expect(typeof complete).toBe("function");}, TIMEOUT);it("builds for a frontend script note and honours the api context", async () => {const frontend = await buildTypeCompletion(SCRIPT_MIME_FRONTEND);- expect(frontend.source).toBeTruthy();+ expect(frontend.complete).toBeTruthy();const handler = await buildTypeCompletion(SCRIPT_MIME_BACKEND, { customRequestHandler: true });- expect(handler.source).toBeTruthy();+ expect(handler.complete).toBeTruthy();}, TIMEOUT);});diff --git a/packages/codemirror/src/type_completion/index.ts b/packages/codemirror/src/type_completion/index.tsindex fe615ed0f5..de4a9f7924 100644--- a/packages/codemirror/src/type_completion/index.ts+++ b/packages/codemirror/src/type_completion/index.ts@@ -1,4 +1,3 @@-import type { CompletionSource } from "@codemirror/autocomplete";import type { Extension } from "@codemirror/state";import { EditorView } from "@codemirror/view";@@ -198,28 +197,38 @@ async function createEnv(mime: string, context: ScriptApiContext = {}) {export interface TypeCompletion {/** Editor extensions wiring the TypeScript environment (sync, lint, hover). */extensions: Extension[];- /** Autocompletion source for the editor's shared `autocompletion()`, or null. */- source: CompletionSource | null;+ /** Looks up the completions at a position, or null for a MIME type with no language service. */+ complete: TypeCompleter | null;+}++/** The completions at `pos`, best first, or null where the language service offers none there. */+export type TypeCompleter =+ (pos: number, explicit: boolean) => Promise<TypeCompletionEntry[] | null>;++/** A completion the TypeScript language service offers. */+export interface TypeCompletionEntry {+ label: string;+ /** The kind of symbol, as CodeMirror names it (`function`, `property`, …). */+ type?: string;}/*** Wires the TypeScript language service into the editor for the given script- * MIME type. The completion `source` is returned separately (rather than as its- * own `autocompletion()` extension) so it can be merged with other sources —- * e.g. snippet slash-commands — into the editor's single autocompletion.+ * MIME type. The completions are returned as a `complete` function rather than an+ * extension, so the host can list them alongside its own entries, such as snippets.*- * Returns empty extensions and a null source for non-script MIME types.+ * Returns empty extensions and a null `complete` for non-script MIME types.** `context` tunes the offered `api` surface per note (e.g. exposing* `req`/`res`/`pathParams` only for custom request handlers).*/export async function buildTypeCompletion(mime: string, context: ScriptApiContext = {}): Promise<TypeCompletion> {if (!isScriptMime(mime)) {- return { extensions: [], source: null };+ return { extensions: [], complete: null };}const env = await createEnv(mime, context);- const [ { tsFacet, tsSync }, { tsAutocomplete }, { tsLinter }, { tsHover } ] = await Promise.all([+ const [ environment, { getAutocompletion }, { tsLinter }, { tsHover } ] = await Promise.all([import("./codemirror-ts/environment.js"),import("./codemirror-ts/autocomplete.js"),import("./codemirror-ts/lint.js"),@@ -228,17 +237,25 @@ export async function buildTypeCompletion(mime: string, context: ScriptApiContex// `tsLinter` only underlines diagnostics inline; `lintGutter` adds the// error/warning markers in the gutter (as the old ESLint integration did).const { lintGutter } = await import("@codemirror/lint");+ const path = scriptPath(mime);return {extensions: [- tsFacet.of({ env, path: scriptPath(mime) }),- tsSync(),+ environment.tsFacet.of({ env, path }),+ environment.tsSync(),tsLinter({ diagnosticCodesToIgnore: ignoredDiagnosticCodes(mime) }),tsHover({ renderTooltip: renderHoverTooltip }),lintGutter(),hoverTheme],- source: tsAutocomplete()+ async complete(pos, explicit) {+ const result = await getAutocompletion({ env, path, context: { pos, explicit } });+ if (!result) return null;++ return [ ...result.options ]+ .sort((a, b) => (b.boost ?? 0) - (a.boost ?? 0))+ .map(({ label, type }) => ({ label, type }));+ }};}