Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/code embed: rework slash commands to make them available in code embeds

Adorian Doranac5cbd964c2b
diff --git a/.claude/skills/developing-content-embeds/SKILL.md b/.claude/skills/developing-content-embeds/SKILL.md
index b1fff0b2df..10eef3ceb6 100644
--- a/.claude/skills/developing-content-embeds/SKILL.md
+++ b/.claude/skills/developing-content-embeds/SKILL.md
@@ -108,6 +108,14 @@ embeds receive `SourceEmbedProps` (`content`, `editor`) whichever storage the so
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
+ `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 tools
really changed (`MermaidDiagramTools.update()` compares a JSON snapshot) and after the render
(`queueMicrotask`), as a listener updates the editor's toolbar.
diff --git a/apps/client/src/widgets/type_widgets/code/Code.spec.tsx b/apps/client/src/widgets/type_widgets/code/Code.spec.tsx
index f71ed03ff2..36f43d2874 100644
--- a/apps/client/src/widgets/type_widgets/code/Code.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/code/Code.spec.tsx
@@ -10,6 +10,9 @@ import { renderInto } from "../../../test/render";
import { ParentComponent } from "../../react/react_utils";
import { EditableCode, ReadOnlyCode } from "./Code";
+// 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 --git a/apps/client/src/widgets/type_widgets/code/Code.tsx b/apps/client/src/widgets/type_widgets/code/Code.tsx
index a60e863a50..bce2ea3e39 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 { type CompletionTarget, useEditorCompletions } from "./editor_completions";
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,24 +146,13 @@ export function EditableCode({ note, ntxId, noteContext, debounceUpdate, parentC
useKeyboardShortcuts("code-detail", containerRef, parentComponent, ntxId);
- // Code snippets (#snippet notes with a matching MIME) as `/snippet:<name>` slash commands.
- // Disabled for Markdown notes, whose editor provides its own combined slash-command menu. 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,
- (candidate) => candidate.type === "code" && (candidate.mime === note.mime || candidate.mime === "text/plain"),
- note.mime,
- !note.isMarkdown(),
- note.noteId
- );
-
return (
<>
<CodeEditor
ntxId={ntxId}
editorRef={combinedEditorRef} containerRef={containerRef}
mime={mime ?? "text/plain"}
+ completions={{ note, getNotePath: () => noteContext?.notePath }}
customRequestHandler={customRequestHandler != null}
className="note-detail-code-editor"
placeholder={placeholder ?? t("editable_code.placeholder")}
@@ -190,10 +177,20 @@ export function EditableCode({ note, ntxId, noteContext, debounceUpdate, parentC
);
}
-export function CodeEditor({ ntxId, containerRef: externalContainerRef, editorRef: externalEditorRef, mime, onInitialized, lineWrapping, allowKeyboardSuggestions, ...editorProps }: CodeMirrorProps & Pick<TypeWidgetProps, "ntxId">) {
+export interface CodeEditorProps extends CodeMirrorProps, 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 [ codeLineWrapEnabled ] = useTriliumOptionBool("codeLineWrapEnabled");
const [ codeNoteTheme ] = useTriliumOption("codeNoteTheme");
const [ codeNoteTabWidth ] = useTriliumOption("codeNoteTabWidth");
@@ -209,7 +206,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);
@@ -269,6 +266,7 @@ export function CodeEditor({ ntxId, containerRef: externalContainerRef, editorRe
if (typeof externalEditorRef === "function") externalEditorRef(codeEditorRef.current);
else if (externalEditorRef) externalEditorRef.current = codeEditorRef.current;
}
+ setView(codeEditorRef.current);
initialized.current.resolve();
onInitialized?.();
}}
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
index 61e269d272..67517e4398 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
@@ -13,6 +13,7 @@ import type { ContentEditor } from "../../../services/content_renderer";
import froca from "../../../services/froca";
import LoadResults from "../../../services/load_results";
import options from "../../../services/options";
+import search from "../../../services/search";
import {
buildCodeViewTextEditor, getEmbedMenuItems, runEmbedMenuItem, summarizeMenuItem
} from "../../../test/content_embed";
@@ -34,7 +35,8 @@ const renderCodePreview = vi.hoisted(() => vi.fn(
}
));
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
}));
@@ -88,6 +90,34 @@ describe("CodeEmbed", () => {
expect(getContent()).toBe("# print(1)");
});
+ it("lists the snippets of its language after a slash while the toggle is on", async () => {
+ const snippet = buildNote({
+ title: "Greeting", type: "code", mime: "text/x-python", content: "print('hi')"
+ });
+ const searchForNotes = vi.spyOn(search, "searchForNotes").mockResolvedValue([ snippet ]);
+ const { figure } = await mount(buildCodeNote(""), buildEditor(), { isEditable: true });
+ const view = await findView(figure);
+ expect(searchForNotes).toHaveBeenCalledWith("#snippet");
+
+ view.focus();
+ const rows = () => [
+ ...document.querySelectorAll(".note-autocomplete-menu [role=option]")
+ ];
+ // Typed again until the snippets have loaded, as a list opens only where it has entries.
+ await vi.waitFor(() => {
+ act(() => view.dispatch({
+ changes: { from: 0, to: view.state.doc.length, insert: "/" },
+ selection: { anchor: 1 }
+ }));
+ expect(rows().map((row) => row.textContent))
+ .toEqual([ expect.stringContaining("Greeting") ]);
+ });
+ view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", {
+ key: "Enter", bubbles: true, cancelable: true
+ }));
+ await vi.waitFor(() => expect(view.state.doc.toString()).toBe("print('hi')"));
+ });
+
it("lets the find search the editor while the toggle is on", async () => {
const { figure } = await mount(buildCodeNote("print(1)\nprint(2)"), buildEditor(), {
isEditable: true
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
index 5000917f4b..bbf518d20e 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
@@ -101,6 +101,7 @@ export default function CodeEmbed({
>
<CodeEmbedEditor
note={note}
+ ownerNote={entity instanceof FNote ? entity : entity.getNote()}
editor={editor}
content={content}
mime={mime}
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
index 4e5b0f32a4..8d28fe8bd2 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
@@ -12,6 +12,8 @@ import { CodeEditor } from "./Code";
export interface CodeEmbedEditorProps {
note: FNote | null;
+ /** The note that holds an attachment, which images upload to and new notes go under. */
+ ownerNote?: FNote | null;
/** Saves the edits, or `undefined` to show the content read-only. */
editor: ContentEditor | undefined;
content: string;
@@ -41,7 +43,7 @@ export interface CodeEmbedEditorProps {
* `editor`, the content is read-only.
*/
export default function CodeEmbedEditor({
- note, editor, content, mime, tabWidth, useTabs, wrapLines, hasLineNumbers, viewRef,
+ note, ownerNote, editor, content, mime, tabWidth, useTabs, wrapLines, hasLineNumbers, viewRef,
isShown = true, onClose, onChange, onReady
}: CodeEmbedEditorProps) {
const isLoadingRef = useRef(false);
@@ -101,6 +103,7 @@ export default function CodeEmbedEditor({
editorRef={viewRef}
className="code-embed-editor"
mime={mime}
+ completions={editor && { note, ownerNote }}
vimKeybindings={vimKeymapEnabled}
readOnly={!editor}
lineNumbers={hasLineNumbers}
diff --git a/apps/client/src/widgets/type_widgets/code/editor_completions.spec.tsx b/apps/client/src/widgets/type_widgets/code/editor_completions.spec.tsx
new file mode 100644
index 0000000000..421362ef15
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/code/editor_completions.spec.tsx
@@ -0,0 +1,288 @@
+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 { 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`. */
+ function mount(view: VanillaCodeMirror, mime: string, target: CompletionTarget | undefined) {
+ function Probe() {
+ useEditorCompletions(view, mime, target);
+ return null;
+ }
+
+ act(() => render(h(Probe, {}), container));
+ }
+
+ /** 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", () => {
+ 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());
+ expect(setCompletionSource)
+ .toHaveBeenCalledExactlyOnceWith("markdownCodeFence", expect.any(Function));
+ act(() => render(null, container));
+ expect(setNamedExtension).toHaveBeenLastCalledWith("slashCommands", []);
+ expect(setCompletionSource).toHaveBeenLastCalledWith("markdownCodeFence", null);
+
+ setNamedExtension.mockClear();
+ setCompletionSource.mockClear();
+ mount(view, "text/x-python", { note: null });
+ expect(setNamedExtension)
+ .toHaveBeenCalledExactlyOnceWith("slashCommands", expect.anything());
+ act(() => render(null, container));
+ expect(setNamedExtension).toHaveBeenLastCalledWith("slashCommands", []);
+ 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 () => {
+ const editor = buildEditor();
+ mount(editor, "text/x-python", { note: { noteId: "s2" } as FNote });
+
+ type(editor, "/");
+ await settle();
+ expect(rows()).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!"));
+
+ // A code editor offers no note lists.
+ type(editor, "@Al");
+ await settle();
+ expect(rows()).toEqual([]);
+ expect(getNoteSuggestions).not.toHaveBeenCalled();
+ });
+
+ 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 --git a/apps/client/src/widgets/type_widgets/code/editor_completions.tsx b/apps/client/src/widgets/type_widgets/code/editor_completions.tsx
new file mode 100644
index 0000000000..12818f6e29
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/code/editor_completions.tsx
@@ -0,0 +1,169 @@
+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 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";
+
+/** 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`.
+ */
+export function useEditorCompletions(
+ view: VanillaCodeMirror | null,
+ mime: string,
+ target: CompletionTarget | undefined
+) {
+ 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[]>([]);
+
+ useEffect(() => {
+ if (!isEnabled || !isMarkdown) return;
+ void getTaskStateDefinitions().then((states) => { taskStatesRef.current = states; });
+ }, [ isEnabled, isMarkdown ]);
+
+ useEffect(() => {
+ if (!view || !isEnabled) return;
+
+ const getOwnerNote = () => targetRef.current?.ownerNote ?? targetRef.current?.note ?? null;
+ const getNotePath = () => (
+ targetRef.current?.getNotePath?.() ?? getOwnerNote()?.getBestNotePathString()
+ );
+ const commands = (): SlashCommand[] => [
+ ...(isMarkdown ? buildMarkdownCommands({
+ editorView: view, getOwnerNote, taskStates: taskStatesRef.current
+ }) : []),
+ ...snippetsRef.current
+ .filter((snippet) => snippet.noteId !== targetRef.current?.note?.noteId)
+ .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,
+ 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.setCompletionSource("markdownCodeFence", null);
+ };
+ }, [ view, isEnabled, isMarkdown ]);
+}
+
+const COMMAND_TYPED = new RegExp(`${SLASH_COMMAND_REGEX.source}$`);
+
+/** 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 }
+ });
+ }
+ };
+}
+
+/**
+ * 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 --git a/apps/client/src/widgets/type_widgets/code/snippets.spec.ts b/apps/client/src/widgets/type_widgets/code/snippets.spec.ts
index 78d6434d24..17ca2c91f9 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,4 @@
-import type { Completion } from "@codemirror/autocomplete";
-import type { EditorView } from "@codemirror/view";
+import type { NoteType } from "@triliumnext/commons";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type FNote from "../../../entities/fnote";
@@ -10,9 +9,9 @@ vi.mock("../../../services/search.js", () => ({
}));
import search from "../../../services/search.js";
-import { buildSnippetCompletions, getCodeSnippets, isCodeSnippetChange } 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";
interface NoteStub {
noteId: string;
@@ -49,29 +48,23 @@ 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" }
- ]);
-
- expect(withDesc?.label).toBe("/snippet:Header - Page header");
- expect(withoutDesc?.label).toBe("/snippet:Footer");
-
- // 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);
-
- expect(dispatched).toEqual([{
- changes: { from: 3, to: 11, insert: "the footer" },
- selection: { anchor: 3 + "the footer".length }
- }]);
+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);
});
});
@@ -97,8 +90,6 @@ describe("isCodeSnippetChange", () => {
describe("getCodeSnippets", () => {
beforeEach(() => {
vi.mocked(search.searchForNotes).mockReset();
- logErrorMock.mockReset();
- vi.stubGlobal("logError", logErrorMock);
});
it("maps matching notes, reading the description from #snippetDescription", async () => {
@@ -141,10 +132,25 @@ describe("getCodeSnippets", () => {
expect(snippet?.content).toBe("");
});
+ it("shares one search between loads at the same time, and searches again later", async () => {
+ vi.mocked(search.searchForNotes).mockResolvedValue([ makeNote({ noteId: "css1" }) ]);
+
+ const [ first, second ] = await Promise.all([
+ getCodeSnippets(() => true), getCodeSnippets(() => true)
+ ]);
+ expect(search.searchForNotes).toHaveBeenCalledOnce();
+ expect([ first, second ].map((snippets) => snippets.length)).toEqual([ 1, 1 ]);
+
+ await getCodeSnippets(() => true);
+ expect(search.searchForNotes).toHaveBeenCalledTimes(2);
+ });
+
it("returns an empty list and logs when loading fails", async () => {
vi.mocked(search.searchForNotes).mockRejectedValue(new Error("boom"));
+ const logError = vi.spyOn(ws, "logError");
expect(await getCodeSnippets(() => true)).toEqual([]);
- expect(logErrorMock).toHaveBeenCalled();
+ expect(logError).toHaveBeenCalled();
+ logError.mockRestore();
});
});
diff --git a/apps/client/src/widgets/type_widgets/code/snippets.ts b/apps/client/src/widgets/type_widgets/code/snippets.ts
index 64a2317663..d45aebb1b1 100644
--- a/apps/client/src/widgets/type_widgets/code/snippets.ts
+++ b/apps/client/src/widgets/type_widgets/code/snippets.ts
@@ -1,11 +1,10 @@
-import { type Completion, type CompletionContext, type CompletionSource } from "@codemirror/autocomplete";
-import type { EditorView } from "@codemirror/view";
-import type VanillaCodeMirror from "@triliumnext/codemirror";
+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";
/** Matches a `/command` token at the start of a line or after whitespace. Shared by every editor. */
@@ -28,7 +27,7 @@ export async function getCodeSnippets(matches: (note: FNote) => boolean): Promis
try {
// The `search` route includes archived notes, so drop archived ones; also skip protected
// snippets whose content isn't available (no active protected session) — they can't be inserted.
- const notes = (await search.searchForNotes("#snippet"))
+ const notes = (await searchSnippetNotes())
.filter((note) => matches(note) && !note.isArchived && note.isContentAvailable());
return await Promise.all(notes.map(async (note) => ({
@@ -38,11 +37,21 @@ export async function getCodeSnippets(matches: (note: FNote) => boolean): Promis
content: (await note.getContent()) ?? ""
})));
} catch (e) {
- logError("Error while building code snippets: ", e);
+ logError(`Error while building code snippets: ${e}`);
return [];
}
}
+/** The `#snippet` notes. Editors that load them at the same time share one search. */
+function searchSnippetNotes() {
+ pendingSearch ??= search.searchForNotes("#snippet").finally(() => {
+ pendingSearch = null;
+ });
+ return pendingSearch;
+}
+
+let pendingSearch: Promise<FNote[]> | null = null;
+
/**
* Whether the reloaded entities could change the snippet list — a snippet was created, deleted,
* retitled, had its description changed, or its content edited. `knownNoteIds` are the note IDs of
@@ -63,55 +72,42 @@ 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.
+ * 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 buildSnippetCompletions(snippets: CodeSnippet[]): Completion[] {
- return snippets.map((snippet) => ({
- label: snippet.description
- ? `/snippet:${snippet.title} - ${snippet.description}`
- : `/snippet:${snippet.title}`,
- apply(view: EditorView, _completion: Completion, from: number, to: number) {
- view.dispatch({
- changes: { from, to, insert: snippet.content },
- selection: { anchor: from + snippet.content.length }
- });
- }
- }));
+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;
}
/**
- * 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);
- // Keep the latest predicate without making it a dependency (it's a fresh closure each render);
- // `reloadKey` is the stable trigger for filter changes.
- const matchesRef = useRef(matches);
- useEffect(() => { matchesRef.current = matches; });
const reload = useCallback(() => {
- if (!enabled) {
+ const reloadId = ++reloadCountRef.current;
+ if (!isEnabled) {
snippetsRef.current = [];
return;
}
- const reloadId = ++reloadCountRef.current;
- void getCodeSnippets((note) => matchesRef.current(note)).then((snippets) => {
+ void getCodeSnippets((note) => isSnippetFor(note, mime)).then((snippets) => {
if (reloadId === reloadCountRef.current) {
snippetsRef.current = snippets;
}
});
- }, [enabled]);
+ }, [isEnabled, mime]);
- useEffect(() => { reload(); }, [reload, reloadKey]);
+ useEffect(() => { reload(); }, [reload]);
useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
- if (!enabled) return;
+ if (!isEnabled) return;
const knownNoteIds = new Set(snippetsRef.current.map((snippet) => snippet.noteId));
if (isCodeSnippetChange(loadResults, knownNoteIds)) {
reload();
@@ -119,49 +115,4 @@ export function useCodeSnippets(matches: (note: FNote) => boolean, reloadKey: st
});
return snippetsRef;
-}
-
-/**
- * Registers a `/snippet:<name>` slash command on a CodeMirror code editor, listing the snippets
- * accepted by `matches` (e.g. those whose MIME equals the editor note's). Inserting one drops its
- * content at the cursor. No-op when `enabled` is false (e.g. the Markdown editor, which builds its
- * own combined slash-command menu instead).
- */
-export function useSnippetSlashCommands(editorView: VanillaCodeMirror | null, matches: (note: FNote) => boolean, reloadKey: string, enabled: boolean, 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 file
diff --git a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx
index 4c76bea312..9d8a45d7e0 100644
--- a/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx
+++ b/apps/client/src/widgets/type_widgets/markdown/Markdown.tsx
@@ -14,21 +14,20 @@ import { useCallback, useContext, useEffect, useMemo, useState } from "preact/ho
import appContext from "../../../components/app_context";
import NoteContext from "../../../components/note_context";
import FNote from "../../../entities/fnote";
-import froca from "../../../services/froca";
import keyboard_actions from "../../../services/keyboard_actions";
import note_create from "../../../services/note_create";
-import options from "../../../services/options";
import { removeIndividualBinding } from "../../../services/shortcuts";
-import tree from "../../../services/tree";
-import utils, { isDesktop } from "../../../services/utils";
+import { isDesktop } from "../../../services/utils";
import { useLegacyImperativeHandlers, useTriliumEvent } from "../../react/hooks";
import { resolveNoteChip } from "../../search_field_editor";
import { extractHighlightsFromStaticHtml, type RawHighlight } from "../../sidebar/highlights_extract";
import SplitEditor from "../helpers/SplitEditor";
import { ReadOnlyTextContent } from "../text/ReadOnlyText";
import { TypeWidgetProps } from "../type_widget";
-import { useMarkdownCompletions } from "./completions";
-import { insertText, replaceSelection, uploadImageAndInsert } from "./editor_utils";
+import {
+ insertDateTime, insertText, replaceSelection, showAddLinkDialog, showIncludeNoteDialog,
+ uploadImageAndInsert
+} from "./editor_utils";
const marked = new Marked({ breaks: true, gfm: true });
// Headings in the outline are rendered by this instance rather than by `renderToHtml`, so it needs
@@ -106,9 +105,8 @@ export default function Markdown(props: TypeWidgetProps) {
usePublishToc(props.noteContext, editorView, previewEl, headings, props.note);
usePublishHighlights(props.noteContext, editorView, previewEl, highlights, props.note);
useImageDrop(props.note, editorView);
- useTextCommands(props.parentComponent, editorView);
+ useTextCommands(editorView);
useNoteLinkChips(editorView);
- useMarkdownCompletions(props.parentComponent, editorView, props.note, () => props.noteContext?.notePath);
useMarkdownKeymap(editorView);
const ctx = useMemo<MarkdownContextValue>(
@@ -371,63 +369,18 @@ export function findActiveBlock(blocks: ArrayLike<HTMLElement>, activeLine: numb
* - Add Link (Ctrl+L): opens the add-link dialog, inserts markdown link syntax
* - Insert Date/Time (Alt+T): inserts a formatted date/time string
*/
-function useTextCommands(parentComponent: TypeWidgetProps["parentComponent"], editorView: VanillaCodeMirror | null) {
+function useTextCommands(editorView: VanillaCodeMirror | null) {
useLegacyImperativeHandlers({
addLinkToTextCommand() {
- if (!editorView) return;
-
- const { from, to } = editorView.state.selection.main;
- const selectedText = editorView.state.sliceDoc(from, to);
-
- parentComponent?.triggerCommand("showAddLinkDialog", {
- text: selectedText,
- hasSelection: from !== to,
- async addLink(notePath: string, linkTitle: string | null, externalLink?: boolean) {
- if (!editorView) return;
-
- let md: string;
- if (externalLink) {
- const label = (from !== to) ? selectedText : (linkTitle || notePath);
- md = `[${label}](${notePath})`;
- } else if (linkTitle) {
- const label = (from !== to) ? selectedText : linkTitle;
- md = `[${label}](#${notePath})`;
- } else {
- const noteId = tree.getNoteIdFromUrl(notePath);
- md = `[[${noteId}]]`;
- }
-
- replaceSelection(editorView, md, from, to);
- editorView.focus();
- }
- });
+ if (editorView) showAddLinkDialog(editorView);
},
insertDateTimeToTextCommand() {
- if (!editorView) return;
-
- const dateString = utils.formatDateTime(new Date(), options.get("customDateTimeFormat"));
- insertText(editorView, dateString);
+ if (editorView) insertDateTime(editorView);
},
addIncludeNoteToTextCommand() {
- if (!editorView) return;
-
- parentComponent?.triggerCommand("showContentEmbedDialog", {
- editorApi: {
- addContentEmbed(noteId: string, boxSize?: string) {
- insertText(editorView, `<figure class="include-note" data-note-id="${noteId}" data-box-size="${boxSize ?? "full"}"></figure>\n`);
- editorView.focus();
- },
- async addImage(noteId: string) {
- const note = await froca.getNote(noteId);
- if (!note) return;
- const encodedTitle = encodeURIComponent(note.title);
- insertText(editorView, `![${note.title}](api/images/${noteId}/${encodedTitle})\n`);
- editorView.focus();
- }
- }
- });
+ if (editorView) showIncludeNoteDialog(editorView);
},
async cutIntoNoteCommand() {
diff --git a/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.spec.tsx
index 01a5908e71..9a94dc5f96 100644
--- a/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.spec.tsx
@@ -23,6 +23,8 @@ vi.mock("../../../services/i18n", async (importOriginal) => ({
...(await importOriginal<object>()),
t: (key: string) => key
}));
+// The `/` list of the source loads the task states from the `_taskStates` subtree.
+vi.mock("../../../services/task_states", () => ({ getTaskStateDefinitions: async () => [] }));
// `CodeEditor` reads the theme as a string.
options.set("codeNoteTheme", "");
diff --git a/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.tsx b/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.tsx
index 816f77bcfa..8ffb5b59e5 100644
--- a/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.tsx
@@ -88,6 +88,7 @@ export default function MarkdownEmbed({
isEditing={isEditing}
isSourceShown={isSourceShown}
note={note}
+ ownerNote={entity instanceof FNote ? entity : entity.getNote()}
editor={editor}
content={content}
mime={MARKDOWN_MIME}
diff --git a/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts b/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts
index fa91947060..e601607816 100644
--- a/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts
+++ b/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts
@@ -4,38 +4,26 @@ import { ensureSyntaxTree } from "@codemirror/language";
import { EditorState } from "@codemirror/state";
import VanillaCodeMirror from "@triliumnext/codemirror";
import type { MimeType, TaskStateDef } from "@triliumnext/commons";
-import { h, render } from "preact";
-import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type FNote from "../../../entities/fnote";
import mime_types from "../../../services/mime_types.js";
-import type { NoteSuggestionOptions, Suggestion } from "../../../services/note_autocomplete";
-import type { TypeWidgetProps } from "../type_widget";
-import { buildCodeFenceOptions, buildSlashCommands, buildTaskItemInsert, codeFenceCompletionSource, isClosingFence, markdownCompletionAt, parseCodeFencePrefix, useMarkdownCompletions } from "./completions";
-
-// The hook's two 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>>()
+import {
+ buildCodeFenceOptions, buildMarkdownCommands, buildTaskItemInsert, codeFenceCompletionSource,
+ isClosingFence, markdownCompletionAt, parseCodeFencePrefix
+} from "./completions";
+
+const editorUtils = vi.hoisted(() => ({
+ uploadImageAndInsert: vi.fn(),
+ insertDateTime: vi.fn(),
+ showAddLinkDialog: vi.fn(),
+ showIncludeNoteDialog: vi.fn()
}));
-vi.mock("../../../services/note_autocomplete", async (importOriginal) => ({
- ...await importOriginal<typeof import("../../../services/note_autocomplete")>(),
- getNoteSuggestions,
- createNoteFromSuggestion
-}));
-
-const { uploadImageAndInsert } = vi.hoisted(() => ({ uploadImageAndInsert: vi.fn() }));
vi.mock("./editor_utils", async (importOriginal) => ({
...await importOriginal<typeof import("./editor_utils")>(),
- uploadImageAndInsert
+ ...editorUtils
}));
-vi.mock("../code/snippets", async (importOriginal) => ({
- ...await importOriginal<typeof import("../code/snippets")>(),
- useCodeSnippets: () => ({ current: [] })
-}));
-vi.mock("../../../services/task_states", () => ({ getTaskStateDefinitions: () => Promise.resolve([]) }));
// The catalogue is not loaded in specs, and the sample diagrams translate their names as they load.
vi.mock("../../../services/i18n", async (importOriginal) => ({
...await importOriginal<typeof import("../../../services/i18n")>(),
@@ -221,12 +209,11 @@ describe("markdownCompletionAt", () => {
});
});
-describe("buildSlashCommands", () => {
+describe("buildMarkdownCommands", () => {
let editor: VanillaCodeMirror;
- const triggerCommand = vi.fn();
beforeEach(() => {
- triggerCommand.mockReset();
+ vi.clearAllMocks();
const parent = document.createElement("div");
document.body.append(parent);
editor = new VanillaCodeMirror({ parent });
@@ -234,17 +221,15 @@ describe("buildSlashCommands", () => {
afterEach(() => editor.destroy());
- let currentNote = { noteId: "first" } as FNote;
+ let currentNote: FNote | null = { noteId: "first" } as FNote;
const todo = (name: string, markdownSymbol: string): TaskStateDef => ({ name, title: name, markdownSymbol, isCompleted: false, icon: `bx bx-${name}` });
function commands(taskStates: TaskStateDef[] = []) {
- return buildSlashCommands({
- parentComponent: { triggerCommand } as unknown as TypeWidgetProps["parentComponent"],
- getNote: () => currentNote,
+ return buildMarkdownCommands({
editorView: editor,
- taskStates,
- snippets: [ { noteId: "s1", title: "Greeting", description: "Says hello", content: "Hello!" } ]
+ getOwnerNote: () => currentNote,
+ taskStates
});
}
@@ -265,13 +250,11 @@ describe("buildSlashCommands", () => {
expect(byId("table")?.iconSvg).toContain("<svg");
expect(byId("tip")?.iconSvg).toContain("<svg");
expect(byId("todo:done")).toMatchObject({ aliases: expect.arrayContaining([ "todo:done", "done" ]), icon: "bx bx-done" });
- expect(byId("snippet:Greeting")).toMatchObject({ title: "Greeting", description: "Says hello", icon: "bx bx-code-curly" });
// One run of commands, with no dividers, as the text editor lists them.
expect(entries.some((entry) => entry.startsGroup)).toBe(false);
});
it("replaces the typed command with what it inserts", () => {
- expect(run("snippet:Greeting", "Hi /snip")).toBe("Hi Hello!");
expect(run("todo:done", "- /todo", [ todo("done", "x") ])).toBe("- [x] ");
expect(run("todo:done", "/todo", [ todo("done", "x") ])).toBe("- [x] ");
expect(run("tip", "/tip")).toBe("> [!TIP]\n> ");
@@ -321,133 +304,23 @@ describe("buildSlashCommands", () => {
if (!picker) throw new Error("no file picker opened");
Object.defineProperty(picker, "files", { value: [ file ] });
picker.dispatchEvent(new Event("change"));
- expect(uploadImageAndInsert).toHaveBeenCalledExactlyOnceWith(editor, currentNote, file);
+ expect(editorUtils.uploadImageAndInsert)
+ .toHaveBeenCalledExactlyOnceWith(editor, currentNote, file);
+
+ // Without an owner note, nothing uploads.
+ currentNote = null;
+ picker.dispatchEvent(new Event("change"));
+ expect(editorUtils.uploadImageAndInsert).toHaveBeenCalledOnce();
click.mockRestore();
});
- it("removes the typed command before running one of the text editor's commands", () => {
+ it("removes the typed command, then runs a dialog or an insertion on the editor", () => {
expect(run("date", "On /date")).toBe("On ");
- expect(triggerCommand).toHaveBeenCalledExactlyOnceWith("insertDateTimeToText");
- });
-});
-
-describe("useMarkdownCompletions", () => {
- let container: HTMLElement;
-
- beforeEach(() => {
- container = document.createElement("div");
- document.body.appendChild(container);
- });
-
- afterEach(() => {
- render(null, container);
- container.remove();
- });
-
- /** Mounts the hook against `editorView`. */
- function mount(editorView: VanillaCodeMirror) {
- function Probe() {
- useMarkdownCompletions({} as TypeWidgetProps["parentComponent"], editorView, { noteId: "n1" } as FNote, () => "root/parent");
- return null;
+ expect(run("link", "See /link")).toBe("See ");
+ expect(run("include", "/include")).toBe("");
+ const { insertDateTime, showAddLinkDialog, showIncludeNoteDialog } = editorUtils;
+ for (const action of [ insertDateTime, showAddLinkDialog, showIncludeNoteDialog ]) {
+ expect(action).toHaveBeenCalledExactlyOnceWith(editor);
}
-
- act(() => render(h(Probe, {}), container));
- }
-
- it("registers the list and the fence languages with the editor, and withdraws both on unmount", () => {
- const setNamedExtension = vi.fn();
- const setCompletionSource = vi.fn();
- mount({ setNamedExtension, setCompletionSource } as unknown as VanillaCodeMirror);
-
- expect(setNamedExtension).toHaveBeenCalledExactlyOnceWith("markdownCompletions", expect.anything());
- expect(setCompletionSource).toHaveBeenCalledExactlyOnceWith("markdownCodeFence", expect.any(Function));
-
- act(() => render(null, container));
- expect(setNamedExtension).toHaveBeenLastCalledWith("markdownCompletions", []);
- expect(setCompletionSource).toHaveBeenLastCalledWith("markdownCodeFence", null);
- });
-
- it("lists the commands for what follows a slash, as the text editor does, and runs the one picked", async () => {
- const parent = document.createElement("div");
- document.body.append(parent);
- const editor = new VanillaCodeMirror({ parent });
- mount(editor);
- editor.focus();
-
- editor.dispatch({ changes: { from: 0, insert: "/tip" }, selection: { anchor: 4 } });
- const rows = () => [ ...document.querySelectorAll(".note-autocomplete-menu [role=option]") ];
- // Found by its title, without the slash.
- await vi.waitFor(() => expect(rows().map((row) => row.textContent)).toEqual([ expect.stringContaining("titles.tip") ]));
- expect(rows()[0]?.querySelector("b")?.textContent).toBe("tip");
- // 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.
- editor.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
- await vi.waitFor(() => expect(editor.state.doc.toString()).toBe("> [!TIP]\n> "));
- await vi.waitFor(() => expect(rows()).toEqual([]));
-
- act(() => render(null, container));
- editor.destroy();
- });
-
- it("lists the notes for what follows an @ or a [[, as the text editor does, and links the one picked or created", async () => {
- getNoteSuggestions.mockResolvedValue([
- { notePath: "root/projects/abc123", noteTitle: "Alpha", notePathTitle: "Projects / Alpha", highlightedNotePathTitle: "<b>Al</b>pha" },
- { action: "create-child-note", noteTitle: "Al", parentNoteId: "parent", highlightedNotePathTitle: "Create child note" }
- ]);
- const parent = document.createElement("div");
- document.body.append(parent);
- const editor = new VanillaCodeMirror({ parent });
- mount(editor);
- editor.focus();
- const rows = () => [ ...document.querySelectorAll(".note-autocomplete-menu [role=option]") ];
- const press = (key: string) => editor.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));
-
- editor.dispatch({ changes: { from: 0, insert: "see @Al" }, selection: { anchor: 7 } });
- 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("Enter");
- await vi.waitFor(() => expect(editor.state.doc.toString()).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; }));
- editor.dispatch({ changes: { from: 14, insert: " @Al" }, selection: { anchor: 18 } });
- await vi.waitFor(() => expect(rows()).toHaveLength(2));
- press("ArrowDown");
- await new Promise((resolve) => setTimeout(resolve, 0));
- press("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(editor.state.doc.toString()).toBe("see [[abc123]] [[new1]]"));
-
- // After [[ the same list opens, and a pick inside a link already closed takes its brackets too.
- editor.focus();
- editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: "see [[Al" }, selection: { anchor: 8 } });
- await vi.waitFor(() => expect(rows()).toHaveLength(2));
- press("Enter");
- await vi.waitFor(() => expect(editor.state.doc.toString()).toBe("see [[abc123]]"));
- editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: "see [[Al]] x" }, selection: { anchor: 8 } });
- await vi.waitFor(() => expect(rows()).toHaveLength(2));
- press("Enter");
- await vi.waitFor(() => expect(editor.state.doc.toString()).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");
- editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: "see [[Al]] x" }, selection: { anchor: 8 } });
- await vi.waitFor(() => expect(rows()).toHaveLength(2));
- press("ArrowDown");
- await new Promise((resolve) => setTimeout(resolve, 0));
- press("Enter");
- await vi.waitFor(() => expect(editor.state.doc.toString()).toBe("see [[new2]] x"));
-
- act(() => render(null, container));
- editor.destroy();
});
});
diff --git a/apps/client/src/widgets/type_widgets/markdown/completions.tsx b/apps/client/src/widgets/type_widgets/markdown/completions.tsx
index d4ab2efcec..d430d85fee 100644
--- a/apps/client/src/widgets/type_widgets/markdown/completions.tsx
+++ b/apps/client/src/widgets/type_widgets/markdown/completions.tsx
@@ -11,7 +11,9 @@ import noteIcon from "@triliumnext/ckeditor5/src/icons/note.svg?raw";
import tabsIcon from "@triliumnext/ckeditor5/src/icons/tabs.svg?raw";
import internalLinkIcon from "@triliumnext/ckeditor5/src/icons/trilium.svg?raw";
import type VanillaCodeMirror from "@triliumnext/codemirror";
-import { hostedCompletion, type HostedCompletionApply, type HostedCompletionState } from "@triliumnext/codemirror/src/extensions/hosted_completion";
+import type {
+ HostedCompletionApply
+} from "@triliumnext/codemirror/src/extensions/hosted_completion";
import { isAnchorState, type TaskStateDef } from "@triliumnext/commons";
import bxBulb from "boxicons/svg/regular/bx-bulb.svg?raw";
import bxCommentError from "boxicons/svg/regular/bx-comment-error.svg?raw";
@@ -19,101 +21,24 @@ import bxError from "boxicons/svg/regular/bx-error.svg?raw";
import bxErrorCircle from "boxicons/svg/regular/bx-error-circle.svg?raw";
import bxInfoCircle from "boxicons/svg/regular/bx-info-circle.svg?raw";
import bxNetworkChart from "boxicons/svg/regular/bx-network-chart.svg?raw";
-import { useEffect, useRef } from "preact/hooks";
import type FNote from "../../../entities/fnote";
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 { CompletionMatch, SlashCommand } from "../code/editor_completions";
+import { SLASH_COMMAND_REGEX } from "../code/snippets";
import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams";
-import type { TypeWidgetProps } from "../type_widget";
-import { uploadImageAndInsert } from "./editor_utils";
+import {
+ insertDateTime, showAddLinkDialog, showIncludeNoteDialog, uploadImageAndInsert
+} from "./editor_utils";
-/** A `/` command of the Markdown editor, listed as the text editor lists its own. */
-export interface SlashCommand extends CommandEntry {
- /** Runs the command on the typed `/command`, which starts at `from` and ends at the caret, `to`. */
- apply: HostedCompletionApply;
-}
-
-/** A `/command` or a note typed before the caret, from its `/`, its `@` or its `[[`. */
-export interface MarkdownCompletionMatch {
- kind: "command" | "note";
- from: number;
- /** What follows the `/`, the `@` or the `[[`, which the list filters by, as the text editor's do. */
- query: string;
-}
-
-/** What the commands are built from, read again each time the list looks them up. */
-export interface SlashCommandContext {
- parentComponent: TypeWidgetProps["parentComponent"];
- /** The note being edited, read when a command needs it, as switching notes reuses the editor. */
- getNote(): FNote;
+/** What the Markdown commands are built from, read again each time the list looks them up. */
+export interface MarkdownCommandContext {
editorView: VanillaCodeMirror;
+ /** The note that images upload to, read when the image arrives. */
+ getOwnerNote(): FNote | null;
/** The user's task states, one `/todo:<state>` each where it has a Markdown marker. */
taskStates: TaskStateDef[];
- snippets: CodeSnippet[];
-}
-
-/**
- * Lists the `/` commands and the `@` notes typed at the start of a line or after whitespace, and
- * the notes typed after a Wikilink's `[[`, in the text editor's lists, through
- * `hostedCompletion()`. A note picked is linked as `[[noteId]]`,
- * and one created goes under the note at `getNotePath()`. The code-fence languages stay with
- * CodeMirror's own completion.
- */
-export function useMarkdownCompletions(
- parentComponent: TypeWidgetProps["parentComponent"],
- editorView: VanillaCodeMirror | null,
- note: FNote,
- getNotePath: () => string | null | undefined
-) {
- // Held in refs so the lists read the current note and parent component without registering
- // the extension again.
- const noteRef = useRef(note);
- const parentRef = useRef(parentComponent);
- const getNotePathRef = useRef(getNotePath);
- getNotePathRef.current = getNotePath;
- // The user-configured todo task states (from the `_taskStates` subtree), loaded once.
- const taskStatesRef = useRef<TaskStateDef[]>([]);
- // Markdown snippets (#snippet code notes with a markdown MIME) plus generic plain-text snippets,
- // inserted via `/snippet:<name>`. useCodeSnippets keeps the ref fresh so the list reads the latest.
- const snippetsRef = useCodeSnippets(
- (candidate) => candidate.isMarkdown() || (candidate.type === "code" && candidate.mime === "text/plain"),
- "markdown"
- );
- useEffect(() => { noteRef.current = note; }, [note]);
- useEffect(() => { parentRef.current = parentComponent; }, [parentComponent]);
- useEffect(() => { void getTaskStateDefinitions().then((states) => { taskStatesRef.current = states; }); }, []);
-
- useEffect(() => {
- if (!editorView) return;
-
- const commands = () => buildSlashCommands({
- parentComponent: parentRef.current,
- getNote: () => noteRef.current,
- editorView,
- taskStates: taskStatesRef.current,
- snippets: snippetsRef.current.filter((snippet) => snippet.noteId !== noteRef.current.noteId)
- });
- // Bridges the codemirror package's own @codemirror/state identity, as for the sources below.
- type CmMarkdownMatcher = Parameters<typeof hostedCompletion<MarkdownCompletionMatch>>[0]["match"];
- editorView.setNamedExtension("markdownCompletions", hostedCompletion({
- match: markdownCompletionAt as unknown as CmMarkdownMatcher,
- list: () => createMarkdownCompletionList(commands, () => getNotePathRef.current())
- }));
- // CodeMirror allows one `override` config per editor, so sources go through
- // `setCompletionSource` instead of each adding its own `autocompletion()`.
- // Bridges the codemirror package's own @codemirror/autocomplete identity, as code/snippets.ts does.
- type CmCompletionSource = Parameters<VanillaCodeMirror["setCompletionSource"]>[1];
- editorView.setCompletionSource("markdownCodeFence", codeFenceCompletionSource as unknown as CmCompletionSource);
-
- return () => {
- editorView.setNamedExtension("markdownCompletions", []);
- editorView.setCompletionSource("markdownCodeFence", null);
- };
- }, [editorView]);
}
/**
@@ -121,7 +46,9 @@ export function useMarkdownCompletions(
* or the note typed after a `[[`, the marker nearest the caret where both stand; or `null` in a code
* block or a code span, where any of them is part of the code.
*/
-export function markdownCompletionAt(before: string, _explicit: boolean, state: EditorState): MarkdownCompletionMatch | null {
+export function markdownCompletionAt(
+ before: string, _explicit: boolean, state: EditorState
+): CompletionMatch | null {
const mention = NOTE_TYPED.exec(before);
const wikilink = WIKILINK_TYPED.exec(before);
// A `/` inside an open link is part of the title being typed.
@@ -147,16 +74,18 @@ const NOTE_TYPED = /(?:^|(?<=\s))@[^@]*$/;
const WIKILINK_TYPED = /\[\[[^[\]]*$/;
/**
- * The commands the `/` list offers, titled, described, found by the same words and drawn with the same
- * icons as the text editor's, where it has the command too. Each is found by the word typed after the
- * `/` as well, such as `todo:done`.
+ * The Markdown commands of the `/` list, titled, described, found by the same words and drawn
+ * with the same icons as the text editor's, where it has the command too. Each is found by the
+ * word typed after the `/` as well, such as `todo:done`.
*/
-export function buildSlashCommands({ parentComponent, getNote, editorView, taskStates, snippets }: SlashCommandContext): SlashCommand[] {
- /** Removes the typed command, then runs one of the text editor's commands in its place. */
- const runCommand = (name: Parameters<NonNullable<typeof parentComponent>["triggerCommand"]>[0]): HostedCompletionApply =>
+export function buildMarkdownCommands(
+ { editorView, getOwnerNote, taskStates }: MarkdownCommandContext
+): SlashCommand[] {
+ /** Removes the typed command, then runs `action` on the editor. */
+ const runAction = (action: (view: VanillaCodeMirror) => void): HostedCompletionApply =>
(view, from, to) => {
view.dispatch({ changes: { from, to } });
- parentComponent?.triggerCommand(name);
+ action(editorView);
};
return [
@@ -165,12 +94,12 @@ export function buildSlashCommands({ parentComponent, getNote, editorView, taskS
description: t("markdown_slash_commands.date"),
aliases: [ "time", "now", "today", "timestamp" ],
iconSvg: dateTimeIcon
- }, runCommand("insertDateTimeToText")),
+ }, runAction(insertDateTime)),
command("include", {
title: t("markdown_slash_commands.titles.include"),
description: t("markdown_slash_commands.include"),
iconSvg: noteIcon
- }, runCommand("addIncludeNoteToText")),
+ }, runAction(showIncludeNoteDialog)),
command("image", {
title: t("markdown_slash_commands.titles.image"),
description: t("markdown_slash_commands.image"),
@@ -183,7 +112,8 @@ export function buildSlashCommands({ parentComponent, getNote, editorView, taskS
input.accept = "image/*";
input.addEventListener("change", () => {
const file = input.files?.[0];
- if (file) uploadImageAndInsert(editorView, getNote(), file);
+ const note = getOwnerNote();
+ if (file && note) uploadImageAndInsert(editorView, note, file);
});
input.click();
}),
@@ -192,7 +122,7 @@ export function buildSlashCommands({ parentComponent, getNote, editorView, taskS
description: t("markdown_slash_commands.link"),
aliases: [ "internal link", "trilium link", "reference link" ],
iconSvg: internalLinkIcon
- }, runCommand("addLinkToText")),
+ }, runAction(showAddLinkDialog)),
command("math", {
title: t("markdown_slash_commands.titles.math"),
description: t("markdown_slash_commands.math"),
@@ -360,18 +290,7 @@ export function buildSlashCommands({ parentComponent, getNote, editorView, taskS
const insert = buildTaskItemInsert(state.markdownSymbol, precededByBullet);
view.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 }
- });
- }))
+ })
];
}
@@ -394,46 +313,11 @@ function command(name: string, entry: Omit<SlashCommand, "id" | "apply">, apply:
return { ...entry, id: name, aliases: [ name, ...(entry.aliases ?? []) ], apply };
}
-/**
- * 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 `@` note.
- */
-function createMarkdownCompletionList(commands: () => SlashCommand[], getParentNotePath: () => string | null | undefined) {
- return createHostedList<HostedCompletionState<MarkdownCompletionMatch>>((state, list) => {
- const { kind, from, query } = state.match;
- if (kind === "note") {
- return (
- <NoteMentionList
- key={`note:${from}`}
- {...list}
- query={query}
- allowCreatingNotes
- parentNotePath={getParentNotePath()}
- onPick={(notePath) => state.commit(typeof notePath === "string"
- ? linkTo(notePath)
- : notePath.then((path) => path ? linkTo(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)}
- />
- );
- });
-}
-
/**
* Puts the link to the note at `notePath` in place of the typed note. Where the caret is inside a
* Wikilink already closed, the rest of the link up to its `]]` goes too.
*/
-function linkTo(notePath: string): HostedCompletionApply {
+export function linkToNote(notePath: string): HostedCompletionApply {
return (view, from, to) => {
const isWikilink = view.state.sliceDoc(from, from + 2) === "[[";
const rest = isWikilink ? /^[^[\]\n]*\]\]/.exec(view.state.sliceDoc(to, view.state.doc.lineAt(to).to)) : null;
diff --git a/apps/client/src/widgets/type_widgets/markdown/editor_utils.ts b/apps/client/src/widgets/type_widgets/markdown/editor_utils.ts
index 411bc350bd..69774ccb7b 100644
--- a/apps/client/src/widgets/type_widgets/markdown/editor_utils.ts
+++ b/apps/client/src/widgets/type_widgets/markdown/editor_utils.ts
@@ -1,9 +1,14 @@
import type VanillaCodeMirror from "@triliumnext/codemirror";
+import appContext from "../../../components/app_context";
import type FNote from "../../../entities/fnote";
+import froca from "../../../services/froca";
import { t } from "../../../services/i18n";
+import options from "../../../services/options";
import server from "../../../services/server";
import toast from "../../../services/toast";
+import tree from "../../../services/tree";
+import utils from "../../../services/utils";
/** Inserts text at the given position (or cursor) and moves the cursor to the end of the inserted text. */
export function insertText(view: VanillaCodeMirror, text: string, pos?: number) {
@@ -46,3 +51,55 @@ export async function uploadImageAndInsert(view: VanillaCodeMirror, note: FNote,
const base = t("markdown_editor.image_upload_failed", { name: file.name });
toast.showError(detail ? `${base} ${detail}` : base);
}
+
+/** Opens the add link dialog, then puts the link picked in place of the selection of `view`. */
+export function showAddLinkDialog(view: VanillaCodeMirror) {
+ const { from, to } = view.state.selection.main;
+ const selectedText = view.state.sliceDoc(from, to);
+
+ void appContext.triggerCommand("showAddLinkDialog", {
+ text: selectedText,
+ hasSelection: from !== to,
+ async addLink(notePath: string, linkTitle: string | null, externalLink?: boolean) {
+ let md: string;
+ if (externalLink) {
+ const label = (from !== to) ? selectedText : (linkTitle || notePath);
+ md = `[${label}](${notePath})`;
+ } else if (linkTitle) {
+ const label = (from !== to) ? selectedText : linkTitle;
+ md = `[${label}](#${notePath})`;
+ } else {
+ const noteId = tree.getNoteIdFromUrl(notePath);
+ md = `[[${noteId}]]`;
+ }
+
+ replaceSelection(view, md, from, to);
+ view.focus();
+ }
+ });
+}
+
+/** Inserts the current date and time at the cursor, in the `customDateTimeFormat` option. */
+export function insertDateTime(view: VanillaCodeMirror) {
+ insertText(view, utils.formatDateTime(new Date(), options.get("customDateTimeFormat")));
+}
+
+/** Opens the include note dialog, then inserts the embed or the image picked at the cursor. */
+export function showIncludeNoteDialog(view: VanillaCodeMirror) {
+ void appContext.triggerCommand("showContentEmbedDialog", {
+ editorApi: {
+ addContentEmbed(noteId: string, boxSize?: string) {
+ const attributes = `data-note-id="${noteId}" data-box-size="${boxSize ?? "full"}"`;
+ insertText(view, `<figure class="include-note" ${attributes}></figure>\n`);
+ view.focus();
+ },
+ async addImage(noteId: string) {
+ const note = await froca.getNote(noteId);
+ if (!note) return;
+ const encodedTitle = encodeURIComponent(note.title);
+ insertText(view, `![${note.title}](api/images/${noteId}/${encodedTitle})\n`);
+ view.focus();
+ }
+ }
+ });
+}
diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.json
index 033b53d8e9..668604cebc 100644
--- a/apps/server/src/assets/help/help_content.json
+++ b/apps/server/src/assets/help/help_content.json
@@ -134,7 +134,7 @@
"_help_0Ofbk1aSuVRu": "<figure class=\"image image-style-align-right image_resized\" style=\"width:50.47%;\"><img style=\"aspect-ratio:880/553;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Images/Image%20references_image.png\" width=\"880\" height=\"553\"></figure><p>Image references are an easy way to embed the preview of another note type into a&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;note.</p><h2>Supported note types</h2><ul><li><a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a></li><li><a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a></li><li><a class=\"reference-link\" href=\"#root/_help_gBbsAeiuUxI5\">Mind Map</a></li></ul><h2>Steps</h2><ol><li>Go to one of the supported notes (listed above) and look for the&nbsp;<span class=\"tn-icon bx bx-copy\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_1P8QXI5edXNd\">Note buttons</a>&nbsp;area.</li><li>Go to a&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;note and use the Paste function to insert the reference to that note.</li></ol><h2>Interaction</h2><ul><li>Double-clicking an image reference from a text note will automatically open the target note.</li><li>Clicking an image reference while <kbd>Ctrl</kbd> is pressed will open the target note in a new tab.</li><li>Modifying the target note should also update the image reference. If that doesn't happen, consider&nbsp;<a class=\"reference-link\" href=\"#root/_help_s8alTXmpFR61\">Refreshing the application</a>.</li></ul>",
"_help_VRoP0g1uHHc2": "<figure class=\"image image-style-align-center image_resized\" style=\"width:76.29%;\"><img style=\"aspect-ratio:1479/865;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/In-editor%20AI%20assistant_image.png\" width=\"1479\" height=\"865\"></figure><p>The AI assistant works on the text you are already writing: select a passage and have it rewritten, translated or turned into a table, or ask for new content at the cursor. Unlike the <a href=\"#root/_help_LrKznOtw9cQD\">AI chat</a>, it does not open a conversation window, the result is previewed in place and only enters the note when you accept it.</p><h2>Requirements</h2><p>The assistant is only available once at least one provider is configured in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>AI / LLM</em>, with at least one model selected for it. Until then the toolbar entry is not shown at all.</p><h2>Accessing the AI assistant</h2><p>To access the AI assistant:</p><ul><li>Look for the&nbsp;<span class=\"tn-icon cke cke-trilium-ai\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>. Press the button itself to enter the <em>Ask AI</em> mode or press the arrow key next to it to access the quick commands and the model selection.</li><li>Look for <em>AI assistant</em> or any of the <em>AI</em>-prefixed quick commands in&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</li><li>Press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>K</kbd>.</li><li>Select a text and choose the <em>AI assistant</em> option in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_jcQVxzYybYgz\">Note contextual menu</a>.</li></ul><h2>What the assistant works on</h2><figure class=\"table\"><table><thead><tr><th>Situation</th><th>What is sent</th></tr></thead><tbody><tr><td>Text is selected</td><td>The selection.</td></tr><tr><td>Nothing is selected, and you pick a quick action</td><td>The paragraph the cursor is in.</td></tr><tr><td>Nothing is selected, and you type your own prompt</td><td>Nothing, the response is new content written at the cursor.</td></tr></tbody></table></figure><p>In all cases the assistant also sends the text before and after the target, so that the model can tell what it is writing into: asked to <em>Continue writing</em> or to summarize, a model that can only see the selected words is guessing at the document around them. This surrounding text is context only, it is never rewritten.</p><aside class=\"admonition important\"><p>That means a single run sends more than the passage you highlighted. See&nbsp;<a class=\"reference-link\" href=\"#root/_help_cRRrdZjgyhNc\">Privacy</a>&nbsp;for exactly what leaves your machine.</p></aside><h2>Quick actions</h2><p>The arrow beside the toolbar button opens a menu of ready-made instructions, grouped by what they do.</p><ul><li>The <em>Reformat</em> actions produce real Trilium content rather than plain text: <em>Diagram</em> inserts a Mermaid diagram, <em>Callout</em> an admonition, and <em>Collapsible</em> a collapsible block.</li><li>The <em>Translate</em> group lists the <a href=\"#root/_help_veGu4faJErEM\">content languages</a> you have enabled, or a predefined list if no content languages are set. It can be filled from within the editor, the last entry of the submenu opens the language configuration directly.</li></ul><p>Actions that need something to work on are greyed out when there is nothing to work on (for example an empty paragraph with no selection).</p><h2>Asking for something specific</h2><p>Choosing <em>Ask AI…</em> (<span class=\"tn-icon bx bx-message-square-dots\"></span>) opens a prompt where you can describe the change in your own words, for example: \"make this less formal\", \"add a row for 2024\", \"write an intro paragraph for this section\". Press <kbd>Enter</kbd> or the <span class=\"tn-icon cke cke-arrow-up\"></span> send button to run it.</p><p>Once a response arrives you can keep going in the same prompt, and the assistant treats it as a conversation rather than as a fresh request: after <em>Translate this to German</em>, asking for <em>make it shorter</em> shortens the German, not the original.</p><h2>Reviewing the result</h2><p>The response streams in as it is generated, and can be interrupted at any point by pressing the <em>Stop</em> (<span class=\"tn-icon cke cke-stop\"></span>) button; whatever arrived before that stays usable.</p><p>Nothing is written into the note until you say so. The review offers:</p><ul><li><em>Result</em>, which displays the response as it will be inserted.</li><li><em>Changes</em>, which displays an inline diff against the original, with insertions and deletions marked. When the model rewrote the passage rather than editing it, the review opens on <em>Result</em> instead: a diff of two texts with little in common is harder to read than the answer itself.</li><li><em>Try again</em> (<span class=\"tn-icon cke cke-refresh\"></span>), to re-run the same instruction.</li><li><em>Replace</em>, which substitutes the original passage</li><li><em>Insert below</em>, which keeps the original and adds the response after it.</li></ul><p>Trilium also reports the model that produced it, the tokens consumed and, for providers that report it, the price.</p><p>If you ask for a correction and there is nothing to correct, the assistant will indicate it instead of showing a blank diff.</p><h2>Choosing the model</h2><p>The bottom of the quick actions menu shows which model the assistant runs on, and lets you pick another from the models you selected in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>AI / LLM</em>, grouped by provider.</p><p>The model can also be changed while asking for something specific, or after the assistant has generated its response (i.e. if the response needs a better model).</p><p>This choice is separate from the model used by the chat, and is remembered across notes and devices. Left unset, the assistant follows the first configured provider.</p>",
"_help_mVEYwt20exhO": "<p><em>Quick actions</em> are a feature of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_VRoP0g1uHHc2\">In-editor AI assistant</a>&nbsp;for&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;notes which automatically triggers an LLM suggestion based on a defined prompt. The built-in quick actions come with a predefined prompt, but it is also possible to define your own quick actions.</p><h2>Creating a custom quick action</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>: </p><ol><li>Right-click the note where you want to place the quick action.</li><li>Select <em>Insert child note</em>.</li><li>Select <em>More</em> → <em>AI Quick Action</em>. The entry appears only when AI is enabled.</li></ol><p>Afterwards, simply type in the content of the note the desired prompt. The text can be formatted in the same manner as a normal text note and it will be passed to the LLM as Markdown.</p><p>The title of the note will become the title of the quick action.</p><p>Of note:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;notes work too.</li><li>An empty note is ignored.</li><li><a class=\"reference-link\" href=\"#root/_help_MKmLg5x6xkor\">Archived Notes</a>&nbsp;are also excluded.</li></ul><h2>Using a quick action</h2><p>Once a quick action is defined, the action will appear under the <em>Quick Actions</em> dropdown in a group called <em>Custom</em>.</p>",
- "_help_nBAXQFj20hS1": "<p>Text notes can \"include\" another note as a read-only widget or an interactive widget, depending on the type of note.</p><p>This can be useful for e.g. including a dynamically generated chart (from scripts &amp; \"render HTML\" note) or other more advanced use cases.</p><h2>Including a note</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, look for the&nbsp;<span class=\"tn-icon cke cke-trilium-note\"></span> button. There is also a keyboard shortcut defined for it but it is not allocated by default.</p><p>To include a note that is already linked, right-click a reference link to it in a text note being edited and select <em>Convert link to an included note</em>, at the end of the menu. The include gets the box size that suits the note, as one added from the button does.</p><p>An <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> can be included the same way, from the context menu of a link to it (see <em>Embedding an attachment</em> there).</p><p>A link to blocks of a text note is converted the same way, with <em>Convert link to note excerpt</em>, and the include then shows only those blocks. See <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>.</p><h2>Box sizes</h2><p>The box size sets how much of the included note is shown.</p><ul><li><em>Tiny</em> shows a single row instead of the content: the note's icon, its title with the path to the note above it, and buttons to act on the note. The included note is never rendered, so wherever the note is shown outside the editor, such as in print, in a tooltip or on a shared page, a <em>Tiny</em> include appears as a link to the included note.</li><li><em>Small</em> and <em>Medium</em> show the content in a box of limited height. Text scrolls inside the box, while a picture, a diagram or a video is scaled down to fit it.</li><li><em>Full</em> shows the whole content.</li><li><em>Expandable</em> shows only the title until its <span class=\"tn-icon bx bx-chevron-right\"></span> arrow is pressed. In a read-only note, a click anywhere on the title row other than its buttons and link expands or collapses it as well.</li></ul><p>A new include gets the size that suits what it shows:</p><ul><li><em>Tiny</em> for a note or an attachment that has no preview, such as a relation map or an archive.</li><li><em>Small</em> for audio.</li><li><em>Full</em> for a code note or a code file, such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment, and for an excerpt of the blocks of a text note.</li><li><em>Medium</em> for anything else.</li></ul><p>The dialog that includes a note selects that size once the note is picked, and you can choose another one there. To change the size later, select the include and use the <em>Box size</em> menu in its toolbar, or the <em>Size</em> submenu of its <em>More actions</em> menu.</p><h2>Resizing</h2><p>A <em>Small</em>, <em>Medium</em> or <em>Expandable</em> include can be resized to any width and height. A <em>Tiny</em> or <em>Full</em> include always fits its content.</p><ul><li>To resize an include, select it and drag the handle in its bottom-right corner. To change only the width or only the height, drag the middle of its right or bottom edge instead, where a touch screen shows a handle too. In right-to-left text, the handle is in the bottom-left corner and the width changes from the left edge.</li><li>Resizing works with a mouse, a pen or a finger.</li><li>While the height changes, moving the handle near the top or the bottom of the note scrolls the note.</li><li>An include narrower than the note is centered, so changing its width moves both of its sides. Making it as wide as the note returns it to the full width.</li><li>To cancel a resize, press <kbd>Esc</kbd> before releasing the handle.</li><li>To reset the size, double-click the corner handle, or double-tap it on a touch screen. Double-clicking the right or bottom edge resets only the width or the height.</li><li>Choosing a box size resets the height. Choosing <em>Tiny</em> or <em>Full</em> resets the width too.</li><li>While an <em>Expandable</em> include is collapsed, only its width can be changed.</li></ul><h2>Caption</h2><p>An include can have a caption, shown centered at the bottom of its box. The caption is part of the text note, so it can be formatted like the rest of the text, for example in bold or with a link.</p><ul><li>To add a caption, select the include, press the <span class=\"tn-icon cke cke-caption\"></span> <em>Toggle caption on</em> button in its toolbar and type the caption.</li><li>To remove the caption, press the same button again. Pressing it once more brings back the text it had, as long as the note stays open.</li><li>A <em>Tiny</em> include has no caption. Switching an include to <em>Tiny</em> removes its caption, and switching it back to a larger size restores the caption, as long as the note stays open.</li><li>An <em>Expandable</em> include shows its caption under the title while the content is collapsed, and under the content once it is expanded.</li></ul><h2>Title</h2><p>The title row of an include links to the included note and holds its buttons. To show only the content, select the include and press the <span class=\"tn-icon bx bx-window-alt\"></span> <em>Show title</em> button in its toolbar. Pressing it again shows the title.</p><ul><li>While the title is hidden, the <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> button in the toolbar of the include opens the menu of the included note.</li><li>A <em>Tiny</em> or <em>Expandable</em> include always shows its title, and its toolbar has no <em>Show title</em> button.</li></ul><h2>Opening an included note</h2><p>To open an included note in a new tab, press the <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> button at the end of its title. An embedded attachment has the same button.</p><p>The <span class=\"tn-icon bx bx-dots-vertical-rounded\"></span> <em>More actions</em> button at the end of the title row opens the same menu as right-clicking anywhere on the title row: the other places to open the note in and, for an embedded attachment, the actions on the attachment.</p><p>In a note being edited, the menu also has the commands of the include's toolbar: the <em>Size</em> submenu, <em>Show title</em> and <em>Show caption</em>, each checked while it is in effect, and <em>Convert to link</em> at the end. A drawing canvas, a Mermaid diagram, an included text, code or Markdown note and an embedded code or Markdown file also have <em>Editable</em>, above <em>Size</em>. An included code or Markdown note, an embedded code or Markdown file and a Mermaid diagram also have the <em>Word wrap</em> and <em>Line numbers</em> submenus after <em>Editable</em> (see <em>Editing an include in place</em> below). A Mermaid diagram, an included Markdown note and an embedded Markdown file also have <em>Source view</em>, <em>Split view</em> and <em>Preview</em> after these submenus. For an embedded attachment they follow its first group of actions; for an included note they end the menu.</p><p>To show an include of size <em>Medium</em> or <em>Full</em> on the whole screen, press the <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em> button at the end of its title. An excerpt of the blocks of a note has an <span class=\"tn-icon bx bx-pencil\"></span> <em>Edit excerpt</em> button there instead; see <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>. To return, press <span class=\"tn-icon bx bx-exit\"></span> <em>Exit fullscreen</em> in the top-right corner, or <kbd>Esc</kbd>.</p><p>A <em>Tiny</em> include has these buttons instead, followed by the same <em>More actions</em> button:</p><ul><li>For a note, <span class=\"tn-icon bx bx-edit\"></span> <em>Quick edit</em> opens the note in&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, and <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> opens it in a new tab.</li><li>For an embedded attachment, <span class=\"tn-icon bx bx-file-find\"></span> <em>Open externally</em> opens the file in another application, and <span class=\"tn-icon bx bx-download\"></span> <em>Download</em> downloads it. The size of the file is shown under its title.</li></ul><h2>Converting an include to a link</h2><p>To replace an include with a link to the included note, select it and press the <span class=\"tn-icon cke cke-link\"></span> <em>Convert to link</em> button in its toolbar, or choose <em>Convert to link</em> at the end of its <em>More actions</em> menu. An embedded attachment turns into a link to the attachment the same way.</p><h2>Included notes in the share functionality</h2><p>If a <a href=\"#root/_help_R9pX4DGra2Vt\">shared note</a> contains one or more included notes, they will be displayed in the content of the note as if they were part of the note itself. The caption of an include is shown under the included content. A <em>Tiny</em> include is shown as a link to the included note instead, and so is an include that would show a note already shown around it, such as a note that includes itself. The same goes for a printed or exported note.</p><p>For this to work, the included notes must also be shared, otherwise they will not be shown. However, the included notes can still be hidden from the note tree via <code>#shareHiddenFromTree</code>.</p><h2>Interactive notes</h2><p>Since v0.104.0, included notes might become interactive depending on their note type:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a>&nbsp;(e.g.&nbsp;<a class=\"reference-link\" href=\"#root/_help_81SGnPGMk7Xc\">Geo Map</a>) will render fully interactive, including creating new notes.</li><li><a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a>&nbsp;will also display the results.</li><li><a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a>&nbsp;provides an interactive preview of the website.</li></ul><h2>Included images</h2><p>An included image, whether an image note or an image attachment, is shown in the image viewer, which zooms and pans it:</p><ul><li>To zoom, press the <span class=\"tn-icon bx bx-plus-circle\"></span> <em>Zoom in</em> and <span class=\"tn-icon bx bx-minus-circle\"></span> <em>Zoom out</em> buttons in the bottom-right corner of the image, or pinch on a touch screen. The percentage between them resets the zoom.</li><li>To zoom with the mouse wheel, click the image first. Until then, the mouse wheel scrolls the note.</li><li>To pan an image that is zoomed in, drag it. At its fitted size, dragging the image on a touch screen scrolls the note.</li><li>To return to the fitted size, double-click the image.</li></ul><p>In a <em>Small</em> or <em>Medium</em> box, the image is scaled down to fit the height of the box. In fullscreen, it fits the screen.</p><h2>Editing an include in place</h2><p>An included text note, an included code note and an embedded code file such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment can be edited without leaving the note that includes them. A code note or file is shown with syntax highlighting and line numbers until then, in the colors of the code editor. Included Markdown can be edited too, see <em>Included Markdown</em> below.</p><ul><li>To edit, select the include and turn on the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or check <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. Turn <em>Editable</em> off to return to the preview.</li><li>While <em>Editable</em> is on, the arrow keys move the caret into the include and back out, as through the rest of the text. Entering from above or from the left puts the caret at the start of the include, and entering from below or from the right puts it at the end. A collapsed <em>Expandable</em> include is skipped.</li><li>While an included text note has the focus, the formatting toolbar applies to it. The notes it includes in turn stay read-only.</li><li>Code is edited in the same code editor as a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note, with its theme, indentation and line wrapping settings.</li><li>The toolbar of an included code note or an embedded code file also has the language and indentation menus of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_AlJ73vBCjWDw\">Status bar</a>, between <em>Editable</em> and the <em>Box size</em> menu: <em>Change language mode</em>, which shows the current language, and <em>Change tab width</em>, which shows the current indentation. <em>Re-indent content to</em> converts the indentation of the code itself and saves it to the included note or file, whether <em>Editable</em> is on or off.<ul><li>For an included note, the menus change the note, as they do in its own tab.</li><li>For an embedded code file, the language and indentation settings change only how this include shows the file, and are saved with the note that includes it. The language replaces the one that the file name gives, and the <em>Use default</em> entries return to the indentation set in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em>. These settings leave the file itself unchanged, and other includes of it keep their own settings.</li></ul></li><li>The <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu of an included code or Markdown note, an embedded code or Markdown file and a <a href=\"#root/_help_CohkqWQC1iBv\">Mermaid diagram</a> has two more submenus after <em>Editable</em>, each with <em>Auto</em>, <em>On</em> and <em>Off</em>. They change how the code editor shows the source, and for code the preview as well.<ul><li><em>Word wrap</em> wraps long lines instead of scrolling them. <em>Auto</em> follows the setting in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em>. For an included note, it sets the <code>#wrapLines</code> label of the note, as the <em>Word wrap</em> submenu of its <a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a> does for a code note. For an embedded file or a Mermaid diagram, it changes only this include.</li><li><em>Line numbers</em> shows or hides the numbers at the start of each line. <em>Auto</em> shows them, as a code note does. It changes only this include, for an included note as well.</li></ul></li><li>The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.</li><li>An include of <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a> edits only the referenced blocks.</li><li>Editing is not available in a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, for an included note marked <code>#readOnly</code>, or for an attachment of another note.</li><li><a class=\"reference-link\" href=\"#root/_help_McngOG2jbUWX\">Search in note</a> finds the text of included text and code notes among the results of the note around them, and replaces it while <em>Editable</em> is on.</li></ul><h2>Included Markdown</h2><p>An included&nbsp;<a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a>&nbsp;note and an embedded Markdown file, such as a <code>.md</code> attachment, are shown with the same three views as a Markdown note in its own tab (see&nbsp;<a class=\"reference-link\" href=\"#root/_help_SL5f1Auq7sVN\">Note types with split view</a>): <span class=\"tn-icon bx bx-code\"></span> <em>Source view</em>, <span class=\"tn-icon bx bxs-dock-left\"></span> <em>Split view</em> and <span class=\"tn-icon bx bx-show\"></span> <em>Preview</em>.</p><ul><li>To switch the view, press one of the three buttons in the title row of the include. In a note being edited, the toolbar of the include has the same buttons after <em>Editable</em>, and its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu has them as <em>Source view</em>, <em>Split view</em> and <em>Preview</em>.</li><li>Until a view is chosen, the include shows the <em>Preview</em>, and the <em>Split view</em> while <em>Editable</em> is on.</li><li>To edit the Markdown, turn on <em>Editable</em> (see <em>Editing an include in place</em> above). The source is edited in the code editor of a Markdown note, and the preview follows the changes as you type. While <em>Editable</em> is off, the source can be read and copied but not changed.</li><li>The <em>Word wrap</em> and <em>Line numbers</em> submenus of the <em>More actions</em> menu change how the source shows, as for code (see <em>Editing an include in place</em> above).</li><li>As in a Markdown note, the preview scrolls along with the source and highlights the block where the cursor is, and <kbd>Ctrl</kbd>+<kbd>B</kbd>, <kbd>Ctrl</kbd>+<kbd>I</kbd>, <kbd>Ctrl</kbd>+<kbd>M</kbd> and <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd> format the selection.</li><li>In a note being edited, the view is saved with the include, so two includes of the same note can show different views. In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the view can be changed too, until the note is opened again.</li><li>While the source shows, the include has the height of its box size, or the height it was resized to. A <em>Full</em> include gets a fixed height too, instead of fitting its content.</li><li><a class=\"reference-link\" href=\"#root/_help_McngOG2jbUWX\">Search in note</a>&nbsp;searches the source while it shows, and the preview otherwise.</li></ul><h2>Drawing canvases</h2><p>A drawing canvas is an Excalidraw canvas, like the one of a <a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a> note, drawn directly in the text note. It is not a note of its own: the drawing is kept in a <code>Canvas.excalidraw</code> <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> of the text note and is saved together with the text.</p><ul><li>To insert a drawing canvas, open the <span class=\"tn-icon cke cke-plus\"></span> <em>Insert</em> menu of the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> and choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em>, above <em>Mermaid diagram</em>. It is also available as <em>Drawing canvas</em> in the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>. The canvas is added empty and editable, in a <em>Medium</em> box with its title hidden, and takes the focus, ready for drawing.</li><li>To draw or write over an image, select the image and press the <span class=\"tn-icon bx bxs-pen\"></span> <em>Convert image to a drawing canvas</em> button of its toolbar. The image is replaced by an editable drawing canvas in a <em>Medium</em> box, with its title hidden and the focus in it. The image sits at its original size in the middle of the canvas, zoomed so that all of it shows, and is locked so that it cannot be selected or moved by accident. While it is locked, the canvas can be zoomed in on the image but not zoomed out past it or scrolled beyond its edges. To move or resize the image anyway, right-click it and choose <em>Unlock</em>. The caption of the image is kept, but not its alignment or link. Only an image on its own line can be converted, not one inside a paragraph. Undo brings the image back.</li><li>An Excalidraw file (<code>.excalidraw</code>) attached with the <span class=\"tn-icon cke cke-paper-clip\"></span><em>Attach file</em> button becomes a drawing canvas too, in a <em>Medium</em> box titled with the file name. It starts with <em>Editable</em> off, so the drawing shows but cannot be changed until <em>Editable</em> is turned on (see below).</li><li>To draw on a canvas that does not have the focus, click it first. Until then, touch gestures scroll the note. The canvas then has the tools, menus and keyboard shortcuts of a Canvas note. The toolbars, the menus and the properties of the selected shapes show only while the canvas has the focus, so elsewhere the drawing reads like a picture in the text.</li><li>The mouse wheel and the touchpad scroll the note over a canvas too, as over the text. To zoom, use the zoom buttons of the canvas toolbar; to move around the drawing, use the <span class=\"tn-icon bx bxs-hand\"></span> <em>Hand</em> tool. In fullscreen, the mouse wheel moves and zooms the drawing instead.</li><li>The canvas toolbar replaces the Excalidraw menu: <em>Export image</em>, <em>Find on canvas</em>, <em>Library</em> and <em>Help</em> are at the end of its <span class=\"tn-icon bx bx-category\"></span> <em>More tools</em> menu. In fullscreen, the Excalidraw menu shows again.</li><li>A new drawing has the background color of the note. A background chosen from the Excalidraw menu replaces it.</li><li>To protect a finished drawing from accidental changes, select it and turn off the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or uncheck <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. The drawing then shows as a still picture, at the zoom and position it had, and can no longer be changed, zoomed or moved. To draw again, turn <em>Editable</em> back on.</li><li>The box sizes, resizing, the caption and the title work as for an included note, but the toolbar of a drawing leaves the box size, <em>Show title</em> and <em>Convert to link</em> to its <em>More actions</em> menu.</li><li>In the desktop layout, Excalidraw keeps its desktop interface however small the box is. In the mobile layout, a narrow or short box switches it to a compact interface. For more room, choose <em>Full</em>, or show the title and press <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em>.</li><li>Pictures added to the drawing are stored in the same attachment. A converted image is kept as an image attachment of the note instead, named with a generated code.</li><li>In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the drawing shows as a still picture too.</li><li>On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, the drawing is shown as a picture at its own size, whatever the size of its box, in light or dark colors to match the page. Each change to the drawing saves this picture as an SVG image attachment of the note, also named with a generated code.</li></ul><h3>Limitations</h3><ul><li>The Excalidraw shape library is not saved for a drawing canvas.</li><li>Outside the editor, for example in a tooltip, when printing or in the list of attachments, the drawing is shown as a picture.</li><li>A drawing has no picture for shared pages until its first change, except one converted from an image. Until then, for example for an attached <code>.excalidraw</code> file, a shared page shows a link to download the drawing instead.</li><li>In Safari, the picture of a drawing on a shared page follows the light or dark appearance of the system rather than the theme chosen on the page.</li><li>A copy of a drawing canvas pasted in the same note shares the drawing with the original, so a change to one shows in the other only after the note is opened again. A copy pasted in another note gets a drawing of its own.</li></ul>",
+ "_help_nBAXQFj20hS1": "<p>Text notes can \"include\" another note as a read-only widget or an interactive widget, depending on the type of note.</p><p>This can be useful for e.g. including a dynamically generated chart (from scripts &amp; \"render HTML\" note) or other more advanced use cases.</p><h2>Including a note</h2><p>In the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, look for the&nbsp;<span class=\"tn-icon cke cke-trilium-note\"></span> button. There is also a keyboard shortcut defined for it but it is not allocated by default.</p><p>To include a note that is already linked, right-click a reference link to it in a text note being edited and select <em>Convert link to an included note</em>, at the end of the menu. The include gets the box size that suits the note, as one added from the button does.</p><p>An <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> can be included the same way, from the context menu of a link to it (see <em>Embedding an attachment</em> there).</p><p>A link to blocks of a text note is converted the same way, with <em>Convert link to note excerpt</em>, and the include then shows only those blocks. See <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>.</p><h2>Box sizes</h2><p>The box size sets how much of the included note is shown.</p><ul><li><em>Tiny</em> shows a single row instead of the content: the note's icon, its title with the path to the note above it, and buttons to act on the note. The included note is never rendered, so wherever the note is shown outside the editor, such as in print, in a tooltip or on a shared page, a <em>Tiny</em> include appears as a link to the included note.</li><li><em>Small</em> and <em>Medium</em> show the content in a box of limited height. Text scrolls inside the box, while a picture, a diagram or a video is scaled down to fit it.</li><li><em>Full</em> shows the whole content.</li><li><em>Expandable</em> shows only the title until its <span class=\"tn-icon bx bx-chevron-right\"></span> arrow is pressed. In a read-only note, a click anywhere on the title row other than its buttons and link expands or collapses it as well.</li></ul><p>A new include gets the size that suits what it shows:</p><ul><li><em>Tiny</em> for a note or an attachment that has no preview, such as a relation map or an archive.</li><li><em>Small</em> for audio.</li><li><em>Full</em> for a code note or a code file, such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment, and for an excerpt of the blocks of a text note.</li><li><em>Medium</em> for anything else.</li></ul><p>The dialog that includes a note selects that size once the note is picked, and you can choose another one there. To change the size later, select the include and use the <em>Box size</em> menu in its toolbar, or the <em>Size</em> submenu of its <em>More actions</em> menu.</p><h2>Resizing</h2><p>A <em>Small</em>, <em>Medium</em> or <em>Expandable</em> include can be resized to any width and height. A <em>Tiny</em> or <em>Full</em> include always fits its content.</p><ul><li>To resize an include, select it and drag the handle in its bottom-right corner. To change only the width or only the height, drag the middle of its right or bottom edge instead, where a touch screen shows a handle too. In right-to-left text, the handle is in the bottom-left corner and the width changes from the left edge.</li><li>Resizing works with a mouse, a pen or a finger.</li><li>While the height changes, moving the handle near the top or the bottom of the note scrolls the note.</li><li>An include narrower than the note is centered, so changing its width moves both of its sides. Making it as wide as the note returns it to the full width.</li><li>To cancel a resize, press <kbd>Esc</kbd> before releasing the handle.</li><li>To reset the size, double-click the corner handle, or double-tap it on a touch screen. Double-clicking the right or bottom edge resets only the width or the height.</li><li>Choosing a box size resets the height. Choosing <em>Tiny</em> or <em>Full</em> resets the width too.</li><li>While an <em>Expandable</em> include is collapsed, only its width can be changed.</li></ul><h2>Caption</h2><p>An include can have a caption, shown centered at the bottom of its box. The caption is part of the text note, so it can be formatted like the rest of the text, for example in bold or with a link.</p><ul><li>To add a caption, select the include, press the <span class=\"tn-icon cke cke-caption\"></span> <em>Toggle caption on</em> button in its toolbar and type the caption.</li><li>To remove the caption, press the same button again. Pressing it once more brings back the text it had, as long as the note stays open.</li><li>A <em>Tiny</em> include has no caption. Switching an include to <em>Tiny</em> removes its caption, and switching it back to a larger size restores the caption, as long as the note stays open.</li><li>An <em>Expandable</em> include shows its caption under the title while the content is collapsed, and under the content once it is expanded.</li></ul><h2>Title</h2><p>The title row of an include links to the included note and holds its buttons. To show only the content, select the include and press the <span class=\"tn-icon bx bx-window-alt\"></span> <em>Show title</em> button in its toolbar. Pressing it again shows the title.</p><ul><li>While the title is hidden, the <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> button in the toolbar of the include opens the menu of the included note.</li><li>A <em>Tiny</em> or <em>Expandable</em> include always shows its title, and its toolbar has no <em>Show title</em> button.</li></ul><h2>Opening an included note</h2><p>To open an included note in a new tab, press the <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> button at the end of its title. An embedded attachment has the same button.</p><p>The <span class=\"tn-icon bx bx-dots-vertical-rounded\"></span> <em>More actions</em> button at the end of the title row opens the same menu as right-clicking anywhere on the title row: the other places to open the note in and, for an embedded attachment, the actions on the attachment.</p><p>In a note being edited, the menu also has the commands of the include's toolbar: the <em>Size</em> submenu, <em>Show title</em> and <em>Show caption</em>, each checked while it is in effect, and <em>Convert to link</em> at the end. A drawing canvas, a Mermaid diagram, an included text, code or Markdown note and an embedded code or Markdown file also have <em>Editable</em>, above <em>Size</em>. An included code or Markdown note, an embedded code or Markdown file and a Mermaid diagram also have the <em>Word wrap</em> and <em>Line numbers</em> submenus after <em>Editable</em> (see <em>Editing an include in place</em> below). A Mermaid diagram, an included Markdown note and an embedded Markdown file also have <em>Source view</em>, <em>Split view</em> and <em>Preview</em> after these submenus. For an embedded attachment they follow its first group of actions; for an included note they end the menu.</p><p>To show an include of size <em>Medium</em> or <em>Full</em> on the whole screen, press the <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em> button at the end of its title. An excerpt of the blocks of a note has an <span class=\"tn-icon bx bx-pencil\"></span> <em>Edit excerpt</em> button there instead; see <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>. To return, press <span class=\"tn-icon bx bx-exit\"></span> <em>Exit fullscreen</em> in the top-right corner, or <kbd>Esc</kbd>.</p><p>A <em>Tiny</em> include has these buttons instead, followed by the same <em>More actions</em> button:</p><ul><li>For a note, <span class=\"tn-icon bx bx-edit\"></span> <em>Quick edit</em> opens the note in&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, and <span class=\"tn-icon bx bx-link-external\"></span> <em>Open in new tab</em> opens it in a new tab.</li><li>For an embedded attachment, <span class=\"tn-icon bx bx-file-find\"></span> <em>Open externally</em> opens the file in another application, and <span class=\"tn-icon bx bx-download\"></span> <em>Download</em> downloads it. The size of the file is shown under its title.</li></ul><h2>Converting an include to a link</h2><p>To replace an include with a link to the included note, select it and press the <span class=\"tn-icon cke cke-link\"></span> <em>Convert to link</em> button in its toolbar, or choose <em>Convert to link</em> at the end of its <em>More actions</em> menu. An embedded attachment turns into a link to the attachment the same way.</p><h2>Included notes in the share functionality</h2><p>If a <a href=\"#root/_help_R9pX4DGra2Vt\">shared note</a> contains one or more included notes, they will be displayed in the content of the note as if they were part of the note itself. The caption of an include is shown under the included content. A <em>Tiny</em> include is shown as a link to the included note instead, and so is an include that would show a note already shown around it, such as a note that includes itself. The same goes for a printed or exported note.</p><p>For this to work, the included notes must also be shared, otherwise they will not be shown. However, the included notes can still be hidden from the note tree via <code>#shareHiddenFromTree</code>.</p><h2>Interactive notes</h2><p>Since v0.104.0, included notes might become interactive depending on their note type:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a>&nbsp;(e.g.&nbsp;<a class=\"reference-link\" href=\"#root/_help_81SGnPGMk7Xc\">Geo Map</a>) will render fully interactive, including creating new notes.</li><li><a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a>&nbsp;will also display the results.</li><li><a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a>&nbsp;provides an interactive preview of the website.</li></ul><h2>Included images</h2><p>An included image, whether an image note or an image attachment, is shown in the image viewer, which zooms and pans it:</p><ul><li>To zoom, press the <span class=\"tn-icon bx bx-plus-circle\"></span> <em>Zoom in</em> and <span class=\"tn-icon bx bx-minus-circle\"></span> <em>Zoom out</em> buttons in the bottom-right corner of the image, or pinch on a touch screen. The percentage between them resets the zoom.</li><li>To zoom with the mouse wheel, click the image first. Until then, the mouse wheel scrolls the note.</li><li>To pan an image that is zoomed in, drag it. At its fitted size, dragging the image on a touch screen scrolls the note.</li><li>To return to the fitted size, double-click the image.</li></ul><p>In a <em>Small</em> or <em>Medium</em> box, the image is scaled down to fit the height of the box. In fullscreen, it fits the screen.</p><h2>Editing an include in place</h2><p>An included text note, an included code note and an embedded code file such as a <code>.js</code>, <code>.py</code> or <code>.txt</code> attachment can be edited without leaving the note that includes them. A code note or file is shown with syntax highlighting and line numbers until then, in the colors of the code editor. Included Markdown can be edited too, see <em>Included Markdown</em> below.</p><ul><li>To edit, select the include and turn on the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or check <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. Turn <em>Editable</em> off to return to the preview.</li><li>While <em>Editable</em> is on, the arrow keys move the caret into the include and back out, as through the rest of the text. Entering from above or from the left puts the caret at the start of the include, and entering from below or from the right puts it at the end. A collapsed <em>Expandable</em> include is skipped.</li><li>While an included text note has the focus, the formatting toolbar applies to it. The notes it includes in turn stay read-only.</li><li>Code is edited in the same code editor as a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note, with its theme, indentation and line wrapping settings.</li><li>Typing <code>/</code> in the code lists the <a class=\"reference-link\" href=\"#root/_help_IEgsWp5hHH35\">Code Snippets</a> of its language, as in a code note.</li><li>The toolbar of an included code note or an embedded code file also has the language and indentation menus of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_AlJ73vBCjWDw\">Status bar</a>, between <em>Editable</em> and the <em>Box size</em> menu: <em>Change language mode</em>, which shows the current language, and <em>Change tab width</em>, which shows the current indentation. <em>Re-indent content to</em> converts the indentation of the code itself and saves it to the included note or file, whether <em>Editable</em> is on or off.<ul><li>For an included note, the menus change the note, as they do in its own tab.</li><li>For an embedded code file, the language and indentation settings change only how this include shows the file, and are saved with the note that includes it. The language replaces the one that the file name gives, and the <em>Use default</em> entries return to the indentation set in&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em>. These settings leave the file itself unchanged, and other includes of it keep their own settings.</li></ul></li><li>The <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu of an included code or Markdown note, an embedded code or Markdown file and a <a href=\"#root/_help_CohkqWQC1iBv\">Mermaid diagram</a> has two more submenus after <em>Editable</em>, each with <em>Auto</em>, <em>On</em> and <em>Off</em>. They change how the code editor shows the source, and for code the preview as well.<ul><li><em>Word wrap</em> wraps long lines instead of scrolling them. <em>Auto</em> follows the setting in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em>. For an included note, it sets the <code>#wrapLines</code> label of the note, as the <em>Word wrap</em> submenu of its <a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a> does for a code note. For an embedded file or a Mermaid diagram, it changes only this include.</li><li><em>Line numbers</em> shows or hides the numbers at the start of each line. <em>Auto</em> shows them, as a code note does. It changes only this include, for an included note as well.</li></ul></li><li>The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.</li><li>An include of <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a> edits only the referenced blocks.</li><li>Editing is not available in a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, for an included note marked <code>#readOnly</code>, or for an attachment of another note.</li><li><a class=\"reference-link\" href=\"#root/_help_McngOG2jbUWX\">Search in note</a> finds the text of included text and code notes among the results of the note around them, and replaces it while <em>Editable</em> is on.</li></ul><h2>Included Markdown</h2><p>An included&nbsp;<a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a>&nbsp;note and an embedded Markdown file, such as a <code>.md</code> attachment, are shown with the same three views as a Markdown note in its own tab (see&nbsp;<a class=\"reference-link\" href=\"#root/_help_SL5f1Auq7sVN\">Note types with split view</a>): <span class=\"tn-icon bx bx-code\"></span> <em>Source view</em>, <span class=\"tn-icon bx bxs-dock-left\"></span> <em>Split view</em> and <span class=\"tn-icon bx bx-show\"></span> <em>Preview</em>.</p><ul><li>To switch the view, press one of the three buttons in the title row of the include. In a note being edited, the toolbar of the include has the same buttons after <em>Editable</em>, and its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu has them as <em>Source view</em>, <em>Split view</em> and <em>Preview</em>.</li><li>Until a view is chosen, the include shows the <em>Preview</em>, and the <em>Split view</em> while <em>Editable</em> is on.</li><li>To edit the Markdown, turn on <em>Editable</em> (see <em>Editing an include in place</em> above). The source is edited in the code editor of a Markdown note, and the preview follows the changes as you type. While <em>Editable</em> is off, the source can be read and copied but not changed.</li><li>The source has the slash commands and the <code>@</code> and <code>[[</code> note links of a <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> note. A note created from the <code>@</code> or <code>[[</code> list goes under the included note, or for an embedded file under the note that includes it, and <code>/image</code> uploads the image to that same note.</li><li>The <em>Word wrap</em> and <em>Line numbers</em> submenus of the <em>More actions</em> menu change how the source shows, as for code (see <em>Editing an include in place</em> above).</li><li>As in a Markdown note, the preview scrolls along with the source and highlights the block where the cursor is, and <kbd>Ctrl</kbd>+<kbd>B</kbd>, <kbd>Ctrl</kbd>+<kbd>I</kbd>, <kbd>Ctrl</kbd>+<kbd>M</kbd> and <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd> format the selection.</li><li>In a note being edited, the view is saved with the include, so two includes of the same note can show different views. In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the view can be changed too, until the note is opened again.</li><li>While the source shows, the include has the height of its box size, or the height it was resized to. A <em>Full</em> include gets a fixed height too, instead of fitting its content.</li><li><a class=\"reference-link\" href=\"#root/_help_McngOG2jbUWX\">Search in note</a>&nbsp;searches the source while it shows, and the preview otherwise.</li></ul><h2>Drawing canvases</h2><p>A drawing canvas is an Excalidraw canvas, like the one of a <a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a> note, drawn directly in the text note. It is not a note of its own: the drawing is kept in a <code>Canvas.excalidraw</code> <a href=\"#root/_help_0vhv7lsOLy82\">attachment</a> of the text note and is saved together with the text.</p><ul><li>To insert a drawing canvas, open the <span class=\"tn-icon cke cke-plus\"></span> <em>Insert</em> menu of the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> and choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em>, above <em>Mermaid diagram</em>. It is also available as <em>Drawing canvas</em> in the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>. The canvas is added empty and editable, in a <em>Medium</em> box with its title hidden, and takes the focus, ready for drawing.</li><li>To draw or write over an image, select the image and press the <span class=\"tn-icon bx bxs-pen\"></span> <em>Convert image to a drawing canvas</em> button of its toolbar. The image is replaced by an editable drawing canvas in a <em>Medium</em> box, with its title hidden and the focus in it. The image sits at its original size in the middle of the canvas, zoomed so that all of it shows, and is locked so that it cannot be selected or moved by accident. While it is locked, the canvas can be zoomed in on the image but not zoomed out past it or scrolled beyond its edges. To move or resize the image anyway, right-click it and choose <em>Unlock</em>. The caption of the image is kept, but not its alignment or link. Only an image on its own line can be converted, not one inside a paragraph. Undo brings the image back.</li><li>An Excalidraw file (<code>.excalidraw</code>) attached with the <span class=\"tn-icon cke cke-paper-clip\"></span><em>Attach file</em> button becomes a drawing canvas too, in a <em>Medium</em> box titled with the file name. It starts with <em>Editable</em> off, so the drawing shows but cannot be changed until <em>Editable</em> is turned on (see below).</li><li>To draw on a canvas that does not have the focus, click it first. Until then, touch gestures scroll the note. The canvas then has the tools, menus and keyboard shortcuts of a Canvas note. The toolbars, the menus and the properties of the selected shapes show only while the canvas has the focus, so elsewhere the drawing reads like a picture in the text.</li><li>The mouse wheel and the touchpad scroll the note over a canvas too, as over the text. To zoom, use the zoom buttons of the canvas toolbar; to move around the drawing, use the <span class=\"tn-icon bx bxs-hand\"></span> <em>Hand</em> tool. In fullscreen, the mouse wheel moves and zooms the drawing instead.</li><li>The canvas toolbar replaces the Excalidraw menu: <em>Export image</em>, <em>Find on canvas</em>, <em>Library</em> and <em>Help</em> are at the end of its <span class=\"tn-icon bx bx-category\"></span> <em>More tools</em> menu. In fullscreen, the Excalidraw menu shows again.</li><li>A new drawing has the background color of the note. A background chosen from the Excalidraw menu replaces it.</li><li>To protect a finished drawing from accidental changes, select it and turn off the <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of its toolbar, or uncheck <em>Editable</em> in its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu. The drawing then shows as a still picture, at the zoom and position it had, and can no longer be changed, zoomed or moved. To draw again, turn <em>Editable</em> back on.</li><li>The box sizes, resizing, the caption and the title work as for an included note, but the toolbar of a drawing leaves the box size, <em>Show title</em> and <em>Convert to link</em> to its <em>More actions</em> menu.</li><li>In the desktop layout, Excalidraw keeps its desktop interface however small the box is. In the mobile layout, a narrow or short box switches it to a compact interface. For more room, choose <em>Full</em>, or show the title and press <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em>.</li><li>Pictures added to the drawing are stored in the same attachment. A converted image is kept as an image attachment of the note instead, named with a generated code.</li><li>In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the drawing shows as a still picture too.</li><li>On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, the drawing is shown as a picture at its own size, whatever the size of its box, in light or dark colors to match the page. Each change to the drawing saves this picture as an SVG image attachment of the note, also named with a generated code.</li></ul><h3>Limitations</h3><ul><li>The Excalidraw shape library is not saved for a drawing canvas.</li><li>Outside the editor, for example in a tooltip, when printing or in the list of attachments, the drawing is shown as a picture.</li><li>A drawing has no picture for shared pages until its first change, except one converted from an image. Until then, for example for an attached <code>.excalidraw</code> file, a shared page shows a link to download the drawing instead.</li><li>In Safari, the picture of a drawing on a shared page follows the light or dark appearance of the system rather than the theme chosen on the page.</li><li>A copy of a drawing canvas pasted in the same note shares the drawing with the original, so a change to one shows in the other only after the note is opened again. A copy pasted in another note gets a drawing of its own.</li></ul>",
"_help_CohkqWQC1iBv": "<p>Press the&nbsp;<span class=\"tn-icon cke cke-plus\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>&nbsp;to reveal special inserable items and blocks such as symbols, Math expressions and separators.</p><h2>Bookmarks</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_oSuaNgyyKnhu\">Anchors</a>&nbsp;section.</p><h2>Emoji</h2><figure class=\"image image-style-align-right image_resized\" style=\"width:42.4%;\"><img style=\"aspect-ratio:366/410;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Insert%20buttons_plus.png\" width=\"366\" height=\"410\"></figure><p>This feature allows inserting Unicode emoji characters. Simply select a category and a desired emoji to insert it.</p><p>Emojis can also be searched by their English name and the skin tone can be selected via a combo box to the right.</p><p>There is also the possibility of inserting emojis directly by typing <code>:</code> followed by a name of an emoji, triggering the display of a list of emojis. Simply use the arrow keys to select one and press <kbd>Enter</kbd> or <kbd>Tab</kbd> to insert it.</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Insert%20buttons_plus.png\" width=\"272\" height=\"187\"><h2>Symbols</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:346/322;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Insert%20buttons_image.png\" width=\"346\" height=\"322\"></figure><p>Pressing the&nbsp;<span class=\"tn-icon cke cke-special-characters\"></span> button will reveal a popup window displaying a list of characters that are generally more difficult to insert directly from the keyboard, such as a subset of emojis, quotation characters, etc.</p><p>Interaction:</p><ul><li>Click on a character to insert it at the current cursor position.</li><li>The window can be dragged around by the top bar where the title is, to avoid it getting in the way of the text.</li><li>Click on the <em>Category</em> selector to filter the characters.</li></ul><h2>Multicolumn layout</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a>&nbsp;page.</p><h2>Math equations</h2><p>See the dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a>&nbsp;page.</p><h2>Drawing canvas</h2><p>Choose <span class=\"tn-icon bx bx-pen\"></span> <em>Drawing canvas</em> to draw on an Excalidraw canvas inside the text. See <em>Drawing canvases</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</p><h2>Mermaid diagram</h2><p>Press the&nbsp;<span class=\"tn-icon cke cke-trilium-mermaid-insert\"></span> button to create an inline Mermaid diagram. The arrow next to it lists a template for each kind of diagram. The diagram is also available as <em>Mermaid diagram</em> in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</p><p>This feature is quite similar to the&nbsp;<a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a>&nbsp;note types and is meant as an alternative to it for simple diagrams. For more complex diagrams, use the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>&nbsp;feature for a dedicated Mermaid note.</p><figure class=\"image\"><img style=\"aspect-ratio:1174/358;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Insert%20buttons_image.png\" width=\"1174\" height=\"358\"></figure><p>A diagram shows in a box like the one of an included note, so it can be resized, given another box size (<em>Small</em>, <em>Medium</em> or <em>Full</em>) from its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu or shown in fullscreen, as described in&nbsp;<a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</p><ul><li>The <span class=\"tn-icon bx bx-edit-alt\"></span> <em>Editable</em> button at the start of the diagram's toolbar decides whether its source can be changed. While it is off, the source still shows, but read-only.</li><li>The buttons next to it choose what the diagram shows, as for a Mermaid note: <span class=\"tn-icon bx bx-code\"></span> <em>Source view</em> for the Mermaid source alone, <span class=\"tn-icon bx bxs-dock-left\"></span> <em>Split view</em> for the source with the diagram next to it, and <span class=\"tn-icon bx bx-show\"></span> <em>Preview</em> for the diagram alone. Its <em>More actions</em> menu offers the same choice.</li><li>The <em>Word wrap</em> and <em>Line numbers</em> submenus of its <em>More actions</em> menu change how the source shows, each with <em>Auto</em>, <em>On</em> and <em>Off</em>, as for an included code note (see <em>Editing an include in place</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>).</li><li>A new diagram starts editable, in <em>Split view</em>. The diagram updates a moment after you stop typing. If the source has an error, the error shows over the last diagram that worked, which stays dimmed, as in a Mermaid note. On desktop, drag the divider between the source and the diagram to resize them.</li><li>A diagram without a chosen view shows the source next to the diagram while it is editable, and the diagram alone otherwise. In a read-only note, the source can never be changed. A read-only note and the AI chat show a diagram in the same box, in the view it was saved with, and with the zoom buttons over the diagram instead of in a toolbar. A <em>Medium</em> or <em>Full</em> diagram also has a <span class=\"tn-icon bx bx-fullscreen\"></span> <em>Fullscreen</em> button there, or over the source in the <em>Source</em> view.</li><li>To zoom, use the <span class=\"tn-icon bx bx-zoom-out\"></span> and <span class=\"tn-icon bx bx-zoom-in\"></span> buttons of the diagram's toolbar; the zoom level between them resets the zoom. In fullscreen, where the toolbar is hidden, the same buttons show over the diagram. Drag the diagram to move around it, and double-click it to reset the view. The mouse wheel scrolls the note until you click the diagram, and then zooms it.</li><li>While the source shows, the <span class=\"tn-icon bx bx-help-circle\"></span> <em>Mermaid syntax help</em> button at the end of the toolbar opens the help on&nbsp;<a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a>, which links to the Mermaid syntax.</li><li>Undo in the text note also undoes the changes made to the source of a diagram.</li></ul><p>The source of the diagram stays in the note as a Mermaid code block, so the diagram is exported to Markdown as a <code>mermaid</code> code block that other applications can show.</p><p>Diagrams created in earlier versions keep the view they were saved with, and open editable.</p><h2>Horizontal ruler</h2><p>This feature will display a horizontal line, generally useful to separate different sections of the text. To do so, press the&nbsp;<span class=\"tn-icon cke cke-horizontal-line\"></span> button in the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>.</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Insert%20buttons_image.png\" width=\"502\" height=\"95\"><p>Alternatively, it's possible to insert a horizontal ruler by typing <code>---</code>.</p><h2>Page break</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:371/79;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/3_Insert%20buttons_image.png\" width=\"371\" height=\"79\"></figure><p>Page breaks provide a way to force the next paragraph or block (table, image, etc.) to be displayed onto the next page when printing (either to a real printer to <a href=\"#root/_help_NRnIZmSMc5sj\">when exporting to PDF</a>).</p><p>Page breaks are marked in the editor with the words <em>Page break</em>, but they will not actually be shown when printed.</p><ul><li>To insert a page break, press the&nbsp;<span class=\"tn-icon cke cke-page-break\"></span> in the formatting toolbar.</li><li>To insert many page breaks at once, insert a page break first, click on it and press <kbd>Ctrl</kbd>+<kbd>C</kbd>. Then use <kbd>Ctrl</kbd>+<kbd>V</kbd>, to paste as many times as needed.</li></ul><h2>Date and time</h2><p>The <span class=\"tn-icon cke cke-trilium-date-time\"></span> button inserts the current date and time at the cursor, replacing the selected text if there is any. The inserted text takes the formatting of the text around it, so a date inserted inside bold text is bold too.</p><ul><li>To insert the date in the default format, press the button itself or press <kbd>Alt</kbd>+<kbd>T</kbd>.</li><li>To insert it in another format, press the arrow next to the button and pick a format from the list. Each entry shows the current date and time in that format: the default one, the date or the time alone, the date written out, and ISO 8601.</li><li>The same formats are offered by the <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>: type <code>/date</code>, <code>/time</code>, <code>/now</code> or <code>/today</code>. The <em>Insert date/time</em> entry uses the default format, and shows what it inserts underneath; the other entries show their output in the title.</li></ul><p>The default format can be changed in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text Notes</em> → <em>Editor</em> → <em>Date/time format</em>, using <a href=\"https://day.js.org/docs/en/display/format\">Day.js format tokens</a> (for example <code>DD.MM.YYYY HH:mm</code>).</p><h2>Icons</h2><p>Icons just like the ones for the <a href=\"#root/_help_p9kXRFAkwN4o\">note icon</a> can be inserted in text. For more information see&nbsp;<a class=\"reference-link\" href=\"#root/_help_hD8GawVuazff\">Icons</a>.</p>",
"_help_hD8GawVuazff": "<p>Icons just like the <a href=\"#root/_help_hD8GawVuazff\">note icons</a> can be inserted in the content of a note, including from any other <a href=\"#root/_help_gOKqSJgXLcIj\">custom icon packs</a>.</p><h2>Features</h2><ul><li>The icon can be formatted through the<a class=\"reference-link\" href=\"#root/_help_Gr6xFaF6ioJ5\">General formatting</a>&nbsp;tools of the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>:<ul><li>Foreground/icon color</li><li>Background color/highlight</li><li>Font size</li></ul></li><li>Custom&nbsp;<a class=\"reference-link\" href=\"#root/_help_gOKqSJgXLcIj\">Icon Packs</a>&nbsp;are also supported.<ul><li>For emojis, prefer the Emoji functionality from&nbsp;<a class=\"reference-link\" href=\"#root/_help_CohkqWQC1iBv\">Insert buttons</a>.</li></ul></li><li>When an icon is clicked a floating toolbar appears with the following functions:<ul><li><span class=\"tn-icon bx bx-sticker\"></span>&nbsp;which changes the icon.</li><li><span class=\"tn-icon bx bx-reflect-horizontal\"></span>&nbsp;which applies transforms: rotate (90 / 180 / 270) and flip horizontal/vertical. Only one transform can be used per icon.</li></ul></li></ul><h2>Usage</h2><ul><li>The in-app help/user guide makes use of these icons in order to illustrate buttons in the UI.</li><li>The&nbsp;<a class=\"reference-link\" href=\"#root/_help_GnhlmrATVqcH\">Microsoft OneNote</a>&nbsp;importer also makes use of them for the&nbsp;<a class=\"reference-link\" href=\"#root/_help_LpvyEIBIAAj7\">Tags</a>.</li></ul><h2>Inserting an icon</h2><p>There are two ways to insert an icon:</p><ul><li>Via the&nbsp;<a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>&nbsp;look for the&nbsp;<span class=\"tn-icon bx bx-plus\"></span> icon and then the&nbsp;<span class=\"tn-icon bx bx-sticker\"></span> icon.</li><li>Via&nbsp;<a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>, type <code>/icon</code>.</li></ul><p>An icon picker will appear, search for an icon and click it to insert it in the document.</p><h2>Finding notes by their icons</h2><p>An icon can be <a href=\"#root/_help_eIg8jdvaoNNd\">searched</a>. A note containing a&nbsp;<span class=\"tn-icon bx bx-star\"></span> icon can be found by searching for <code>star</code>, or its <code>iconClass</code> (<code>bx-star</code>).</p><p>To find the name of the icon, hover the mouse over an icon while in the icon picker.</p><h2>Markdown rendering</h2><p>When exporting to&nbsp;<a class=\"reference-link\" href=\"#root/_help_Oau6X9rCuegd\">Markdown</a>, the item will render as raw HTML representation of the icon as is used by Trilium:</p><pre><code class=\"language-text-html\">&lt;span class=\"tn-icon bx bx-star\"&gt;&lt;/span&gt;</code></pre>",
"_help_oiVPnW8QfnvS": "<h2>Trilium-specific shortcuts</h2><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Bring up inline formatting toolbar (arrow keys ←,→ to navigate, Enter to apply)</td><td>Alt+F10</td><td>⌥+F10</td></tr><tr><td>Bring up block formatting toolbar</td><td>Alt+F10</td><td>⌥+F10</td></tr><tr><td>Create <a href=\"#root/_help_QEAPj01N5f7w\">external link</a></td><td>Ctrl+K</td><td>⌘+K</td></tr><tr><td>Create <a href=\"#root/_help_QEAPj01N5f7w\">internal (note) link</a></td><td>Ctrl+L</td><td>⌘+L</td></tr><tr><td>Inserts current date and time at caret position</td><td>Alt+T</td><td>⌥+T</td></tr><tr><td>Increase paragraph indentation</td><td>Tab</td><td>⇥</td></tr><tr><td>Decrease paragraph indentation</td><td>Shift + Tab</td><td>⇧ + ⇥</td></tr><tr><td>Mark selected text as <a href=\"#root/_help_UYuUB1ZekNQU\">keyboard shortcut</a></td><td>Ctrl + Alt + K</td><td>⌘+ ⌥+ K</td></tr><tr><td>Insert&nbsp;<a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a></td><td>Ctrl + M</td><td>⌘+ M</td></tr><tr><td>Move blocks (lists, paragraphs, etc.) up</td><td>Ctrl+↑</td><td>⌘+↑</td></tr><tr><td>Alt+↑</td><td>⌥+↑</td><td></td></tr><tr><td>Move blocks (lists, paragraphs, etc.) down</td><td>Ctrl+↑</td><td>⌘+↑</td></tr><tr><td>Alt+↓</td><td>⌥+↓</td><td></td></tr><tr><td>Move the selected content to another column of a <a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a></td><td>Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End</td><td>⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End</td></tr><tr><td>Move the current column of a multicolumn layout</td><td>Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End</td><td>⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End</td></tr><tr><td>Add a column after or before the current one in a multicolumn layout</td><td>Ctrl+Enter, Ctrl+Shift+Enter</td><td>⌘+Enter, ⌘+⇧+Enter</td></tr><tr><td>Move the selected content to another tab in <a class=\"reference-link\" href=\"#root/_help_EK2ckIZ74tbT\">Content tabs</a></td><td>Ctrl+←, Ctrl+→, Ctrl+Shift+Home, Ctrl+Shift+End</td><td>⌘+←, ⌘+→, ⌘+⇧+Home, ⌘+⇧+End</td></tr><tr><td>Move the current tab of a tabs block</td><td>Ctrl+Alt+←, Ctrl+Alt+→, Ctrl+Alt+Home, Ctrl+Alt+End</td><td>⌘+⌥+←, ⌘+⌥+→, ⌘+⌥+Home, ⌘+⌥+End</td></tr><tr><td>Add a tab after or before the current one in a tabs block</td><td>Ctrl+Enter, Ctrl+Shift+Enter</td><td>⌘+Enter, ⌘+⇧+Enter</td></tr></tbody></table></figure><h2>Common shortcuts</h2><aside class=\"admonition tip\"><p>This section of keyboard shortcuts presents a subset of the keyboard shortcuts as supported by the editor technology we are using,&nbsp;<a class=\"reference-link\" href=\"#root/_help_MI26XDLSAlCD\">CKEditor</a>. The shortcuts were taken from the <a href=\"https://ckeditor.com/docs/ckeditor5/latest/features/accessibility.html#keyboard-shortcuts\">official documentation</a>. Note that not all the shortcuts in the original documentation are applicable (due to using a different configuration).</p></aside><h3>Content editing</h3><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Insert a hard break (a new paragraph)</td><td>Enter</td><td></td></tr><tr><td>Insert a soft break (a <code>&lt;br&gt;</code> element)</td><td>Shift+Enter</td><td>⇧Enter</td></tr><tr><td>Copy selected content</td><td>Ctrl+C</td><td>⌘C</td></tr><tr><td>Paste content</td><td>Ctrl+V</td><td>⌘V</td></tr><tr><td>Paste content as plain text</td><td>Ctrl+Shift+V</td><td>⌘⇧V</td></tr><tr><td>Undo</td><td>Ctrl+Z</td><td>⌘Z</td></tr><tr><td>Redo</td><td>Ctrl+Y, Ctrl+Shift+Z</td><td>⌘Y, ⌘⇧Z</td></tr><tr><td>Bold text</td><td>Ctrl+B</td><td>⌘B</td></tr><tr><td>Change text case</td><td>Shift+F3</td><td>⇧F3 (may require Fn)</td></tr><tr><td>Create link</td><td>Ctrl+K</td><td>⌘K</td></tr><tr><td>Move out of a link</td><td>←←, →→</td><td></td></tr><tr><td>Move out of an inline code style</td><td>←←, →→</td><td></td></tr><tr><td>Select all</td><td>Ctrl+A</td><td>⌘A</td></tr><tr><td>Find in the document</td><td>Ctrl+F</td><td>⌘F</td></tr><tr><td>Copy text formatting</td><td>Ctrl+Shift+C</td><td>⌘⇧C</td></tr><tr><td>Paste text formatting</td><td>Ctrl+Shift+V</td><td>⌘⇧V</td></tr><tr><td>Italic text</td><td>Ctrl+I</td><td>⌘I</td></tr><tr><td>Strikethrough text</td><td>Ctrl+Shift+X</td><td>⌘⇧X</td></tr><tr><td>Underline text</td><td>Ctrl+U</td><td>⌘U</td></tr><tr><td>Revert autoformatting action</td><td>Backspace</td><td></td></tr></tbody></table></figure><h3>Interacting with blocks</h3><p>Blocks are images, tables, blockquotes, annotations.</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Insert a new paragraph directly after a widget</td><td>Enter</td><td></td></tr><tr><td>Insert a new paragraph directly before a widget</td><td>Shift+Enter</td><td>⇧Enter</td></tr><tr><td>Move the caret to allow typing directly before a widget</td><td>↑, ←</td><td></td></tr><tr><td>Move the caret to allow typing directly after a widget</td><td>↓, →</td><td></td></tr><tr><td>After entering a nested editable, move the selection to the closest ancestor widget. For example: move from an image caption to the whole image widget.</td><td>Tab then Esc</td><td></td></tr></tbody></table></figure><p>Specifically for lists:</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Increase list item indent</td><td>⇥</td><td></td></tr><tr><td>Decrease list item indent</td><td>Shift+⇥</td><td>⇧⇥</td></tr></tbody></table></figure><p>In tables:</p><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Move the selection to the next cell</td><td>⇥</td><td></td></tr><tr><td>Move the selection to the previous cell</td><td>Shift+⇥</td><td>⇧⇥</td></tr><tr><td>Insert a new table row (when in the last cell of a table)</td><td>⇥</td><td></td></tr><tr><td>Navigate through the table</td><td>↑, →, ↓, ←</td><td></td></tr></tbody></table></figure><h3>General UI shortcuts</h3><figure class=\"table\"><table><thead><tr><th>Action</th><th>PC</th><th>Mac</th></tr></thead><tbody><tr><td>Close contextual balloons, dropdowns, and dialogs</td><td>Esc</td><td></td></tr><tr><td>Open the accessibility help dialog</td><td>Alt+0</td><td>⌥0</td></tr><tr><td>Move focus between form fields (inputs, buttons, etc.)</td><td>⇥, Shift+⇥</td><td>⇥, ⇧⇥</td></tr><tr><td>Move focus to the toolbar, navigate between toolbars</td><td>Alt+F10</td><td>⌥F10 (may require Fn)</td></tr><tr><td>Navigate through the toolbar or menu bar</td><td>↑, →, ↓, ←</td><td></td></tr><tr><td>Navigate to the next focusable field or an element outside the editor</td><td>Tab, Shift+Tab</td><td></td></tr><tr><td>Execute the currently focused button. Executing buttons that interact with the editor content moves the focus back to the content.</td><td>Enter, Space</td><td></td></tr><tr><td>Move focus in and out of an active dialog window</td><td>Ctrl+F6</td><td>⌘F6 (may require Fn)</td></tr></tbody></table></figure>",
@@ -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.&nbsp;</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&nbsp;<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&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;note</li><li>Via the <em>Create note</em> or <em>Create child note</em> options of the note search (new tab or&nbsp;<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&nbsp;<a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>&nbsp;context menu (<em>Insert child note</em>, <em>Insert note after</em>) still creates it at the chosen place.</p><p>Unlike the&nbsp;<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&nbsp;<a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>&nbsp;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&nbsp;<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.&nbsp;<a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>&nbsp;→ <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&nbsp;<a class=\"reference-link\" href=\"#root/_help_6tZeKvSHEUiB\">Demo Notes</a>, including examples like the&nbsp;<a class=\"reference-link\" href=\"#root/_help_iRwzGnHPzonm\">Relation Map</a>,&nbsp;<a class=\"reference-link\" href=\"#root/_help_xYjQUYhpbUEW\">Task Manager</a>, and&nbsp;<a class=\"reference-link\" href=\"#root/_help_l0tKav7yLHGF\">Day Notes</a>.</p><p>Additionally, see&nbsp;<a class=\"reference-link\" href=\"#root/_help_47ZrP6FNuoG8\">Default Note Title</a>&nbsp;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&nbsp;<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&nbsp;<a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a>&nbsp;note.</p><h2>Creating a Markdown snippet</h2><p>In the&nbsp;<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&nbsp;<a class=\"reference-link\" href=\"#root/_help_OFXdgB2nNk1F\">Promoted Attributes</a>&nbsp;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>&nbsp;with their language mode set to \"Plain text\" are also listed here.</p><h2>Limitations</h2><ul><li>Unlike&nbsp;<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&nbsp;<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&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;note.</p><h2>Creating a Code snippet</h2><p>In the&nbsp;<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&nbsp;<a class=\"reference-link\" href=\"#root/_help_OFXdgB2nNk1F\">Promoted Attributes</a>&nbsp;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&nbsp;<a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a>&nbsp;notes and any code note regardless of its language mode.</p></aside><h2>Limitations</h2><ul><li>Unlike&nbsp;<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&nbsp;<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&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;note.</p><h2>Creating a Code snippet</h2><p>In the&nbsp;<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&nbsp;<a class=\"reference-link\" href=\"#root/_help_OFXdgB2nNk1F\">Promoted Attributes</a>&nbsp;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&nbsp;<a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a>&nbsp;notes and any code note regardless of its language mode.</p></aside><h2>Limitations</h2><ul><li>Unlike&nbsp;<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&nbsp;<a class=\"reference-link\" href=\"#root/_help_KRlZFoIH0j6p\">Connections tab</a>&nbsp;in the&nbsp;<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&nbsp;<a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a>&nbsp;→ <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&nbsp;<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&nbsp;<a class=\"reference-link\" href=\"#root/_help_RnaPdbciOfeq\">Right Sidebar</a>, the root node is the current note.</li><li>When using a dedicated&nbsp;<a class=\"reference-link\" href=\"#root/_help_bdUJEHsAPYQR\">Note Map</a>&nbsp;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>&nbsp;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&nbsp;<a class=\"reference-link\" href=\"#root/_help_Cq5X6iKQop6R\">Relations</a>&nbsp;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>&nbsp;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&nbsp;<a class=\"reference-link\" href=\"#root/_help_RnaPdbciOfeq\">Right Sidebar</a>&nbsp;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&nbsp;<a class=\"reference-link\" href=\"#root/_help_bdUJEHsAPYQR\">Note Map</a>&nbsp;for more information.</li><li><a class=\"reference-link\" href=\"#root/_help_iRwzGnHPzonm\">Relation Map</a>&nbsp;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>&nbsp;</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>&nbsp;</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&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>Code Notes</em> is not highlighted.</li></ul></td><td>&nbsp;</td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a></th><td>Not supported.</td><td>&nbsp;</td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_iRwzGnHPzonm\">Relation Map</a></th><td>Not supported.</td><td>&nbsp;</td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_bdUJEHsAPYQR\">Note Map</a></th><td>Not supported.</td><td>&nbsp;</td></tr><tr><th><a class=\"reference-link\" href=\"#root/_help_HcABDtFCkbFN\">Render Note</a></th><td>Not supported.</td><td>&nbsp;</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>&nbsp;</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>&nbsp;</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>&nbsp;</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&nbsp;<a class=\"reference-link\" href=\"#root/_help_WOcw2SLH6tbX\">Server Installation</a>&nbsp;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&nbsp;<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&nbsp;<a class=\"reference-link\" href=\"#root/_help_wX4HbRucYSDD\">Database</a>. Depending on your threat model, it might make more sense to use&nbsp;<a class=\"reference-link\" href=\"#root/_help_ycBFjKrrwE9p\">Exporting static HTML for web publishing</a>&nbsp;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&nbsp;<a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a>&nbsp;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>&lt;head&gt;</code> section</li><li><code>#shareHtmlLocation=head:end</code> - Injects HTML at the end of the <code>&lt;head&gt;</code> section (default)</li><li><code>#shareHtmlLocation=body:start</code> - Injects HTML at the beginning of the <code>&lt;body&gt;</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&nbsp;<a class=\"reference-link\" href=\"#root/_help_eIg8jdvaoNNd\">Search</a>&nbsp;with <code>#!shareAlias</code>.</li><li>To be able to enter the share alias faster, consider using&nbsp;<a class=\"reference-link\" href=\"#root/_help_OFXdgB2nNk1F\">Promoted Attributes</a>&nbsp;(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&nbsp;<a class=\"reference-link\" href=\"#root/_help_Qjt68inQ2bRj\">Serving directly the content of a note</a>&nbsp;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>&nbsp; <br><code>~shareOpenGraphImage</code></td><td>Can be either a label with the address of an image, or a relation to an image&nbsp;<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 --git a/docs/User Guide/User Guide/Advanced Usage/Snippets/Code Snippets.md b/docs/User Guide/User Guide/Advanced Usage/Snippets/Code Snippets.md
index f546c3fd98..1938ea3322 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 `/` 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>.
> [!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/Note Types/Text/Include Note.md b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
index 1a8a7098ff..3d6a0824e5 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Include Note.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Include Note.md
@@ -112,6 +112,7 @@ An included text note, an included code note and an embedded code file such as a
* While _Editable_ is on, the arrow keys move the caret into the include and back out, as through the rest of the text. Entering from above or from the left puts the caret at the start of the include, and entering from below or from the right puts it at the end. A collapsed _Expandable_ include is skipped.
* While an included text note has the focus, the formatting toolbar applies to it. The notes it includes in turn stay read-only.
* Code is edited in the same code editor as a <a class="reference-link" href="../Code.md">Code</a> note, with its theme, indentation and line wrapping settings.
+* Typing `/` in the code lists the <a class="reference-link" href="../../Advanced%20Usage/Snippets/Code%20Snippets.md">Code Snippets</a> of its language, as in a code note.
* The toolbar of an included code note or an embedded code file also has the language and indentation menus of the <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Status%20bar.md">Status bar</a>, between _Editable_ and the _Box size_ menu: _Change language mode_, which shows the current language, and _Change tab width_, which shows the current indentation. _Re-indent content to_ converts the indentation of the code itself and saves it to the included note or file, whether _Editable_ is on or off.
* For an included note, the menus change the note, as they do in its own tab.
* For an embedded code file, the language and indentation settings change only how this include shows the file, and are saved with the note that includes it. The language replaces the one that the file name gives, and the _Use default_ entries return to the indentation set in <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Code Notes_. These settings leave the file itself unchanged, and other includes of it keep their own settings.
@@ -130,6 +131,7 @@ An included <a class="reference-link" href="../Markdown.md">Markdown</a> note
* To switch the view, press one of the three buttons in the title row of the include. In a note being edited, the toolbar of the include has the same buttons after _Editable_, and its <span class="tn-icon cke cke-three-vertical-dots"></span> _More actions_ menu has them as _Source view_, _Split view_ and _Preview_.
* Until a view is chosen, the include shows the _Preview_, and the _Split view_ while _Editable_ is on.
* To edit the Markdown, turn on _Editable_ (see _Editing an include in place_ above). The source is edited in the code editor of a Markdown note, and the preview follows the changes as you type. While _Editable_ is off, the source can be read and copied but not changed.
+* The source has the slash commands and the `@` and `[[` note links of a <a class="reference-link" href="../Markdown.md">Markdown</a> note. A note created from the `@` or `[[` list goes under the included note, or for an embedded file under the note that includes it, and `/image` uploads the image to that same note.
* The _Word wrap_ and _Line numbers_ submenus of the _More actions_ menu change how the source shows, as for code (see _Editing an include in place_ above).
* As in a Markdown note, the preview scrolls along with the source and highlights the block where the cursor is, and <kbd>Ctrl</kbd>+<kbd>B</kbd>, <kbd>Ctrl</kbd>+<kbd>I</kbd>, <kbd>Ctrl</kbd>+<kbd>M</kbd> and <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd> format the selection.
* In a note being edited, the view is saved with the include, so two includes of the same note can show different views. In a [read-only note](../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md), the view can be changed too, until the note is opened again.
diff --git a/packages/codemirror/src/extensions/hosted_completion.ts b/packages/codemirror/src/extensions/hosted_completion.ts
index 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, list
constructor(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, list
destroy() {
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, list
return 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.ts
index 05342d494a..8cc7af6715 100644
--- a/packages/codemirror/src/index.spec.ts
+++ b/packages/codemirror/src/index.spec.ts
@@ -4,6 +4,7 @@ import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";
import { EditorView, showTooltip, type ViewUpdate } from "@codemirror/view";
import { afterEach, describe, expect, it, vi } from "vitest";
+import { hostedCompletion } from "./extensions/hosted_completion.js";
import CodeMirror, { type EditorConfig, getThemeById } from "./index.js";
let editor: CodeMirror | undefined;
@@ -464,6 +465,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", () => {
diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.ts
index 1fde02f558..cf31dc8255 100644
--- a/packages/codemirror/src/index.ts
+++ b/packages/codemirror/src/index.ts
@@ -10,6 +10,7 @@ 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 { isHostedCompletionShown } from "./extensions/hosted_completion.js";
import { buildTypeCompletion, type ScriptApiContext } from "./type_completion/index.js";
export { default as ColorThemes, type ThemeDefinition, type ThemeVariant, getThemeById } from "./color_themes.js";
@@ -354,7 +355,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;
}