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
Merge branch 'main' of https://github.com/TriliumNext/Trilium into feat/code-embeds-improvements
Adorian Doran70e7268b51fc
diff --cc .claude/skills/developing-content-embeds/SKILL.mdindex b70287d1bd,6cd05ae630..0a80c57489--- a/.claude/skills/developing-content-embeds/SKILL.md+++ b/.claude/skills/developing-content-embeds/SKILL.md@@@ -99,27 -99,6 +99,29 @@@ embeds receive `SourceEmbedProps` (`con- `hasEditableFlag` — shows the Editable toggle; the embed carries `data-editable="true"`.- `hasDisplayModes` — shows Source/Split/Preview; the embed carries `data-display-mode`.- `hiddenToolbarItems` — moves box size, title or convert-to-link from the toolbar to the ⋮ menu.+ - `boxSizeIcon` — an SVG the box size dropdown shows in place of the size name, which moves to+ its tooltip (`Box size: %0`). Code and Markdown embeds set it even while read-only+ (`hasEditableFlag: false`), so every one of them shows the icon; code embeds through+ `useContentEmbedMenus()`.+ - `getMenuItems()` — items of the ⋮ menu after Editable, in a group of their own+ (`useContentEmbedMenus(rootRef, menus, menuItems)` passes them through).+- **A CodeMirror pane in an embed** (code, Markdown, Mermaid) takes its line wrapping and line+ numbers from `useEmbedLines(rootRef, note)` (`code/CodeEmbed.tsx`): pass `wrapLines` /+ `hasLineNumbers` to `EmbedSourcePane` or `CodeEmbedEditor`, and `menuItems` (the _Word wrap_+ and _Line numbers_ submenus) to `getMenuItems()` while the content can be edited. A note keeps+ the wrapping in `#wrapLines`; everything else lives in `data-code-wrap-lines` /+ `data-code-line-numbers`, on the `<pre>` for inline source (the code view command sets only+ line numbers on a note embed). `ReadOnlyText` copies them from the `<pre>` to its box.- - **The `/` list** of a CodeMirror pane is the note's own: `CodeEditor` registers- `useEditorCompletions()` (`code/editor_completions.tsx`) from its `completions` prop, which- `CodeEmbedEditor` passes while it has an `editor`. Snippets of the pane's MIME type for any- language; for Markdown also its commands, `@` and `[[`, which need `ownerNote` (the note an- attachment belongs to) for uploads and new notes. `getEdgeLeftBy()` holds the caret in the- embed while the list is open. Specs that mount an editable Markdown pane mock++- **The `/` list** of a CodeMirror pane is the note's own: `CodeEditor` calls++ `useEditorCompletions()` (`code/editor_completions.tsx`) with its `completions` prop, which++ `CodeEmbedEditor` passes while it has an `editor`. For any language other than Markdown it++ only loads the snippets of the pane's MIME type and hands them to `CodeMirror`'s `getSnippets`,++ which `codeCompletions()` (`code/code_completions.tsx`) lists with the TypeScript completions.++ For Markdown it registers its own list instead: the commands and snippets, `@` and `[[`, which++ need `ownerNote` (the note an attachment belongs to) for uploads and new notes.++ `getEdgeLeftBy()` holds the caret in the embed while either list is open. Specs that mount an editable Markdown pane mock+ `services/task_states`; specs that mount any of them keep `services/i18n` partial+ (`importOriginal`), as `NoteAutocomplete` reads it.- `group` on a tool — a separator goes between groups. Notify listeners only when the toolsreally changed (`MermaidDiagramTools.update()` compares a JSON snapshot) and after the render(`queueMicrotask`), as a listener updates the editor's toolbar.diff --cc apps/client/src/widgets/type_widgets/code/Code.spec.tsxindex 36f43d2874,011075fefa..582ffaae01--- a/apps/client/src/widgets/type_widgets/code/Code.spec.tsx+++ b/apps/client/src/widgets/type_widgets/code/Code.spec.tsx@@@ -9,10 -12,22 +12,25 @@@ import { buildNote } from "../../../tesimport { renderInto } from "../../../test/render";import { ParentComponent } from "../../react/react_utils";import { EditableCode, ReadOnlyCode } from "./Code";+ import type { CodeMirrorProps } from "./CodeMirror";++ // While `deferEditor.on` is set, the editor is created one render after `CodeEditor` mounts, after+ // its effects have run, as in a Mermaid note's split; otherwise the real component renders as is.+ const deferEditor = vi.hoisted(() => ({ on: false }));+ vi.mock("./CodeMirror", async (importOriginal) => {+ const { default: RealCodeMirror } = await importOriginal<typeof import("./CodeMirror")>();+ return {+ default: (props: CodeMirrorProps) => {+ const [ shown, setShown ] = useState(!deferEditor.on);+ useEffect(() => setShown(true), []);+ return shown ? <RealCodeMirror {...props} /> : null;+ }+ };+ });+// The `/` list of a Markdown editor loads the task states from the `_taskStates` subtree.+vi.mock("../../../services/task_states", () => ({ getTaskStateDefinitions: async () => [] }));+describe("EditableCode", () => {const parent = { registerHandler() {}, removeHandler() {}, componentId: "c" } as any;const markdown = { type: "code", mime: "text/x-markdown" } as const;diff --cc apps/client/src/widgets/type_widgets/code/Code.tsxindex bce2ea3e39,24ff0a27d2..454cd32552--- a/apps/client/src/widgets/type_widgets/code/Code.tsx+++ b/apps/client/src/widgets/type_widgets/code/Code.tsx@@@ -177,20 -189,10 +177,21 @@@ export function EditableCode({ note, nt);}- export interface CodeEditorProps extends CodeMirrorProps, Pick<TypeWidgetProps, "ntxId"> {-export function CodeEditor({ ntxId, containerRef: externalContainerRef, editorRef: externalEditorRef, mime, onInitialized, lineWrapping, allowKeyboardSuggestions, ...editorProps }: CodeMirrorProps & Pick<TypeWidgetProps, "ntxId">) {++export interface CodeEditorProps++ extends Omit<CodeMirrorProps, "getSnippets">, Pick<TypeWidgetProps, "ntxId"> {+ /** The content that the `/` list completes, or `undefined` for no list. */+ completions?: CompletionTarget;+}++export function CodeEditor({+ ntxId, containerRef: externalContainerRef, editorRef: externalEditorRef, mime, onInitialized,+ lineWrapping, allowKeyboardSuggestions, completions, ...editorProps+}: CodeEditorProps) {const codeEditorRef = useRef<VanillaCodeMirror>(null);+ const [ view, setView ] = useState<VanillaCodeMirror | null>(null);const containerRef = useSyncedRef(externalContainerRef);const initialized = useRef($.Deferred());- useEditorCompletions(view, mime, completions);++ const getSnippets = useEditorCompletions(view, mime, completions);const [ codeLineWrapEnabled ] = useTriliumOptionBool("codeLineWrapEnabled");const [ codeNoteTheme ] = useTriliumOption("codeNoteTheme");const [ codeNoteTabWidth ] = useTriliumOption("codeNoteTabWidth");@@@ -251,6 -249,6 +248,7 @@@return <CodeMirror{...editorProps}mime={mime}++ getSnippets={getSnippets}editorRef={codeEditorRef}containerRef={containerRef}lineWrapping={lineWrapping ?? codeLineWrapEnabled}diff --cc apps/client/src/widgets/type_widgets/code/CodeMirror.tsxindex 5e9b8d5758,0025963f5d..d60a98d44f--- a/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx+++ b/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx@@@ -17,11 -20,15 +20,15 @@@ export interface CodeMirrorProps extendcustomRequestHandler?: 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, lineNumbers = true, customRequestHandler, bulkActionNote, allowKeyboardSuggestions, ...extraOpts }: CodeMirrorProps) {-export default function CodeMirror({ className, content, mime, editorRef: externalEditorRef, containerRef: externalContainerRef, onInitialized, lineWrapping, customRequestHandler, bulkActionNote, allowKeyboardSuggestions, getSnippets, ...extraOpts }: CodeMirrorProps) {++export default function CodeMirror({ className, content, mime, editorRef: externalEditorRef, containerRef: externalContainerRef, onInitialized, lineWrapping, lineNumbers = true, 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(() => {diff --cc apps/client/src/widgets/type_widgets/code/editor_completions.spec.tsxindex 421362ef15,0000000000..f62d791b57mode 100644,000000..100644--- a/apps/client/src/widgets/type_widgets/code/editor_completions.spec.tsx+++ b/apps/client/src/widgets/type_widgets/code/editor_completions.spec.tsx@@@ -1,288 -1,0 +1,262 @@@+import VanillaCodeMirror from "@triliumnext/codemirror";+import { h, render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type FNote from "../../../entities/fnote";+import type { NoteSuggestionOptions, Suggestion } from "../../../services/note_autocomplete";- import { type CompletionTarget, snippetCommand, useEditorCompletions } from "./editor_completions";++import { type CompletionTarget, useEditorCompletions } from "./editor_completions";+import type { CodeSnippet } from "./snippets";++// The hook's asynchronous sources of menu entries, stubbed so mounting it needs no server.+const { getNoteSuggestions, createNoteFromSuggestion } = vi.hoisted(() => ({+ getNoteSuggestions: vi.fn<+ (term: string, options?: NoteSuggestionOptions) => Promise<Suggestion[]>+ >(async () => []),+ createNoteFromSuggestion: vi.fn<+ (suggestion: Suggestion, childParentNotePath?: string | null) => Promise<string | undefined>+ >()+}));+vi.mock("../../../services/note_autocomplete", async (importOriginal) => ({+ ...await importOriginal<typeof import("../../../services/note_autocomplete")>(),+ getNoteSuggestions,+ createNoteFromSuggestion+}));++const { snippets, useCodeSnippets } = vi.hoisted(() => {+ const ref = { current: [] as CodeSnippet[] };+ return { snippets: ref, useCodeSnippets: vi.fn(() => ref) };+});+vi.mock("./snippets", async (importOriginal) => ({+ ...await importOriginal<typeof import("./snippets")>(),+ useCodeSnippets+}));+vi.mock("../../../services/task_states", () => ({+ getTaskStateDefinitions: () => Promise.resolve([])+}));+// The catalogue is not loaded in specs, and the sample diagrams translate their names as they load.+vi.mock("../../../services/i18n", async (importOriginal) => ({+ ...await importOriginal<typeof import("../../../services/i18n")>(),+ t: (key: string) => key+}));++const MARKDOWN = "text/x-markdown";+const GREETING: CodeSnippet = {+ noteId: "s1", title: "Greeting", description: "Says hello", content: "Hello!"+};+const ALPHA: Suggestion = {+ notePath: "root/projects/abc123",+ noteTitle: "Alpha",+ notePathTitle: "Projects / Alpha",+ highlightedNotePathTitle: "<b>Al</b>pha"+};+const CREATE_AL: Suggestion = {+ action: "create-child-note",+ noteTitle: "Al",+ parentNoteId: "parent",+ highlightedNotePathTitle: "Create child note"+};++describe("useEditorCompletions", () => {+ let container: HTMLElement;+ const editors: VanillaCodeMirror[] = [];++ beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ snippets.current = [];+ getNoteSuggestions.mockClear();+ createNoteFromSuggestion.mockClear();+ });++ afterEach(() => {+ act(() => render(null, container));+ container.remove();+ for (const editor of editors) editor.destroy();+ editors.length = 0;+ });+- /** Mounts the hook against `view`. */++ /** Mounts the hook against `view`, and returns what it gives `codeCompletions()`. */+ function mount(view: VanillaCodeMirror, mime: string, target: CompletionTarget | undefined) {++ let getSnippets: () => CodeSnippet[] = () => [];+ function Probe() {- useEditorCompletions(view, mime, target);++ getSnippets = useEditorCompletions(view, mime, target);+ return null;+ }++ act(() => render(h(Probe, {}), container));++ return () => getSnippets();+ }++ /** A focused editor, which the list opens in. */+ function buildEditor() {+ const parent = document.createElement("div");+ document.body.append(parent);+ const editor = new VanillaCodeMirror({ parent });+ editors.push(editor);+ editor.focus();+ return editor;+ }++ /** Puts `text` in `editor`, the caret at `caret` or at its end. */+ function type(editor: VanillaCodeMirror, text: string, caret = text.length) {+ editor.dispatch({+ changes: { from: 0, to: editor.state.doc.length, insert: text },+ selection: { anchor: caret }+ });+ }++ const rows = () => [+ ...document.querySelectorAll(".note-autocomplete-menu [role=option]")+ ];+ const rowTexts = () => rows().map((row) => row.textContent);+ const onlyRow = (text: string) => [ expect.stringContaining(text) ];+ const press = (editor: VanillaCodeMirror, key: string) => editor.contentDOM.dispatchEvent(+ new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true })+ );+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0));+ const textOf = (editor: VanillaCodeMirror) => editor.state.doc.toString();+- it("registers the list, the fence languages only for Markdown, and withdraws both", () => {++ it("registers the list and the fence languages only for Markdown, and withdraws both", () => {+ const setNamedExtension = vi.fn();+ const setCompletionSource = vi.fn();+ const view = { setNamedExtension, setCompletionSource } as unknown as VanillaCodeMirror;++ mount(view, MARKDOWN, { note: null });+ expect(setNamedExtension)- .toHaveBeenCalledExactlyOnceWith("slashCommands", expect.anything());++ .toHaveBeenCalledExactlyOnceWith("markdownCompletions", expect.anything());+ expect(setCompletionSource)+ .toHaveBeenCalledExactlyOnceWith("markdownCodeFence", expect.any(Function));+ act(() => render(null, container));- expect(setNamedExtension).toHaveBeenLastCalledWith("slashCommands", []);++ expect(setNamedExtension).toHaveBeenLastCalledWith("markdownCompletions", []);+ expect(setCompletionSource).toHaveBeenLastCalledWith("markdownCodeFence", null);++ setNamedExtension.mockClear();+ setCompletionSource.mockClear();+ mount(view, "text/x-python", { note: null });- expect(setNamedExtension)- .toHaveBeenCalledExactlyOnceWith("slashCommands", expect.anything());++ expect(useCodeSnippets).toHaveBeenLastCalledWith("text/x-python", true);+ act(() => render(null, container));- expect(setNamedExtension).toHaveBeenLastCalledWith("slashCommands", []);++ expect(setNamedExtension).not.toHaveBeenCalled();+ expect(setCompletionSource).not.toHaveBeenCalled();++ setNamedExtension.mockClear();+ mount(view, MARKDOWN, undefined);+ expect(setNamedExtension).not.toHaveBeenCalled();+ expect(setCompletionSource).not.toHaveBeenCalled();+ expect(useCodeSnippets).toHaveBeenLastCalledWith(MARKDOWN, false);+ });++ it("lists the Markdown commands and the snippets after a slash, and runs one", async () => {+ snippets.current = [ GREETING ];+ const editor = buildEditor();+ mount(editor, MARKDOWN, { note: { noteId: "n1" } as FNote });++ type(editor, "/tip");+ // Found by its title, without the slash.+ await vi.waitFor(() => expect(rowTexts()).toEqual(onlyRow("titles.tip")));+ expect(rows()[0]?.querySelector("b")?.textContent).toBe("tip");+ // Sized as the text editor's `/` list is.+ expect(document.querySelector(".note-autocomplete-menu.slash-command-menu")).not.toBeNull();++ // Opened on the best match, so Enter runs it.+ press(editor, "Enter");+ await vi.waitFor(() => expect(textOf(editor)).toBe("> [!TIP]\n> "));+ await vi.waitFor(() => expect(rows()).toEqual([]));++ type(editor, "/greet");+ await vi.waitFor(() => expect(rowTexts()).toEqual(onlyRow("Greeting")));+ press(editor, "Enter");+ await vi.waitFor(() => expect(textOf(editor)).toBe("Hello!"));+ });+- it("lists only the snippets in a code editor, without the note being edited", async () => {++ it("gives a code editor's snippets to its own list, without the note being edited", async () => {+ const editor = buildEditor();- mount(editor, "text/x-python", { note: { noteId: "s2" } as FNote });-- type(editor, "/");- await settle();- expect(rows()).toEqual([]);++ const getSnippets = mount(editor, "text/x-python", { note: { noteId: "s2" } as FNote });++ expect(getSnippets()).toEqual([]);++ snippets.current = [ GREETING, { noteId: "s2", title: "Itself", content: "x" } ];- type(editor, "a /");- await vi.waitFor(() => expect(rowTexts()).toEqual(onlyRow("Greeting")));- // `/snippet` lists every snippet, as in the text editor.- type(editor, "a /snippet");- await vi.waitFor(() => expect(rows()).toHaveLength(1));- press(editor, "Enter");- await vi.waitFor(() => expect(textOf(editor)).toBe("a Hello!"));++ expect(getSnippets()).toEqual([ GREETING ]);++ // A code editor offers no note lists.+ type(editor, "@Al");+ await settle();+ expect(rows()).toEqual([]);+ expect(getNoteSuggestions).not.toHaveBeenCalled();++++ // A Markdown editor lists them with its commands instead.++ act(() => render(null, container));++ expect(mount(editor, MARKDOWN, { note: null })()).toEqual([]);+ });++ it("lists the notes after an @ or a [[, and links the one picked or created", async () => {+ getNoteSuggestions.mockResolvedValue([ ALPHA, CREATE_AL ]);+ const editor = buildEditor();+ mount(editor, MARKDOWN, {+ note: { noteId: "n1" } as FNote, getNotePath: () => "root/parent"+ });++ type(editor, "see @Al");+ await vi.waitFor(() => expect(rows()).toHaveLength(2));+ // At most ten notes, and creation under the note being edited.+ expect(getNoteSuggestions)+ .toHaveBeenLastCalledWith("Al", { allowCreatingNotes: true, limit: 10 });++ // Opened on the best match, so Enter links it.+ press(editor, "Enter");+ await vi.waitFor(() => expect(textOf(editor)).toBe("see [[abc123]]"));++ // A note created is linked once it exists, past the dialog taking the focus.+ let created: (notePath: string | undefined) => void = () => {};+ createNoteFromSuggestion.mockReturnValueOnce(new Promise((resolve) => {+ created = resolve;+ }));+ type(editor, "see [[abc123]] @Al");+ await vi.waitFor(() => expect(rows()).toHaveLength(2));+ press(editor, "ArrowDown");+ await settle();+ press(editor, "Enter");+ await vi.waitFor(() => expect(createNoteFromSuggestion).toHaveBeenCalledWith(+ expect.objectContaining({ action: "create-child-note" }), "root/parent"+ ));+ editor.contentDOM.blur();+ created("root/parent/new1");+ await vi.waitFor(() => expect(textOf(editor)).toBe("see [[abc123]] [[new1]]"));++ // After [[ the same list opens, and a pick in a link already closed takes its brackets too.+ editor.focus();+ type(editor, "see [[Al");+ await vi.waitFor(() => expect(rows()).toHaveLength(2));+ press(editor, "Enter");+ await vi.waitFor(() => expect(textOf(editor)).toBe("see [[abc123]]"));+ type(editor, "see [[Al]] x", 8);+ await vi.waitFor(() => expect(rows()).toHaveLength(2));+ press(editor, "Enter");+ await vi.waitFor(() => expect(textOf(editor)).toBe("see [[abc123]] x"));+ expect(editor.state.selection.main.head).toBe(14);++ // So does a note created there, once it exists.+ createNoteFromSuggestion.mockResolvedValueOnce("root/parent/new2");+ type(editor, "see [[Al]] x", 8);+ await vi.waitFor(() => expect(rows()).toHaveLength(2));+ press(editor, "ArrowDown");+ await settle();+ press(editor, "Enter");+ await vi.waitFor(() => expect(textOf(editor)).toBe("see [[new2]] x"));+ });++ it("creates notes under the best path of the owner note without a path given", async () => {+ getNoteSuggestions.mockResolvedValue([ CREATE_AL ]);+ createNoteFromSuggestion.mockResolvedValueOnce(undefined);+ const owner = {+ noteId: "owner", getBestNotePathString: () => "root/owner"+ } as unknown as FNote;+ const editor = buildEditor();+ mount(editor, MARKDOWN, { note: null, ownerNote: owner });++ type(editor, "@Al");+ await vi.waitFor(() => expect(rows()).toHaveLength(1));+ press(editor, "Enter");+ await vi.waitFor(() => expect(createNoteFromSuggestion)+ .toHaveBeenLastCalledWith(expect.anything(), "root/owner"));+ });+});-- describe("snippetCommand", () => {- it("lists a snippet by its title, also after /snippet, and inserts its content", () => {- const entry = snippetCommand(GREETING);- expect(entry).toMatchObject({- id: "snippet:Greeting",- title: "Greeting",- description: "Says hello",- aliases: [ "snippet:Greeting", "snippet", "template" ],- icon: "bx bx-code-curly"- });-- const parent = document.createElement("div");- document.body.append(parent);- const editor = new VanillaCodeMirror({ parent });- editor.dispatch({ changes: { from: 0, insert: "Hi /snip" }, selection: { anchor: 8 } });- entry.apply(editor, 3, 8);- expect(editor.state.doc.toString()).toBe("Hi Hello!");- expect(editor.state.selection.main.head).toBe(9);- editor.destroy();- });- });diff --cc apps/client/src/widgets/type_widgets/code/editor_completions.tsxindex 12818f6e29,0000000000..3c44a64be8mode 100644,000000..100644--- a/apps/client/src/widgets/type_widgets/code/editor_completions.tsx+++ b/apps/client/src/widgets/type_widgets/code/editor_completions.tsx@@@ -1,169 -1,0 +1,144 @@@+import type VanillaCodeMirror from "@triliumnext/codemirror";+import {+ hostedCompletion, type HostedCompletionApply, type HostedCompletionState+} from "@triliumnext/codemirror/src/extensions/hosted_completion";+import { isMarkdownMime, type TaskStateDef } from "@triliumnext/commons";- import { useEffect, useRef } from "preact/hooks";++import { useCallback, useEffect, useRef } from "preact/hooks";++import type FNote from "../../../entities/fnote";+import { getTaskStateDefinitions } from "../../../services/task_states";+import {+ type CommandEntry, CommandMentionList, createHostedList, filterCommandEntries, NoteMentionList+} from "../../react/NoteAutocomplete";+import {+ buildMarkdownCommands, codeFenceCompletionSource, linkToNote, markdownCompletionAt+} from "../markdown/completions";- import { type CodeSnippet, SLASH_COMMAND_REGEX, useCodeSnippets } from "./snippets";++import { type CodeSnippet, snippetCommand, useCodeSnippets } from "./snippets";++/** A `/` command of a code editor, listed as the text editor lists its own. */+export interface SlashCommand extends CommandEntry {+ /** Runs the command on the typed `/command`, from `from` to the caret at `to`. */+ apply: HostedCompletionApply;+}++/** A `/command` or a note typed before the caret, from its `/`, its `@` or its `[[`. */+export interface CompletionMatch {+ kind: "command" | "note";+ from: number;+ /** What follows the `/`, the `@` or the `[[`, which the list filters by. */+ query: string;+}++/** The content that a code editor completes. */+export interface CompletionTarget {+ /** The note being edited, which its own `/` list leaves out, or `null` for other content. */+ note: FNote | null;+ /** The note that images upload to and new notes go under. `note` by default. */+ ownerNote?: FNote | null;+ /** The path that new notes go under. The best path of the owner note by default. */+ getNotePath?(): string | null | undefined;+}++/**- * Registers the `/` list of `view`, drawn as the text editor's: the code snippets for `mime`, and- * for Markdown its commands, the notes typed after `@` or `[[`, and the code-fence languages.- * Nothing registers while `target` is `undefined`.++ * Loads the code snippets for `mime` and returns them, without the note being edited, for++ * `codeCompletions()` to list after a `/`. For Markdown, registers the `/` list of `view` instead,++ * drawn as the text editor's: its commands and the snippets, the notes typed after `@` or `[[`,++ * and the code-fence languages. Nothing loads or registers while `target` is `undefined`.+ */+export function useEditorCompletions(+ view: VanillaCodeMirror | null,+ mime: string,+ target: CompletionTarget | undefined- ) {++): () => CodeSnippet[] {+ const isEnabled = target !== undefined;+ const isMarkdown = isMarkdownMime(mime);+ // Read when the list opens, as switching notes reuses the editor.+ const targetRef = useRef(target);+ targetRef.current = target;+ const snippetsRef = useCodeSnippets(mime, isEnabled);+ const taskStatesRef = useRef<TaskStateDef[]>([]);++ const getSnippets = useCallback(() => snippetsRef.current.filter(++ (snippet) => snippet.noteId !== targetRef.current?.note?.noteId++ ), [ snippetsRef ]);++ useEffect(() => {+ if (!isEnabled || !isMarkdown) return;+ void getTaskStateDefinitions().then((states) => { taskStatesRef.current = states; });+ }, [ isEnabled, isMarkdown ]);++ useEffect(() => {- if (!view || !isEnabled) return;++ if (!view || !isEnabled || !isMarkdown) return;++ const getOwnerNote = () => targetRef.current?.ownerNote ?? targetRef.current?.note ?? null;+ const getNotePath = () => (+ targetRef.current?.getNotePath?.() ?? getOwnerNote()?.getBestNotePathString()+ );+ const commands = (): SlashCommand[] => [- ...(isMarkdown ? buildMarkdownCommands({++ ...buildMarkdownCommands({+ editorView: view, getOwnerNote, taskStates: taskStatesRef.current- }) : []),- ...snippetsRef.current- .filter((snippet) => snippet.noteId !== targetRef.current?.note?.noteId)- .map(snippetCommand)++ }),++ ...getSnippets().map(snippetCommand)+ ];- const codeCommandAt = (before: string): CompletionMatch | null => {- const typed = COMMAND_TYPED.exec(before);- if (!typed || commands().length === 0) return null;- return { kind: "command", from: typed.index, query: typed[0].slice(1) };- };- const match: typeof markdownCompletionAt = isMarkdown- ? markdownCompletionAt- : codeCommandAt;++ // Bridges the codemirror package's own @codemirror/state identity.+ type CmMatcher = Parameters<typeof hostedCompletion<CompletionMatch>>[0]["match"];- view.setNamedExtension("slashCommands", hostedCompletion({- match: match as unknown as CmMatcher,++ view.setNamedExtension("markdownCompletions", hostedCompletion({++ match: markdownCompletionAt as unknown as CmMatcher,+ list: () => createCompletionList(commands, getNotePath)+ }));- if (!isMarkdown) {- return () => view.setNamedExtension("slashCommands", []);- }-+ // CodeMirror allows one `override` config per editor, so the fence languages go through+ // `setCompletionSource()`. Bridges the package's own @codemirror/autocomplete identity.+ type CmCompletionSource = Parameters<VanillaCodeMirror["setCompletionSource"]>[1];+ view.setCompletionSource(+ "markdownCodeFence", codeFenceCompletionSource as unknown as CmCompletionSource+ );+ return () => {- view.setNamedExtension("slashCommands", []);++ view.setNamedExtension("markdownCompletions", []);+ view.setCompletionSource("markdownCodeFence", null);+ };- }, [ view, isEnabled, isMarkdown ]);- }-- const COMMAND_TYPED = new RegExp(`${SLASH_COMMAND_REGEX.source}$`);++ }, [ view, isEnabled, isMarkdown, getSnippets ]);+- /** The entry of `snippet` in the `/` list, which puts its content in place of the typed command. */- export function snippetCommand(snippet: CodeSnippet): SlashCommand {- 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 }- });- }- };++ // A Markdown editor lists the snippets with its commands.++ return isMarkdown ? noSnippets : getSnippets;+}+++const noSnippets = (): CodeSnippet[] => [];+++/**+ * The `/` list or the `@` list, drawn as the text editor's: the first runs the command picked on+ * the typed `/command`, the second puts a link to the note picked or created in place of the typed+ * note. A note created goes under `getNotePath()`.+ */+function createCompletionList(+ commands: () => SlashCommand[],+ getNotePath: () => string | null | undefined+) {+ return createHostedList<HostedCompletionState<CompletionMatch>>((state, list) => {+ const { kind, from, query } = state.match;+ if (kind === "note") {+ return (+ <NoteMentionList+ key={`note:${from}`}+ {...list}+ query={query}+ allowCreatingNotes+ parentNotePath={getNotePath()}+ onPick={(notePath) => state.commit(typeof notePath === "string"+ ? linkToNote(notePath)+ : notePath.then((path) => path ? linkToNote(path) : undefined))}+ />+ );+ }++ return (+ <CommandMentionList<SlashCommand>+ key={`command:${from}`}+ {...list}+ query={query}+ source={async (typed) => filterCommandEntries(commands(), typed)}+ className="slash-command-menu"+ onPick={(entry) => state.commit(entry.apply)}+ />+ );+ });+}diff --cc apps/client/src/widgets/type_widgets/code/snippets.spec.tsindex 17ca2c91f9,aea1d09b6a..0459d6bb74--- a/apps/client/src/widgets/type_widgets/code/snippets.spec.ts+++ b/apps/client/src/widgets/type_widgets/code/snippets.spec.ts@@@ -9,9 -8,9 +9,9 @@@ vi.mock("../../../services/search.js",}));import search from "../../../services/search.js";-import { getCodeSnippets, isCodeSnippetChange, snippetCommand } from "./snippets.js";--const logErrorMock = vi.fn();+import * as ws from "../../../services/ws.js";+import { buildNote } from "../../../test/easy-froca";- import { getCodeSnippets, isCodeSnippetChange, isSnippetFor } from "./snippets.js";++import { getCodeSnippets, isCodeSnippetChange, isSnippetFor, snippetCommand } from "./snippets.js";interface NoteStub {noteId: string;@@@ -48,26 -47,32 +48,52 @@@ function makeLoadResults(opts:} as unknown as LoadResults;}+describe("isSnippetFor", () => {+ it("offers code of the same language, any Markdown to Markdown, and plain text to all", () => {+ const snippet = (mime: string, type: NoteType = "code") => (+ buildNote({ title: mime, type, mime })+ );+ const css = snippet("text/css");+ const markdown = snippet("text/markdown");+ const plain = snippet("text/plain");++ expect(isSnippetFor(css, "text/css")).toBe(true);+ expect(isSnippetFor(css, "text/x-python")).toBe(false);+ expect(isSnippetFor(markdown, "text/x-markdown")).toBe(true);+ expect(isSnippetFor(markdown, "text/css")).toBe(false);+ expect(isSnippetFor(css, "text/x-markdown")).toBe(false);+ expect(isSnippetFor(plain, "text/x-markdown")).toBe(true);+ expect(isSnippetFor(plain, "text/css")).toBe(true);+ expect(isSnippetFor(snippet("text/plain", "text"), "text/css")).toBe(false);+ });+});++ 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(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 dispatched: unknown[] = [];+ 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" },+ selection: { anchor: 3 + "the footer".length }+ }]);+ });+ });+describe("isCodeSnippetChange", () => {const known = new Set(["s1"]);diff --cc apps/client/src/widgets/type_widgets/code/snippets.tsindex d45aebb1b1,3241fea629..f55e8bd5e9--- a/apps/client/src/widgets/type_widgets/code/snippets.ts+++ b/apps/client/src/widgets/type_widgets/code/snippets.ts@@@ -1,11 -1,13 +1,15 @@@+ import type {+ HostedCompletionApply+ } from "@triliumnext/codemirror/src/extensions/hosted_completion";+import { isMarkdownMime } from "@triliumnext/commons";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 { logError } from "../../../services/ws.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:-]*/;@@@ -71,22 -63,37 +75,46 @@@ export function isCodeSnippetChange(loareturn attributeChanged || loadResults.getNoteIds().some((noteId) => knownNoteIds.has(noteId));}+/**+ * Whether the snippet note `candidate` can be inserted into content of `mime`: a code note of the+ * same language, of any Markdown MIME type for Markdown, or of plain text.+ */+export function isSnippetFor(candidate: FNote, mime: string) {+ if (candidate.type !== "code") return false;+ if (candidate.mime === "text/plain") return true;+ return isMarkdownMime(mime) ? candidate.isMarkdown() : candidate.mime === mime;+}++ /**+ * 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 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- * ref so consumers (a slash menu) read the latest list when invoked, without re-registering anything.- * When `enabled` is false the ref stays empty and nothing is loaded.+ * Loads the snippets for content of `mime` into a ref and keeps it fresh: reloaded on mount, when+ * `mime` changes, and when relevant entities change. Held in a ref so a `/` list reads the latest+ * list when it opens, without registering anything again. Nothing loads while `isEnabled` is false.*/-export function useCodeSnippets(matches: (note: FNote) => boolean, reloadKey: string, enabled = true) {+export function useCodeSnippets(mime: string, isEnabled = true) {const snippetsRef = useRef<CodeSnippet[]>([]);// Monotonic id so a slow fetch that resolves after a newer reload is discarded (avoids stale data).const reloadCountRef = useRef(0);diff --cc apps/server/src/assets/help/help_content.jsonindex dc60c97a41,d1b9d50366..46167be945--- a/apps/server/src/assets/help/help_content.json+++ b/apps/server/src/assets/help/help_content.json@@@ -205,7 -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>/</code> followed by the start of its title, or <code>/snippet</code> to list all of them, and pick it from the list. This also works in an included code or Markdown note that is being edited in place, see <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</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_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. This also works in an included code or Markdown note that is being edited in place, see <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</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>Syntax highlight with line numbers, in the language of the note and in the colors of the VS Code light or dark theme, following the page's mode. A language not enabled in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em> is not highlighted.</li></ul></td><td> </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>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>",diff --cc docs/User Guide/User Guide/Advanced Usage/Snippets/Code Snippets.mdindex 1938ea3322,7076ed42fe..16babcc012--- 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 +15,7 @@@ The note's title becomes the title of t## Inserting a snippet- To insert a snippet, type `/` followed by the start of its title, or `/snippet` to list all of them, and pick it from the list. This also works in an included code or Markdown note that is being edited in place, see <a class="reference-link" href="../../Note%20Types/Text/Include%20Note.md">Include Note</a>.-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.++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. This also works in an included code or Markdown note that is being edited in place, see <a class="reference-link" href="../../Note%20Types/Text/Include%20Note.md">Include Note</a>.> [!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.