Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/code embed: allow toggling word wrap and line numbering

Adorian Doran94f523328deb
diff --git a/.claude/skills/developing-content-embeds/SKILL.md b/.claude/skills/developing-content-embeds/SKILL.md
index 6cd05ae630..b1fff0b2df 100644
--- a/.claude/skills/developing-content-embeds/SKILL.md
+++ b/.claude/skills/developing-content-embeds/SKILL.md
@@ -99,6 +99,15 @@ embeds receive `SourceEmbedProps` (`content`, `editor`) whichever storage the so
- `hasEditableFlag` — shows the Editable toggle; the embed carries `data-editable="true"`.
- `hasDisplayModes` — shows Source/Split/Preview; the embed carries `data-display-mode`.
- `hiddenToolbarItems` — moves box size, title or convert-to-link from the toolbar to the ⋮ menu.
+ - `getMenuItems()` — items of the ⋮ menu after Editable, in a group of their own
+ (`useContentEmbedMenus(rootRef, menus, menuItems)` passes them through).
+- **A CodeMirror pane in an embed** (code, Markdown, Mermaid) takes its line wrapping and line
+ numbers from `useEmbedLines(rootRef, note)` (`code/CodeEmbed.tsx`): pass `wrapLines` /
+ `hasLineNumbers` to `EmbedSourcePane` or `CodeEmbedEditor`, and `menuItems` (the _Word wrap_
+ and _Line numbers_ submenus) to `getMenuItems()` while the content can be edited. A note keeps
+ the wrapping in `#wrapLines`; everything else lives in `data-code-wrap-lines` /
+ `data-code-line-numbers`, on the `<pre>` for inline source (the code view command sets only
+ line numbers on a note embed). `ReadOnlyText` copies them from the `<pre>` to its box.
- `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/menus/context_menu.ts b/apps/client/src/menus/context_menu.ts
index c3290532e7..04d114a23d 100644
--- a/apps/client/src/menus/context_menu.ts
+++ b/apps/client/src/menus/context_menu.ts
@@ -49,6 +49,8 @@ export interface MenuItemBadge {
export interface MenuCommandItem<T> {
title: string;
+ /** A second line below the title, in smaller text. */
+ description?: string;
command?: T;
type?: string;
mime?: string;
diff --git a/apps/client/src/menus/link_context_menu.spec.ts b/apps/client/src/menus/link_context_menu.spec.ts
index e46ccaa33a..f2fe9d0b37 100644
--- a/apps/client/src/menus/link_context_menu.spec.ts
+++ b/apps/client/src/menus/link_context_menu.spec.ts
@@ -75,6 +75,7 @@ vi.mock("../components/app_context", () => ({
}
}));
+import { registerContentEmbedTools } from "../widgets/type_widgets/text/content_embed_tools";
import linkContextMenu from "./link_context_menu";
const VIEW_SCOPE = { viewMode: "attachments" as const, attachmentId: "att-1" };
@@ -628,6 +629,45 @@ describe("openContextMenu", () => {
]);
});
+ it("offers the items of its content after Editable, in a group of their own", async () => {
+ state = { ...state, isEditable: true, isEditableToggleable: true };
+ const content = embed().querySelector<HTMLElement>(".include-note-content");
+ if (!content) throw new Error("Expected the content box.");
+ const wrap = { title: "Word wrap", items: [] };
+ const lineNumbers = { title: "Show line numbers", checked: true };
+ const unregister = registerContentEmbedTools(content, {
+ getTools: () => [],
+ execute: () => {},
+ subscribe: () => () => {},
+ getMenuItems: () => [ wrap, lineNumbers ]
+ });
+
+ try {
+ expect((await openOn(editable.querySelector("a"))).slice(6, 12)).toMatchObject([
+ { kind: "separator" },
+ { title: "link_context_menu.editable" },
+ wrap,
+ lineNumbers,
+ { kind: "separator" },
+ { title: "link_context_menu.include_size" }
+ ]);
+
+ // Before the display modes, which follow in a group of their own.
+ state = { ...state, displayMode: "split" };
+ expect((await openOn(editable.querySelector("a"))).slice(9, 16)).toMatchObject([
+ lineNumbers,
+ { kind: "separator" },
+ { title: "display_mode.source" },
+ { title: "display_mode.split" },
+ { title: "display_mode.preview" },
+ { kind: "separator" },
+ { title: "link_context_menu.include_size" }
+ ]);
+ } finally {
+ unregister();
+ }
+ });
+
it("appends the commands of an embedded note, its conversion in a group of its own", async () => {
embed().removeAttribute("data-attachment-id");
embed().setAttribute("data-note-id", "n1");
diff --git a/apps/client/src/menus/link_context_menu.ts b/apps/client/src/menus/link_context_menu.ts
index e5ca7f9ccd..076a128aab 100644
--- a/apps/client/src/menus/link_context_menu.ts
+++ b/apps/client/src/menus/link_context_menu.ts
@@ -10,6 +10,7 @@ import { t } from "../services/i18n.js";
import type { ViewScope } from "../services/link.js";
import utils, { escapeHtml, isMobile, isShare } from "../services/utils.js";
import { DISPLAY_MODE_OPTIONS } from "../widgets/type_widgets/helpers/split_editor_mode.js";
+import { getContentEmbedTools } from "../widgets/type_widgets/text/content_embed_tools.js";
import { getClosestNtxId } from "../widgets/widget_utils.js";
import contextMenu, { type ContextMenuOptions, type MenuItem } from "./context_menu.js";
import { submenuItem } from "./context_menu_utils.js";
@@ -295,8 +296,9 @@ function getMenuEmbed(e: LinkMenuOrigin, editor: CKTextEditor): MenuEmbed | null
}
/**
- * The commands that the toolbar of an embed offers, with what each shows checked. Editable is
- * offered only for content that has an editable mode.
+ * The commands that the toolbar of an embed offers, with what each shows checked, and the items
+ * that its content adds after Editable. Editable is offered only for content that has an editable
+ * mode.
*/
function getEmbedItems(embed: MenuEmbed): MenuItem<CommandNames>[] {
const { editor, state } = embed;
@@ -312,6 +314,7 @@ function getEmbedItems(embed: MenuEmbed): MenuItem<CommandNames>[] {
checked: state.isEditable,
handler: () => runEmbedCommand(embed, "toggleContentEmbedEditable")
} ] : [];
+ const contentItems = getContentEmbedTools(embed.element)?.getMenuItems?.() ?? [];
const displayModeItems = state.displayMode
? DISPLAY_MODE_OPTIONS.map(({ value, icon, titleKey }): MenuItem<CommandNames> => ({
title: t(titleKey),
@@ -323,6 +326,8 @@ function getEmbedItems(embed: MenuEmbed): MenuItem<CommandNames>[] {
return [
...editableItems,
+ ...contentItems,
+ ...(contentItems.length ? [ { kind: "separator" } as const ] : []),
...displayModeItems,
...(displayModeItems.length ? [ { kind: "separator" } as const ] : []),
submenuItem({
diff --git a/apps/client/src/services/code_note_preview.spec.ts b/apps/client/src/services/code_note_preview.spec.ts
index 40825d91b5..357126d0fd 100644
--- a/apps/client/src/services/code_note_preview.spec.ts
+++ b/apps/client/src/services/code_note_preview.spec.ts
@@ -67,6 +67,17 @@ describe("renderCodeNotePreview", () => {
expect(await isWrapped(buildNote({ title: "On", "#wrapLines": "" }))).toBe(true);
});
+ it("wraps and numbers the lines as an embed sets, over the note and the option", async () => {
+ const { renderCodeNotePreview } = await freshModule({ codeLineWrapEnabled: "true" });
+ const note = buildNote({ title: "On", "#wrapLines": "" });
+ const render = (lines: Parameters<PreviewModule["renderCodeNotePreview"]>[3]) =>
+ renderCodeNotePreview(CODE, "text/javascript", note, lines);
+
+ expect((await render({})).className).toBe("code-preview code-preview-wrap");
+ expect((await render({ isWrapped: false, hasLineNumbers: false })).className)
+ .toBe("code-preview code-preview-no-line-numbers");
+ });
+
it("shows code too long to highlight plain, still numbered", async () => {
const { renderCodeNotePreview } = await freshModule({});
const long = Array.from({ length: 600 }, () => "let a = 1;").join("\n");
diff --git a/apps/client/src/services/code_note_preview.ts b/apps/client/src/services/code_note_preview.ts
index 70e10a081a..922b27f901 100644
--- a/apps/client/src/services/code_note_preview.ts
+++ b/apps/client/src/services/code_note_preview.ts
@@ -27,25 +27,40 @@ const cache = new Map<string, string>();
let cacheLength = 0;
const mountedThemes = new Set<string>();
+/** How a code preview shows its lines. */
+export interface CodePreviewLines {
+ /** Whether to wrap the lines, over the `#wrapLines` label of the note and the option. */
+ isWrapped?: boolean;
+ /** Whether to number the lines. Defaults to true. */
+ hasLineNumbers?: boolean;
+}
+
/**
* Renders `content` as CodeMirror shows it in a code note: in the colors of the code note themes,
* with line numbers.
*
* @param note the note whose `#wrapLines` label sets the line wrapping, over the option.
*/
-export async function renderCodeNotePreview(content: string, mime: string, note?: FNote | null) {
+export async function renderCodeNotePreview(
+ content: string,
+ mime: string,
+ note?: FNote | null,
+ lines: CodePreviewLines = {}
+) {
const [ themes, language ] = await Promise.all([
Promise.all(getThemeChoices().map(loadSlot)),
shouldSyntaxHighlight(content) ? loadPreviewLanguage(mime) : null
]);
- const isWrapped = isLineWrapped(note);
+ const isWrapped = lines.isWrapped ?? isLineWrapped(note);
+ const hasLineNumbers = lines.hasLineNumbers ?? true;
const cacheKey = [
- ...themes.map(({ theme, key }) => `${key}:${theme.id}`), mime, isWrapped, content
+ ...themes.map(({ theme, key }) => `${key}:${theme.id}`), mime, isWrapped, hasLineNumbers,
+ content
].join("\0");
let html = cache.get(cacheKey);
if (html === undefined) {
- html = renderCodePreview(content, { themes, language, isWrapped });
+ html = renderCodePreview(content, { themes, language, isWrapped, hasLineNumbers });
remember(cacheKey, html);
}
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.ts
index 45b1aca5f8..df7cfea02e 100644
--- a/apps/client/src/services/content_renderer.spec.ts
+++ b/apps/client/src/services/content_renderer.spec.ts
@@ -28,11 +28,14 @@ const renderServiceRender = vi.fn(async (...args: any[]) => {
});
vi.mock("./render.js", () => ({ default: { render: (...args: any[]) => renderServiceRender(...args) } }));
-const renderCodeNotePreview = vi.fn(async (content: string, _mime: string, _note?: unknown) => (
- $("<pre>").append($("<code>").text(content))[0]
-));
+const renderCodeNotePreview = vi.fn(
+ async (content: string, _mime: string, _note?: unknown, _lines?: unknown) => (
+ $("<pre>").append($("<code>").text(content))[0]
+ )
+);
vi.mock("./code_note_preview.js", () => ({
- renderCodeNotePreview: (...args: [ string, string, unknown ]) => renderCodeNotePreview(...args)
+ renderCodeNotePreview: (...args: [ string, string, unknown, unknown ]) =>
+ renderCodeNotePreview(...args)
}));
const setupContextMenu = vi.fn((..._args: any[]) => {});
@@ -372,7 +375,7 @@ describe("getRenderedContent code rendering", () => {
expect(type).toBe("code");
expect($renderedContent.find("pre > code").text()).toBe('{\n "a": 1\n}');
expect(renderCodeNotePreview.mock.calls)
- .toEqual([ [ '{\n "a": 1\n}', "application/json", note ] ]);
+ .toEqual([ [ '{\n "a": 1\n}', "application/json", note, {} ] ]);
});
it("leaves invalid JSON untouched", async () => {
@@ -559,6 +562,21 @@ describe("getRenderedContent editable code", () => {
expect(renderCodeNotePreview.mock.lastCall?.[1]).toBe("text/x-sh");
});
+ it("wraps and numbers the lines of code as its embed sets, for CodeEmbed too", async () => {
+ const att = buildAttachment({ role: "file", mime: "text/plain", title: "a.py" });
+ att.getBlob = (async () => ({ content: "echo 1" })) as any;
+ const lines = { isCodeWrapped: false, hasCodeLineNumbers: false };
+
+ await getRenderedContent(att, lines);
+ expect(renderCodeNotePreview.mock.lastCall?.[3])
+ .toEqual({ isWrapped: false, hasLineNumbers: false });
+
+ await getRenderedContent(att, {
+ ...lines, interactive: true, attachmentEditor: buildEditor()
+ });
+ expect(codeEmbedComponent.mock.lastCall?.[0]).toMatchObject(lines);
+ });
+
it("mounts TextEmbed for an interactive text note, with a preview to render again", async () => {
const note = buildNote({ title: "Doc", type: "text", content: "<p>Hi</p>" });
const noteEditor = buildEditor();
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.ts
index d9f0a5a1f9..6139194c9e 100644
--- a/apps/client/src/services/content_renderer.ts
+++ b/apps/client/src/services/content_renderer.ts
@@ -23,6 +23,7 @@ import { t } from "../services/i18n.js";
import { type MediaEnvironment, showsFileActions } from "../widgets/type_widgets/file/media_environment.js";
import type { LlmChatContent, StoredMessage } from "../widgets/type_widgets/llm_chat/llm_chat_types.js";
import type { BoxSize } from "../widgets/type_widgets/text/CKEditor.js";
+import type { CodePreviewLines } from "./code_note_preview.js";
import renderText, {
postProcessRichContent, renderChildrenList, renderTextContent
} from "./content_renderer_text.js";
@@ -77,6 +78,10 @@ export interface RenderOptions {
* in place of the language of its name.
*/
codeLanguage?: string;
+ /** Whether the embed of a code file wraps its lines, over the option. */
+ isCodeWrapped?: boolean;
+ /** Whether the embed of a code note or file numbers its lines. Defaults to true. */
+ hasCodeLineNumbers?: boolean;
/**
* Lets content that has a source and a rendering, such as Markdown, show either or both, as
* the box of an embed picks. Without it, the rendering shows alone.
@@ -489,9 +494,12 @@ async function renderCode(
const editor = options.interactive ? getContentEditor(entity, options) : undefined;
const content = editor?.getUnsavedContent() ?? (await entity.getBlob())?.content ?? "";
const mime = getCodeMime(entity);
- const { codeLanguage } = options;
+ const { codeLanguage, isCodeWrapped, hasCodeLineNumbers } = options;
const note = entity instanceof FNote ? entity : null;
- const preview = await renderCodePreview(content, codeLanguage ?? mime, note);
+ const preview = await renderCodePreview(content, codeLanguage ?? mime, note, {
+ isWrapped: isCodeWrapped,
+ hasLineNumbers: hasCodeLineNumbers
+ });
if (!editor) {
$renderedContent.append(preview);
@@ -502,10 +510,9 @@ async function renderCode(
const $container = $('<div class="code-embed">');
const container = $container.get(0);
if (container) {
- await mountInteractiveWidget(
- h(CodeEmbed, { entity, editor, content, mime, codeLanguage, preview }),
- container
- );
+ await mountInteractiveWidget(h(CodeEmbed, {
+ entity, editor, content, mime, codeLanguage, isCodeWrapped, hasCodeLineNumbers, preview
+ }), container);
}
$renderedContent.append($container);
}
@@ -513,9 +520,14 @@ async function renderCode(
/**
* The highlighted content of a code note or file, with JSON indented.
*
- * @param note the note whose `#wrapLines` label sets the line wrapping.
+ * @param note the note whose `#wrapLines` label sets the line wrapping, unless `lines` sets it.
*/
-export async function renderCodePreview(content: string, mime: string, note?: FNote | null) {
+export async function renderCodePreview(
+ content: string,
+ mime: string,
+ note?: FNote | null,
+ lines?: CodePreviewLines
+) {
if (mime === "application/json") {
try {
content = JSON.stringify(JSON.parse(content), null, 4);
@@ -525,7 +537,7 @@ export async function renderCodePreview(content: string, mime: string, note?: FN
}
const { renderCodeNotePreview } = await import("./code_note_preview.js");
- return renderCodeNotePreview(content, mime, note);
+ return renderCodeNotePreview(content, mime, note, lines);
}
/**
diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.ts
index 272070e7a1..9deeff0f13 100644
--- a/apps/client/src/services/content_renderer_text.spec.ts
+++ b/apps/client/src/services/content_renderer_text.spec.ts
@@ -592,11 +592,12 @@ describe("Attachment embeds", () => {
.toBe(`#root/${owner.noteId}?viewMode=attachments&attachmentId=embedPic`);
});
- it("renders an embedded code file in the language that its embed sets", async () => {
+ it("renders an embedded code file in the language and lines that its embed sets", async () => {
const owner = buildNote({
title: "Code owner",
content: `<figure class="include-note" data-attachment-id="embedCode"`
- + ` data-code-language="text/x-sh">&nbsp;</figure>`
+ + ` data-code-language="text/x-sh" data-code-wrap-lines="true"`
+ + ` data-code-line-numbers="false">&nbsp;</figure>`
});
const attachment = new FAttachment(froca, {
attachmentId: "embedCode",
@@ -615,7 +616,23 @@ describe("Attachment embeds", () => {
await renderText(owner, $(document.createElement("div")));
expect(getRenderedContent).toHaveBeenCalledWith(
expect.objectContaining({ attachmentId: "embedCode" }),
- { codeLanguage: "text/x-sh" }
+ { codeLanguage: "text/x-sh", isCodeWrapped: true, hasCodeLineNumbers: false }
+ );
+ getRenderedContent.mockRestore();
+ });
+
+ it("renders an embedded code note with the line numbers that its embed sets", async () => {
+ const code = buildNote({ title: "Script", type: "code", mime: "text/x-sh", content: "a" });
+ const owner = buildNote({
+ title: "Code note owner",
+ content: `<figure class="include-note" data-note-id="${code.noteId}"`
+ + ` data-code-line-numbers="false">&nbsp;</figure>`
+ });
+ const getRenderedContent = vi.spyOn(content_renderer, "getRenderedContent");
+
+ await renderText(owner, $(document.createElement("div")));
+ expect(getRenderedContent).toHaveBeenCalledWith(
+ code, expect.objectContaining({ hasCodeLineNumbers: false })
);
getRenderedContent.mockRestore();
});
diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.ts
index 2ade3b9cec..8b0253ddaa 100644
--- a/apps/client/src/services/content_renderer_text.ts
+++ b/apps/client/src/services/content_renderer_text.ts
@@ -10,6 +10,7 @@ import {
import FAttachment from "../entities/fattachment.js";
import FNote from "../entities/fnote.js";
+import { getContentEmbedFlag } from "../widgets/type_widgets/text/content_embed_tools.js";
import { highlightBlockReference } from "./block_reference.js";
import {
addContentDisposer, default as content_renderer, type RenderOptions
@@ -141,9 +142,9 @@ async function renderContentEmbeds(contentEl: HTMLElement, context: ContentEmbed
const { ownerId, attachmentId } = attachment;
replaceWithReferenceLink(embedEl, getAttachmentEmbedHref(ownerId, attachmentId));
} else {
- const { $renderedContent } = await content_renderer.getRenderedContent(attachment, {
- codeLanguage: embedEl.getAttribute("data-code-language") ?? undefined
- });
+ const { $renderedContent } = await content_renderer.getRenderedContent(
+ attachment, getEmbedCodeView(embedEl)
+ );
replaceEmbedContent(embedEl, $renderedContent.toArray());
}
continue;
@@ -160,12 +161,25 @@ async function renderContentEmbeds(contentEl: HTMLElement, context: ContentEmbed
continue;
}
- const { $renderedContent } = await content_renderer.getRenderedContent(note,
- getNestedEmbedOptions(context, embed.block));
+ const { $renderedContent } = await content_renderer.getRenderedContent(note, {
+ ...getNestedEmbedOptions(context, embed.block),
+ hasCodeLineNumbers: getEmbedCodeView(embedEl).hasCodeLineNumbers
+ });
replaceEmbedContent(embedEl, $renderedContent.toArray());
}
}
+/** How `embedEl` shows a code file or a code note, by its `data-code-*` attributes. */
+export function getEmbedCodeView(
+ embedEl: Element | null | undefined
+): Pick<RenderOptions, "codeLanguage" | "isCodeWrapped" | "hasCodeLineNumbers"> {
+ return {
+ codeLanguage: embedEl?.getAttribute("data-code-language") ?? undefined,
+ isCodeWrapped: getContentEmbedFlag(embedEl, "data-code-wrap-lines"),
+ hasCodeLineNumbers: getContentEmbedFlag(embedEl, "data-code-line-numbers")
+ };
+}
+
/** Puts `content` in an embed, followed by the embed's caption. */
function replaceEmbedContent(embedEl: Element, content: Node[]) {
const caption = getEmbedCaption(embedEl);
diff --git a/apps/client/src/test/content_embed.ts b/apps/client/src/test/content_embed.ts
new file mode 100644
index 0000000000..97aadaf050
--- /dev/null
+++ b/apps/client/src/test/content_embed.ts
@@ -0,0 +1,80 @@
+import { act } from "preact/test-utils";
+import { afterEach, vi } from "vitest";
+
+import type { MenuItem } from "../menus/context_menu";
+import { getContentEmbedTools } from "../widgets/type_widgets/text/content_embed_tools";
+
+/** The `data-code-*` attribute that each setting of `setContentEmbedCodeView` sets. */
+const CODE_VIEW_ATTRIBUTES = {
+ language: "data-code-language",
+ tabWidth: "data-code-tab-width",
+ indentWithTabs: "data-code-indent-with-tabs",
+ wrapLines: "data-code-wrap-lines",
+ lineNumbers: "data-code-line-numbers"
+};
+
+const editables: HTMLElement[] = [];
+
+/**
+ * The editable root of a text editor, in the page, and the editor, whose code view command sets
+ * the `data-code-*` attributes of the embed it selects, as the text editor renders them. Put the
+ * embed in `editable`; it leaves the page after each test.
+ */
+export function buildCodeViewTextEditor() {
+ let selected: Element | null = null;
+ const textEditor = {
+ selectEmbedAt: vi.fn((element: Element) => {
+ selected = element.closest(".include-note");
+ return true;
+ }),
+ plugins: { get: () => ({ selectEmbedAt: textEditor.selectEmbedAt }) },
+ execute: vi.fn((_name: string, codeView: Record<string, unknown>) => {
+ for (const [ setting, attribute ] of Object.entries(CODE_VIEW_ATTRIBUTES)) {
+ const value = codeView[setting];
+ if (value === null) {
+ selected?.removeAttribute(attribute);
+ } else if (value !== undefined) {
+ selected?.setAttribute(attribute, String(value));
+ }
+ }
+ })
+ };
+ const editable = document.createElement("div");
+ editable.className = "ck-editor__editable";
+ Object.assign(editable, { ckeditorInstance: textEditor });
+ document.body.append(editable);
+ editables.push(editable);
+ return { textEditor, editable };
+}
+
+/** The items that the content of `figure` adds to the menu of its embed. */
+export function getEmbedMenuItems(figure: HTMLElement) {
+ return getContentEmbedTools(figure)?.getMenuItems?.() ?? [];
+}
+
+/** The title, the checked state and the items of `item`, for comparing. */
+export function summarizeMenuItem<T>(item: MenuItem<T>): unknown {
+ if ("kind" in item) return item;
+ return {
+ title: item.title,
+ ...("checked" in item && { checked: item.checked }),
+ ...(item.items && { items: item.items.map(summarizeMenuItem) })
+ };
+}
+
+/** Runs the item `index` of the menu of the embed, or the item `subIndex` of its submenu. */
+export async function runEmbedMenuItem(figure: HTMLElement, index: number, subIndex?: number) {
+ const item = getEmbedMenuItems(figure)[index];
+ const target = item && !("kind" in item) && subIndex !== undefined
+ ? item.items?.[subIndex]
+ : item;
+ if (!target || "kind" in target) throw new Error(`No menu item at ${index}.`);
+ await act(async () => target.handler?.(target, new MouseEvent("click")));
+}
+
+afterEach(() => {
+ for (const editable of editables) {
+ editable.remove();
+ }
+ editables.length = 0;
+});
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 593c9ca068..0daee8d4bb 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3084,7 +3084,11 @@
"include_size": "Size",
"show_title": "Show title",
"show_caption": "Show caption",
- "editable": "Editable"
+ "editable": "Editable",
+ "line_numbers": "Line numbers",
+ "line_numbers_auto": "Auto",
+ "line_numbers_on": "On",
+ "line_numbers_off": "Off"
},
"electron_integration": {
"desktop-application": "Desktop Application",
diff --git a/apps/client/src/widgets/layout/NoteActions.tsx b/apps/client/src/widgets/layout/NoteActions.tsx
index 2e17a487c5..414ac6c7f6 100644
--- a/apps/client/src/widgets/layout/NoteActions.tsx
+++ b/apps/client/src/widgets/layout/NoteActions.tsx
@@ -24,7 +24,9 @@ import { isAlwaysFullWidthByType } from "../note_wrapper";
import Dropdown, { type DropdownHandle } from "../react/Dropdown";
import { FormDropdownDivider, FormDropdownSubmenu, FormListHeader, FormListItem, FormListToggleableItem } from "../react/FormList";
import { useEffectiveReadOnly, useIsNoteReadOnly, useNoteContext, useNoteLabel, useNoteLabelBoolean, useNoteLabelOptionalBool, useNoteProperty, useNoteRelation, useSyncedRef, useTriliumEvent, useTriliumOption } from "../react/hooks";
+import { MenuItemRows } from "../react/Menu";
import { ParentComponent, POPUP_EDITOR_NTX_ID, useCommandTrigger } from "../react/react_utils";
+import { getWordWrapMenu } from "./code_menus";
import NoteActionsCustom from "./NoteActionsCustom";
import { useShareState } from "./NoteBadges";
import { NoteTypeDropdownContent } from "./NoteTypeSwitcher";
@@ -224,17 +226,7 @@ function CodeProperties({ note }: { note: FNote }) {
return (
<>
- <FormDropdownSubmenu title={t("note_actions.word_wrap")} icon="bx bx-align-justify">
- <FormListItem checked={wrapLines == null} onClick={() => setWrapLines(null)} description={t("note_actions.word_wrap_auto_description")}>
- {t("note_actions.word_wrap_auto")}
- </FormListItem>
- <FormListItem checked={wrapLines === true} onClick={() => setWrapLines(true)}>
- {t("note_actions.word_wrap_on")}
- </FormListItem>
- <FormListItem checked={wrapLines === false} onClick={() => setWrapLines(false)}>
- {t("note_actions.word_wrap_off")}
- </FormListItem>
- </FormDropdownSubmenu>
+ <MenuItemRows items={[ getWordWrapMenu(wrapLines, setWrapLines) ]} />
<FormDropdownDivider />
</>
);
diff --git a/apps/client/src/widgets/layout/code_menus.spec.tsx b/apps/client/src/widgets/layout/code_menus.spec.tsx
index aca19842c3..e15dac2ced 100644
--- a/apps/client/src/widgets/layout/code_menus.spec.tsx
+++ b/apps/client/src/widgets/layout/code_menus.spec.tsx
@@ -9,8 +9,8 @@ import options from "../../services/options";
import server from "../../services/server";
import { buildNote } from "../../test/easy-froca";
import {
- type CodeMenu, type CodeSettings, type CodeText, useCodeLanguageMenu, useNoteCodeSettings,
- useTabWidthMenu
+ type CodeMenu, type CodeSettings, type CodeText, getLineNumbersMenu, getWordWrapMenu,
+ useCodeLanguageMenu, useNoteCodeSettings, useTabWidthMenu
} from "./code_menus";
vi.mock("../../services/i18n", () => ({
@@ -175,6 +175,37 @@ describe("useCodeLanguageMenu", () => {
});
});
+describe("getWordWrapMenu and getLineNumbersMenu", () => {
+ it("check the current setting, and set it or follow the default again", async () => {
+ const setValue = vi.fn();
+ const wordWrap = getWordWrapMenu(undefined, setValue);
+ expect([ wordWrap.title, wordWrap.uiIcon ])
+ .toEqual([ "note_actions.word_wrap", "bx bx-align-justify" ]);
+ expect(describeItems(wordWrap.items ?? [])).toEqual([
+ "note_actions.word_wrap_auto ✓",
+ "note_actions.word_wrap_on ☐",
+ "note_actions.word_wrap_off ☐"
+ ]);
+ expect(wordWrap.items?.[0])
+ .toMatchObject({ description: "note_actions.word_wrap_auto_description" });
+
+ const lineNumbers = getLineNumbersMenu(false, setValue);
+ expect([ lineNumbers.title, lineNumbers.uiIcon ])
+ .toEqual([ "link_context_menu.line_numbers", "bx bx-list-ol" ]);
+ expect(describeItems(lineNumbers.items ?? [])).toEqual([
+ "link_context_menu.line_numbers_auto ☐",
+ "link_context_menu.line_numbers_on ☐",
+ "link_context_menu.line_numbers_off ✓"
+ ]);
+
+ for (const title of [ "link_context_menu.line_numbers_auto",
+ "link_context_menu.line_numbers_on", "link_context_menu.line_numbers_off" ]) {
+ await select(lineNumbers.items ?? [], title);
+ }
+ expect(setValue.mock.calls).toEqual([ [ null ], [ true ], [ false ] ]);
+ });
+});
+
function buildCodeNote(labels: Record<`#${string}`, string> = {}) {
return buildNote({ title: "Script", type: "code", mime: "text/x-python", ...labels });
}
diff --git a/apps/client/src/widgets/layout/code_menus.tsx b/apps/client/src/widgets/layout/code_menus.tsx
index 1be3d38918..88c2352888 100644
--- a/apps/client/src/widgets/layout/code_menus.tsx
+++ b/apps/client/src/widgets/layout/code_menus.tsx
@@ -4,7 +4,7 @@ import { createPortal } from "preact";
import { useMemo, useState } from "preact/hooks";
import type FNote from "../../entities/fnote";
-import type { MenuItem } from "../../menus/context_menu";
+import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";
import { t } from "../../services/i18n";
import server from "../../services/server";
import {
@@ -64,6 +64,49 @@ export function useNoteCodeSettings(note: FNote | null | undefined): CodeSetting
};
}
+/**
+ * The "Word wrap" submenu of a code editor: follow the global option, on, or off.
+ *
+ * @param wrapLines whether to wrap the lines, or `undefined` to follow the global option.
+ * @param setWrapLines sets the line wrapping, or follows the global option again for `null`.
+ */
+export function getWordWrapMenu<T>(
+ wrapLines: boolean | undefined,
+ setWrapLines: (wrapLines: boolean | null) => void
+): MenuCommandItem<T> {
+ return {
+ title: t("note_actions.word_wrap"),
+ uiIcon: "bx bx-align-justify",
+ items: getAutoOnOffItems(wrapLines, setWrapLines, {
+ auto: t("note_actions.word_wrap_auto"),
+ autoDescription: t("note_actions.word_wrap_auto_description"),
+ on: t("note_actions.word_wrap_on"),
+ off: t("note_actions.word_wrap_off")
+ })
+ };
+}
+
+/**
+ * The "Line numbers" submenu of a code embed: shown as in a code note, on, or off.
+ *
+ * @param lineNumbers whether the embed shows line numbers, or `undefined` for the default.
+ * @param setLineNumbers sets them, or the default again for `null`.
+ */
+export function getLineNumbersMenu<T>(
+ lineNumbers: boolean | undefined,
+ setLineNumbers: (lineNumbers: boolean | null) => void
+): MenuCommandItem<T> {
+ return {
+ title: t("link_context_menu.line_numbers"),
+ uiIcon: "bx bx-list-ol",
+ items: getAutoOnOffItems(lineNumbers, setLineNumbers, {
+ auto: t("link_context_menu.line_numbers_auto"),
+ on: t("link_context_menu.line_numbers_on"),
+ off: t("link_context_menu.line_numbers_off")
+ })
+ };
+}
+
/**
* The "Change language mode" menu of `settings`, and the dialog that its "Configure code notes"
* item opens, which the caller renders.
@@ -189,3 +232,28 @@ export function useTabWidthMenu(
items
};
}
+
+interface AutoOnOffTitles {
+ auto: string;
+ autoDescription?: string;
+ on: string;
+ off: string;
+}
+
+/** The Auto, On and Off items of a setting that is `undefined` while it follows its default. */
+function getAutoOnOffItems<T>(
+ value: boolean | undefined,
+ setValue: (value: boolean | null) => void,
+ titles: AutoOnOffTitles
+): MenuCommandItem<T>[] {
+ return [
+ {
+ title: titles.auto,
+ description: titles.autoDescription,
+ checked: value === undefined,
+ handler: () => setValue(null)
+ },
+ { title: titles.on, checked: value === true, handler: () => setValue(true) },
+ { title: titles.off, checked: value === false, handler: () => setValue(false) }
+ ];
+}
diff --git a/apps/client/src/widgets/react/Menu.spec.tsx b/apps/client/src/widgets/react/Menu.spec.tsx
index 3ba093d4c9..41f3e72014 100644
--- a/apps/client/src/widgets/react/Menu.spec.tsx
+++ b/apps/client/src/widgets/react/Menu.spec.tsx
@@ -132,6 +132,15 @@ describe("Menu with declared rows", () => {
expect(toggle?.querySelector(".description")?.previousElementSibling?.textContent).toBe("Search");
});
+ it("draws the description of an item under its title", () => {
+ render(<Menu anchor={{ x: 10, y: 10 }} onClose={vi.fn()} items={[
+ { title: "Auto", description: "Follow the global setting", checked: true }
+ ]} />, host);
+ const description = document.querySelector(".dropdown-item .description");
+ expect(description?.textContent).toBe("Follow the global setting");
+ expect(description?.previousElementSibling?.textContent).toBe("Auto");
+ });
+
it("closes the menu after running a row, but not for a row that opens a submenu or is disabled", async () => {
const { menu, calls } = renderMenu();
diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsx
index f27f5b79df..0ccb2d57fc 100644
--- a/apps/client/src/widgets/react/Menu.tsx
+++ b/apps/client/src/widgets/react/Menu.tsx
@@ -520,7 +520,7 @@ function MenuItemRow<T>({ row, onSelect }: { row: MenuItem<T>, onSelect: MenuPro
return <FormListCustomItem><row.componentFn /></FormListCustomItem>;
}
- const { title, uiIcon, iconColorClass, checked, enabled, badges, className, keyboardShortcut, shortcut, trailingIcon, items } = row;
+ const { title, description, uiIcon, iconColorClass, checked, enabled, badges, className, keyboardShortcut, shortcut, trailingIcon, items } = row;
// Callers pass HTML: titles escaped with `escapeHtml()` or boxed by `menuName()`.
const label = <span dangerouslySetInnerHTML={{ __html: title }} />;
// `onSelect` decides whether the menu closes, as `contextMenu` does.
@@ -543,7 +543,7 @@ function MenuItemRow<T>({ row, onSelect }: { row: MenuItem<T>, onSelect: MenuPro
// An item with neither keeps no slot for an icon, as an all-text menu such as spelling fixes needs.
icon={"uiIcon" in row || "checked" in row ? uiIcon : null}
iconClassName={iconColorClass} checked={checked} checkable={"checked" in row} disabled={enabled === false}
- className={className} badges={badges?.map((badge) => ({ className: badge.className, text: badge.title }))}
+ description={description} className={className} badges={badges?.map((badge) => ({ className: badge.className, text: badge.title }))}
keyboardShortcut={keyboardShortcut} shortcut={shortcut} trailingIcon={trailingIcon} closeOnSelect={false}
onClick={select}
>
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 4e65a677eb..61e269d272 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx
@@ -8,10 +8,14 @@ import FAttachment from "../../../entities/fattachment";
import FBlob from "../../../entities/fblob";
import type FNote from "../../../entities/fnote";
import contextMenu from "../../../menus/context_menu";
+import attributes from "../../../services/attributes";
import type { ContentEditor } from "../../../services/content_renderer";
import froca from "../../../services/froca";
import LoadResults from "../../../services/load_results";
import options from "../../../services/options";
+import {
+ buildCodeViewTextEditor, getEmbedMenuItems, runEmbedMenuItem, summarizeMenuItem
+} from "../../../test/content_embed";
import { buildNote } from "../../../test/easy-froca";
import { ParentComponent } from "../../react/react_utils";
import { CodeMirrorFindTarget } from "../../find_in_code";
@@ -19,8 +23,11 @@ import { NoteSaves } from "../text/attachment_saves";
import { getContentEmbedTools, getEmbedFindTarget } from "../text/content_embed_tools";
import CodeEmbed from "./CodeEmbed";
+/** How a preview shows the lines of an embed that sets neither. */
+const DEFAULT_LINES = { isWrapped: undefined, hasLineNumbers: true };
+
const renderCodePreview = vi.hoisted(() => vi.fn(
- async (content: string, _mime: string, _note?: unknown) => {
+ async (content: string, _mime: string, _note?: unknown, _lines?: unknown) => {
const pre = document.createElement("pre");
pre.textContent = content;
return pre;
@@ -218,7 +225,7 @@ describe("CodeEmbed", () => {
options.set("codeNotesMimeTypes", JSON.stringify([ "text/x-python", "text/x-sh" ]));
vi.spyOn(contextMenu, "show").mockResolvedValue(undefined);
const editor = buildEditor();
- const { textEditor, editable } = buildTextEditor();
+ const { textEditor, editable } = buildCodeViewTextEditor();
const { figure } = await mount(buildAttachment("script.py"), editor, {
content: "if a:\n b",
mime: "text/x-python",
@@ -240,12 +247,14 @@ describe("CodeEmbed", () => {
expect(textEditor.execute)
.toHaveBeenLastCalledWith("setContentEmbedCodeView", { language: null });
await vi.waitFor(() => {
- expect(renderCodePreview).toHaveBeenLastCalledWith("if a:\n b", "text/x-python", null);
+ expect(renderCodePreview)
+ .toHaveBeenLastCalledWith("if a:\n b", "text/x-python", null, DEFAULT_LINES);
});
await select("codeLanguage", "Plain text");
expect(figure.getAttribute("data-code-language")).toBe("text/plain");
await vi.waitFor(() => {
- expect(renderCodePreview).toHaveBeenLastCalledWith("if a:\n b", "text/plain", null);
+ expect(renderCodePreview)
+ .toHaveBeenLastCalledWith("if a:\n b", "text/plain", null, DEFAULT_LINES);
});
// The indentation, which a re-indent sets with the content, as one change.
@@ -278,6 +287,109 @@ describe("CodeEmbed", () => {
expect(textEditor.execute).not.toHaveBeenCalled();
});
+ it("offers the line wrapping and line numbers of a note in the menu of its embed", async () => {
+ const setLabel = vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);
+ const removeLabel = vi.spyOn(attributes, "removeOwnedLabelByName")
+ .mockResolvedValue(undefined as never);
+ const { textEditor, editable } = buildCodeViewTextEditor();
+ const note = buildNote({
+ title: "Script", type: "code", mime: "text/x-python", content: "a",
+ "#wrapLines": "false"
+ });
+ const { figure } = await mount(note, buildEditor(), {
+ hasCodeLineNumbers: false,
+ embedAttributes: { "data-code-line-numbers": "false" },
+ container: editable
+ });
+ expect(getEmbedMenuItems(figure).map(summarizeMenuItem)).toEqual([
+ {
+ title: "note_actions.word_wrap",
+ items: [
+ { title: "note_actions.word_wrap_auto", checked: false },
+ { title: "note_actions.word_wrap_on", checked: false },
+ { title: "note_actions.word_wrap_off", checked: true }
+ ]
+ },
+ {
+ title: "link_context_menu.line_numbers",
+ items: [
+ { title: "link_context_menu.line_numbers_auto", checked: false },
+ { title: "link_context_menu.line_numbers_on", checked: false },
+ { title: "link_context_menu.line_numbers_off", checked: true }
+ ]
+ }
+ ]);
+ expect(renderCodePreview).not.toHaveBeenCalled();
+
+ // The line wrapping is the `#wrapLines` label of the note.
+ await runEmbedMenuItem(figure, 0, 0);
+ expect(removeLabel).toHaveBeenCalledWith(note, "wrapLines");
+ await runEmbedMenuItem(figure, 0, 1);
+ expect(setLabel).toHaveBeenCalledWith(note.noteId, "wrapLines", "true");
+ expect(textEditor.execute).not.toHaveBeenCalled();
+
+ // The line numbers are kept in the embed, as the note has no label for them.
+ await runEmbedMenuItem(figure, 1, 0);
+ expect(textEditor.execute)
+ .toHaveBeenLastCalledWith("setContentEmbedCodeView", { lineNumbers: null });
+ await vi.waitFor(() => {
+ expect(summarizeMenuItem(getEmbedMenuItems(figure)[1])).toMatchObject({
+ items: [ { checked: true }, { checked: false }, { checked: false } ]
+ });
+ });
+ await vi.waitFor(() => expect(renderCodePreview).toHaveBeenLastCalledWith(
+ "a", "text/x-python", note, { isWrapped: false, hasLineNumbers: true }
+ ));
+ await runEmbedMenuItem(figure, 1, 1);
+ expect(figure.getAttribute("data-code-line-numbers")).toBe("true");
+ });
+
+ it("keeps the line wrapping and the line numbers of a file in its embed", async () => {
+ const { textEditor, editable } = buildCodeViewTextEditor();
+ const { figure } = await mount(buildAttachment("script.py"), buildEditor(), {
+ content: "a",
+ mime: "text/x-python",
+ isCodeWrapped: true,
+ embedAttributes: { "data-code-wrap-lines": "true" },
+ container: editable
+ });
+ expect(getEmbedMenuItems(figure).map(summarizeMenuItem)).toMatchObject([
+ {
+ items: [
+ { checked: false },
+ { checked: true },
+ { checked: false }
+ ]
+ },
+ { items: [ { checked: true }, { checked: false }, { checked: false } ] }
+ ]);
+ expect(renderCodePreview).not.toHaveBeenCalled();
+
+ await runEmbedMenuItem(figure, 0, 2);
+ expect(textEditor.execute)
+ .toHaveBeenLastCalledWith("setContentEmbedCodeView", { wrapLines: false });
+ await runEmbedMenuItem(figure, 1, 2);
+ expect(textEditor.execute)
+ .toHaveBeenLastCalledWith("setContentEmbedCodeView", { lineNumbers: false });
+ expect([ "data-code-wrap-lines", "data-code-line-numbers" ]
+ .map((name) => figure.getAttribute(name))).toEqual([ "false", "false" ]);
+ await vi.waitFor(() => expect(renderCodePreview).toHaveBeenLastCalledWith(
+ "a", "text/x-python", null, { isWrapped: false, hasLineNumbers: false }
+ ));
+
+ // CodeMirror follows the embed.
+ await runEmbedMenuItem(figure, 0, 1);
+ await act(async () => {
+ figure.dataset.editable = "true";
+ await Promise.resolve();
+ });
+ const view = await findView(figure);
+ expect(view.contentDOM.classList.contains("cm-lineWrapping")).toBe(true);
+ expect(figure.querySelector(".cm-lineNumbers")).toBeNull();
+ await runEmbedMenuItem(figure, 1, 1);
+ await vi.waitFor(() => expect(figure.querySelector(".cm-lineNumbers")).not.toBeNull());
+ });
+
it("highlights an attachment with the MIME type it is given", async () => {
const attachment = new FAttachment(froca, {
attachmentId: "script1",
@@ -303,7 +415,8 @@ describe("CodeEmbed", () => {
await Promise.resolve();
});
await vi.waitFor(() => {
- expect(renderCodePreview).toHaveBeenLastCalledWith("ab", "text/x-python", null);
+ expect(renderCodePreview)
+ .toHaveBeenLastCalledWith("ab", "text/x-python", null, DEFAULT_LINES);
});
});
@@ -465,6 +578,8 @@ interface MountOptions {
content?: string;
mime?: string;
codeLanguage?: string;
+ isCodeWrapped?: boolean;
+ hasCodeLineNumbers?: boolean;
preview?: HTMLElement;
isEditable?: boolean;
/** Attributes of the embed, such as `data-code-language`. */
@@ -511,6 +626,8 @@ async function mount(
content={options.content ?? (await entity.getBlob())?.content ?? content}
mime={options.mime ?? entity.mime}
codeLanguage={options.codeLanguage}
+ isCodeWrapped={options.isCodeWrapped}
+ hasCodeLineNumbers={options.hasCodeLineNumbers}
preview={options.preview ?? buildPreview(content)}
/>
</ParentComponent.Provider>,
@@ -558,42 +675,6 @@ async function selectMenuItem(figure: HTMLElement, id: string, title: string, is
await act(async () => item.handler?.(item, new MouseEvent("click")));
}
-/**
- * The editable root of a text editor, in the page, and the editor, whose code view command sets
- * the `data-code-*` attributes of the embed it selects, as the text editor renders them.
- */
-function buildTextEditor() {
- let selected: Element | null = null;
- const textEditor = {
- selectEmbedAt: vi.fn((element: Element) => {
- selected = element.closest(".include-note");
- return true;
- }),
- plugins: { get: () => ({ selectEmbedAt: textEditor.selectEmbedAt }) },
- execute: vi.fn((_name: string, codeView: Record<string, unknown>) => {
- const attributes = {
- language: "data-code-language",
- tabWidth: "data-code-tab-width",
- indentWithTabs: "data-code-indent-with-tabs"
- };
- for (const [ setting, attribute ] of Object.entries(attributes)) {
- const value = codeView[setting];
- if (value === null) {
- selected?.removeAttribute(attribute);
- } else if (value !== undefined) {
- selected?.setAttribute(attribute, String(value));
- }
- }
- })
- };
- const editable = document.createElement("div");
- editable.className = "ck-editor__editable";
- Object.assign(editable, { ckeditorInstance: textEditor });
- document.body.append(editable);
- figures.push(editable);
- return { textEditor, editable };
-}
-
function buildPreview(content: string) {
const pre = document.createElement("pre");
pre.textContent = content;
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
index 01850ceb06..5000917f4b 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx
@@ -4,18 +4,22 @@ import { createPortal, type RefObject } from "preact";
import { lazy, useSyncExternalStore } from "preact/compat";
import { useEffect, useRef, useState } from "preact/hooks";
+import type { CommandNames } from "../../../components/app_context";
import type FAttachment from "../../../entities/fattachment";
import FNote from "../../../entities/fnote";
+import type { MenuItem } from "../../../menus/context_menu";
+import type { CodePreviewLines } from "../../../services/code_note_preview";
import { type ContentEditor, renderCodePreview } from "../../../services/content_renderer";
import {
- type CodeSettings, type CodeText, useCodeLanguageMenu, useNoteCodeSettings, useTabWidthMenu
+ type CodeSettings, type CodeText, getLineNumbersMenu, getWordWrapMenu, useCodeLanguageMenu,
+ useNoteCodeSettings, useTabWidthMenu
} from "../../layout/code_menus";
import { SaveStateBadge } from "../../layout/NoteBadges";
import {
useNoteBlob, useNoteLabelOptionalBool, useTriliumEvent, useTriliumOption
} from "../../react/hooks";
import { useContentEmbedMenus } from "../text/content_embed_menus";
-import { useContentEmbedAttribute } from "../text/content_embed_tools";
+import { useContentEmbedAttribute, useContentEmbedFlag } from "../text/content_embed_tools";
import {
EditableEmbedContent, findTextEditorAround, useEditableEmbed, useEmbedBadgeSlot,
useEmbedPreview
@@ -36,6 +40,10 @@ interface CodeEmbedProps {
mime: string;
/** The language that the embed of a file sets, as a MIME type, in place of `mime`. */
codeLanguage?: string;
+ /** The line wrapping that the embed of a file sets, in place of the option. */
+ isCodeWrapped?: boolean;
+ /** Whether the embed shows line numbers. Shown by default. */
+ hasCodeLineNumbers?: boolean;
/** The highlighted `content`. */
preview: HTMLElement;
}
@@ -45,7 +53,8 @@ interface CodeEmbedProps {
* Editable toggle of its embed is on.
*/
export default function CodeEmbed({
- entity, editor, content: initialContent, mime: initialMime, codeLanguage, preview
+ entity, editor, content: initialContent, mime: initialMime, codeLanguage, isCodeWrapped,
+ hasCodeLineNumbers, preview
}: CodeEmbedProps) {
const rootRef = useRef<HTMLDivElement>(null);
const viewRef = useRef<VanillaCodeMirror>(null);
@@ -57,14 +66,18 @@ export default function CodeEmbed({
const noteSettings = useNoteCodeSettings(note);
const fileSettings = useFileCodeSettings(rootRef, initialMime, codeLanguage);
const settings = note ? noteSettings : fileSettings;
+ const lines = useEmbedLines(rootRef, note, {
+ isWrapped: isCodeWrapped, hasLineNumbers: hasCodeLineNumbers
+ });
const [ content, setContent ] = useState(initialContent);
const mime = settings.mime ?? initialMime;
useSavedContent(entity, editor, setContent);
- const appearance = useCodePreviewAppearance(note);
+ const appearance = useCodePreviewAppearance();
+ const { wrapLines, hasLineNumbers } = lines;
const shownPreview = useEmbedPreview(
preview,
- `${mime}\n${appearance}\n${content}`,
- () => renderCodePreview(content, mime, note),
+ `${mime}\n${appearance}\n${wrapLines}\n${hasLineNumbers}\n${content}`,
+ () => renderCodePreview(content, mime, note, { isWrapped: wrapLines, hasLineNumbers }),
isEditing
);
// The editor while it is open, otherwise the content with the unsaved changes of any embed of
@@ -93,31 +106,80 @@ export default function CodeEmbed({
mime={mime}
tabWidth={settings.tabWidth}
useTabs={settings.useTabs}
+ wrapLines={wrapLines}
+ hasLineNumbers={hasLineNumbers}
viewRef={viewRef}
onClose={setContent}
/>
</EditableEmbedContent>
<SaveStatus rootRef={rootRef} editor={editor} isShown={isEditing} />
{canEdit && (
- <CodeTools rootRef={rootRef} settings={settings} getCodeText={getCodeText} />
+ <CodeTools
+ rootRef={rootRef}
+ settings={settings}
+ menuItems={lines.menuItems}
+ getCodeText={getCodeText}
+ />
)}
</>
);
}
+/** How a code editor in an embed, and its preview, show their lines. */
+export interface EmbedLines {
+ /** Whether to wrap the lines, or `undefined` to follow the global option. */
+ wrapLines: boolean | undefined;
+ hasLineNumbers: boolean;
+ /** The "Word wrap" and "Line numbers" submenus, for the menu of the embed. */
+ menuItems: MenuItem<CommandNames>[];
+}
+
/**
- * The options and the `#wrapLines` label of `note` that `renderCodePreview()` draws with, as a key
- * that changes with any of them.
+ * How the code editor in the embed around `rootRef` shows its lines. The line wrapping of `note`
+ * is its `#wrapLines` label. The embed keeps the line numbers, and the line wrapping of content
+ * other than a note, in `data-code-*` attributes. `initial` applies until the content is in the
+ * embed.
*/
-function useCodePreviewAppearance(note: FNote | null) {
+export function useEmbedLines(
+ rootRef: RefObject<HTMLElement | null>,
+ note: FNote | null,
+ initial: CodePreviewLines = {}
+): EmbedLines {
+ const [ noteWrapLines, setNoteWrapLines ] = useNoteLabelOptionalBool(note, "wrapLines");
+ const embedWrapLines = useContentEmbedFlag(rootRef, "data-code-wrap-lines", initial.isWrapped);
+ const lineNumbers = useContentEmbedFlag(
+ rootRef, "data-code-line-numbers", initial.hasLineNumbers
+ );
+ const wrapLines = note ? noteWrapLines : embedWrapLines;
+ const setWrapLines = (value: boolean | null) => {
+ if (note) {
+ setNoteWrapLines(value);
+ } else {
+ setCodeView(rootRef.current, { wrapLines: value });
+ }
+ };
+
+ return {
+ wrapLines,
+ hasLineNumbers: lineNumbers ?? true,
+ menuItems: [
+ getWordWrapMenu(wrapLines, setWrapLines),
+ getLineNumbersMenu(lineNumbers, (value) => {
+ setCodeView(rootRef.current, { lineNumbers: value });
+ })
+ ]
+ };
+}
+
+/** The options that `renderCodePreview()` draws with, as a key that changes with any of them. */
+function useCodePreviewAppearance() {
const [ theme ] = useTriliumOption("codeNoteTheme");
const [ matchesApp ] = useTriliumOption("codeNoteThemeMatchesApp");
const [ lightTheme ] = useTriliumOption("codeNoteThemeLight");
const [ darkTheme ] = useTriliumOption("codeNoteThemeDark");
const [ isWrapped ] = useTriliumOption("codeLineWrapEnabled");
- const [ isNoteWrapped ] = useNoteLabelOptionalBool(note, "wrapLines");
- return [ theme, matchesApp, lightTheme, darkTheme, isWrapped, isNoteWrapped ].join("\n");
+ return [ theme, matchesApp, lightTheme, darkTheme, isWrapped ].join("\n");
}
/**
@@ -159,21 +221,23 @@ function setCodeView(root: HTMLElement | null, codeView: ContentEmbedCodeView) {
interface CodeToolsProps {
rootRef: RefObject<HTMLElement | null>;
settings: CodeSettings;
+ /** The items of the menu of the embed. */
+ menuItems: MenuItem<CommandNames>[];
/** The text that the re-indent items of the tab width menu convert. */
getCodeText: () => CodeText;
}
/**
* The "Change language mode" and "Change tab width" menus of the status bar, as buttons of the
- * toolbar of the embed around `rootRef`.
+ * toolbar of the embed around `rootRef`, and `menuItems` in its menu.
*/
-function CodeTools({ rootRef, settings, getCodeText }: CodeToolsProps) {
+function CodeTools({ rootRef, settings, menuItems, getCodeText }: CodeToolsProps) {
const language = useCodeLanguageMenu(settings);
const tabWidth = useTabWidthMenu(settings, async () => getCodeText());
useContentEmbedMenus(rootRef, [
{ id: "codeLanguage", ...language.menu },
{ id: "tabWidth", ...tabWidth }
- ]);
+ ], menuItems);
return language.modal;
}
diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
index 2d106f31a3..4e5b0f32a4 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx
@@ -20,6 +20,10 @@ export interface CodeEmbedEditorProps {
tabWidth: number | undefined;
/** Whether to indent with tabs, or `undefined` to follow the global option. */
useTabs: boolean | undefined;
+ /** Whether to wrap the lines, over the `#wrapLines` label of `note` and the global option. */
+ wrapLines?: boolean;
+ /** Whether to show the line numbers. Shown by default. */
+ hasLineNumbers?: boolean;
/** Holds the CodeMirror view while the editor is open, and `null` once it goes away. */
viewRef: RefObject<VanillaCodeMirror | null>;
/** Whether the editor shows. "Search in note" skips a hidden one. Shown by default. */
@@ -37,12 +41,13 @@ export interface CodeEmbedEditorProps {
* `editor`, the content is read-only.
*/
export default function CodeEmbedEditor({
- note, editor, content, mime, tabWidth, useTabs, viewRef, isShown = true, onClose, onChange,
- onReady
+ note, editor, content, mime, tabWidth, useTabs, wrapLines, hasLineNumbers, viewRef,
+ isShown = true, onClose, onChange, onReady
}: CodeEmbedEditorProps) {
const isLoadingRef = useRef(false);
const [ vimKeymapEnabled ] = useTriliumOptionBool("vimKeymapEnabled");
const [ noteWrapLines ] = useNoteLabelOptionalBool(note, "wrapLines");
+ const lineWrapping = wrapLines ?? noteWrapLines;
useEmbedCaretNavigation(() => viewRef.current);
// Runs after the effects of `CodeMirror`, which creates the view.
@@ -98,6 +103,7 @@ export default function CodeEmbedEditor({
mime={mime}
vimKeybindings={vimKeymapEnabled}
readOnly={!editor}
+ lineNumbers={hasLineNumbers}
onContentChanged={() => {
if (editor && !isLoadingRef.current) {
editor.scheduleSave(() => viewRef.current?.getText() ?? "");
@@ -106,7 +112,7 @@ export default function CodeEmbedEditor({
}}
{...(tabWidth !== undefined && { indentSize: tabWidth })}
{...(useTabs !== undefined && { useTabs })}
- {...(noteWrapLines != null && { lineWrapping: noteWrapLines })}
+ {...(lineWrapping != null && { lineWrapping })}
/>
);
}
diff --git a/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx b/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx
index 740b41237f..5e9b8d5758 100644
--- a/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx
+++ b/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx
@@ -19,7 +19,7 @@ export interface CodeMirrorProps extends Omit<EditorConfig, "parent"> {
bulkActionNote?: boolean;
}
-export default function CodeMirror({ className, content, mime, editorRef: externalEditorRef, containerRef: externalContainerRef, onInitialized, lineWrapping, customRequestHandler, bulkActionNote, allowKeyboardSuggestions, ...extraOpts }: CodeMirrorProps) {
+export default function CodeMirror({ className, content, mime, editorRef: externalEditorRef, containerRef: externalContainerRef, onInitialized, lineWrapping, lineNumbers = true, customRequestHandler, bulkActionNote, allowKeyboardSuggestions, ...extraOpts }: CodeMirrorProps) {
const parentRef = useSyncedRef(externalContainerRef);
const codeEditorRef = useRef<VanillaCodeMirror | undefined>(undefined);
@@ -30,6 +30,7 @@ export default function CodeMirror({ className, content, mime, editorRef: extern
const codeEditor = new VanillaCodeMirror({
parent: parentRef.current,
allowKeyboardSuggestions,
+ lineNumbers,
...extraOpts
});
codeEditorRef.current = codeEditor;
@@ -68,6 +69,9 @@ export default function CodeMirror({ className, content, mime, editorRef: extern
// React to line wrapping.
useEffect(() => codeEditorRef.current?.setLineWrapping(!!lineWrapping), [ lineWrapping ]);
+ // React to line numbers.
+ useEffect(() => codeEditorRef.current?.setLineNumbers(lineNumbers), [ lineNumbers ]);
+
// React to indent size / style changes.
useEffect(() => {
if (extraOpts.indentSize != null || extraOpts.useTabs != null) {
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 801213f774..01a5908e71 100644
--- a/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.spec.tsx
@@ -5,8 +5,12 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import Component from "../../../components/component";
import type FNote from "../../../entities/fnote";
+import attributes from "../../../services/attributes";
import type { ContentEditor } from "../../../services/content_renderer";
import options from "../../../services/options";
+import {
+ buildCodeViewTextEditor, getEmbedMenuItems, runEmbedMenuItem, summarizeMenuItem
+} from "../../../test/content_embed";
import { buildNote } from "../../../test/easy-froca";
import { CodeMirrorFindTarget } from "../../find_in_code";
import { ParentComponent } from "../../react/react_utils";
@@ -159,6 +163,38 @@ describe("MarkdownEmbed", () => {
pressCtrl(view, "z");
expect(view.state.doc.toString()).toBe("a");
});
+
+ it("wraps and numbers the lines of the source as the menu of its embed sets", async () => {
+ const setLabel = vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);
+ const { textEditor, editable } = buildCodeViewTextEditor();
+ const note = buildNote({
+ title: "Readme", type: "code", mime: "text/x-markdown", content: "a",
+ "#wrapLines": "true"
+ });
+ const { figure } = await mount(note, buildEditor(), {
+ embedAttributes: { "data-display-mode": "source", "data-code-line-numbers": "false" },
+ container: editable
+ });
+ const view = await findView(figure);
+ expect(view.contentDOM.classList.contains("cm-lineWrapping")).toBe(true);
+ expect(figure.querySelector(".cm-lineNumbers")).toBeNull();
+ expect(getEmbedMenuItems(figure).map(summarizeMenuItem)).toMatchObject([
+ { title: "note_actions.word_wrap", items: [ {}, { checked: true }, {} ] },
+ { title: "link_context_menu.line_numbers", items: [ {}, {}, { checked: true } ] }
+ ]);
+
+ // The line wrapping of a note is its `#wrapLines` label.
+ await runEmbedMenuItem(figure, 0, 2);
+ expect(setLabel).toHaveBeenCalledWith(note.noteId, "wrapLines", "false");
+ await runEmbedMenuItem(figure, 1, 1);
+ expect(textEditor.execute)
+ .toHaveBeenCalledWith("setContentEmbedCodeView", { lineNumbers: true });
+ await vi.waitFor(() => expect(figure.querySelector(".cm-lineNumbers")).not.toBeNull());
+
+ // Content that cannot be edited offers neither.
+ const { figure: locked } = await mount(note, buildEditor({ canEdit: () => false }));
+ expect(getEmbedMenuItems(locked)).toEqual([]);
+ });
});
/** Picks the display mode `mode` on the embed `figure`. */
@@ -175,6 +211,8 @@ interface MountOptions {
renderPreview?: (content: string) => Promise<HTMLElement>;
/** Attributes of the embed, such as `data-display-mode`. */
embedAttributes?: Record<string, string>;
+ /** The element the embed goes in, such as the editable root of a text editor. */
+ container?: HTMLElement;
}
/** Renders `MarkdownEmbed` in the markup of an embed, as the host does. */
@@ -202,7 +240,7 @@ async function mount(
box.className = "include-note-content";
wrapper.append(titleRow, box);
figure.append(wrapper);
- document.body.append(figure);
+ (options.container ?? document.body).append(figure);
figures.push(figure);
const content = (await entity.getBlob())?.content ?? "";
diff --git a/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.tsx b/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.tsx
index b8562347d9..816f77bcfa 100644
--- a/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.tsx
+++ b/apps/client/src/widgets/type_widgets/markdown/MarkdownEmbed.tsx
@@ -5,13 +5,15 @@ import clsx from "clsx";
import type { RefObject } from "preact";
import { useEffect, useRef, useState } from "preact/hooks";
+import type { CommandNames } from "../../../components/app_context";
import type FAttachment from "../../../entities/fattachment";
import FNote from "../../../entities/fnote";
+import type { MenuItem } from "../../../menus/context_menu";
import type { ContentEditor } from "../../../services/content_renderer";
import { isDesktop } from "../../../services/utils";
import { useNoteCodeSettings } from "../../layout/code_menus";
import { useDebouncedValue } from "../../react/hooks";
-import { SaveStatus, useSavedContent } from "../code/CodeEmbed";
+import { SaveStatus, useEmbedLines, useSavedContent } from "../code/CodeEmbed";
import { EmbedSourcePane } from "../code/CodeEmbedEditor";
import { resolveDisplayMode } from "../helpers/split_editor_mode";
import { SplitLayout, useMountedPanes } from "../helpers/SplitEditor";
@@ -49,7 +51,8 @@ export default function MarkdownEmbed({
const { canEdit, isEditing } = useEditableEmbed(rootRef, {
editor, note, tools: null, focusTarget: ".cm-content"
});
- useDisplayModeTools(rootRef, canEdit);
+ const lines = useEmbedLines(rootRef, note);
+ useDisplayModeTools(rootRef, canEdit, lines.menuItems);
const mode = resolveDisplayMode(useContentEmbedDisplayMode(rootRef), !isEditing);
const isSourceShown = mode !== "preview";
const { editorMounted, previewMounted } = useMountedPanes(mode);
@@ -90,6 +93,8 @@ export default function MarkdownEmbed({
mime={MARKDOWN_MIME}
tabWidth={tabWidth}
useTabs={useTabs}
+ wrapLines={lines.wrapLines}
+ hasLineNumbers={lines.hasLineNumbers}
viewRef={viewRef}
onContentChange={setContent}
onReady={setView}
@@ -110,10 +115,17 @@ export function renderMarkdownHtml(source: string) {
}
/**
- * Offers the display modes of the content in `rootRef` on its embed, and the Editable toggle while
- * `canEdit`.
+ * Offers the display modes of the content in `rootRef` on its embed, and the Editable toggle and
+ * `menuItems` while `canEdit`.
*/
-function useDisplayModeTools(rootRef: RefObject<HTMLElement | null>, canEdit: boolean) {
+function useDisplayModeTools(
+ rootRef: RefObject<HTMLElement | null>,
+ canEdit: boolean,
+ menuItems: MenuItem<CommandNames>[]
+) {
+ const menuItemsRef = useRef(menuItems);
+ menuItemsRef.current = menuItems;
+
useEffect(() => {
const root = rootRef.current;
if (!root) return;
@@ -123,7 +135,8 @@ function useDisplayModeTools(rootRef: RefObject<HTMLElement | null>, canEdit: bo
hasDisplayModes: true,
getTools: () => [],
execute: () => {},
- subscribe: () => () => {}
+ subscribe: () => () => {},
+ getMenuItems: () => (canEdit ? menuItemsRef.current : [])
});
}, [ rootRef, canEdit ]);
}
diff --git a/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsx b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsx
index 57d05c16bd..ca499ac727 100644
--- a/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsx
@@ -5,6 +5,9 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import type { ContentEditor } from "../../../services/content_renderer";
import { renderMermaidSvg } from "../../../services/mermaid";
import options from "../../../services/options";
+import {
+ buildCodeViewTextEditor, getEmbedMenuItems, runEmbedMenuItem, summarizeMenuItem
+} from "../../../test/content_embed";
import { getContentEmbedTools } from "../text/content_embed_tools";
import MermaidDiagram from "./MermaidDiagram";
@@ -192,6 +195,34 @@ describe("MermaidDiagram", () => {
});
await vi.waitFor(async () => expect(await isSourceEditable(figure)).toBe(true));
});
+
+ it("wraps and numbers the lines of the source as the menu of its embed sets", async () => {
+ const { textEditor, editable } = buildCodeViewTextEditor();
+ const { figure } = await mount({
+ editor: buildEditor(),
+ displayMode: "source",
+ embedAttributes: { "data-code-wrap-lines": "true", "data-code-line-numbers": "false" },
+ container: editable
+ });
+ const view = await findSourceView(figure);
+ expect(view.contentDOM.classList.contains("cm-lineWrapping")).toBe(true);
+ expect(figure.querySelector(".cm-lineNumbers")).toBeNull();
+ // Word wrap, then line numbers.
+ expect(getEmbedMenuItems(figure).map(summarizeMenuItem)).toMatchObject([
+ { items: [ { checked: false }, { checked: true }, { checked: false } ] },
+ { items: [ { checked: false }, { checked: false }, { checked: true } ] }
+ ]);
+
+ // A diagram has no note, so its embed keeps both.
+ await runEmbedMenuItem(figure, 0, 2);
+ await runEmbedMenuItem(figure, 1, 0);
+ expect(textEditor.execute.mock.calls.map(([ , codeView ]) => codeView))
+ .toEqual([ { wrapLines: false }, { lineNumbers: null } ]);
+ await vi.waitFor(() => {
+ expect(view.contentDOM.classList.contains("cm-lineWrapping")).toBe(false);
+ expect(figure.querySelector(".cm-lineNumbers")).not.toBeNull();
+ });
+ });
});
interface MountOptions {
@@ -200,19 +231,28 @@ interface MountOptions {
displayMode?: string;
boxSize?: string;
hideTitle?: boolean;
+ /** Other attributes of the embed, such as `data-code-wrap-lines`. */
+ embedAttributes?: Record<string, string>;
+ /** The element the embed goes in, such as the editable root of a text editor. */
+ container?: HTMLElement;
}
-async function mount({ editor, isEditable, displayMode, boxSize, hideTitle }: MountOptions) {
+async function mount({
+ editor, isEditable, displayMode, boxSize, hideTitle, embedAttributes, container
+}: MountOptions) {
const figure = document.createElement("figure");
figure.className = "include-note";
if (isEditable) figure.dataset.editable = "true";
if (displayMode) figure.dataset.displayMode = displayMode;
if (boxSize) figure.dataset.boxSize = boxSize;
if (hideTitle) figure.dataset.hideTitle = "true";
+ for (const [ name, value ] of Object.entries(embedAttributes ?? {})) {
+ figure.setAttribute(name, value);
+ }
const box = document.createElement("div");
box.className = "include-note-content";
figure.append(box);
- document.body.append(figure);
+ (container ?? document.body).append(figure);
figures.push(figure);
await act(async () => render(<MermaidDiagram content="graph TD;" editor={editor} />, box));
@@ -241,6 +281,11 @@ function getPanes(figure: HTMLElement) {
/** Whether the CodeMirror of the source pane takes edits, once it has loaded. */
async function isSourceEditable(figure: HTMLElement) {
+ return !(await findSourceView(figure)).state.readOnly;
+}
+
+/** The CodeMirror of the source pane, once it has loaded. */
+async function findSourceView(figure: HTMLElement) {
const { EditorView } = await import("@codemirror/view");
let view: InstanceType<typeof EditorView> | null = null;
await vi.waitFor(() => {
@@ -248,7 +293,8 @@ async function isSourceEditable(figure: HTMLElement) {
view = dom instanceof HTMLElement ? EditorView.findFromDOM(dom) : null;
expect(view).not.toBeNull();
}, { timeout: 5000 });
- return !(view as InstanceType<typeof EditorView> | null)?.state.readOnly;
+ if (!view) throw new Error("CodeMirror did not mount.");
+ return view as InstanceType<typeof EditorView>;
}
function buildEditor(): ContentEditor {
diff --git a/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.tsx b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.tsx
index a88ab4994d..1224ab3b34 100644
--- a/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.tsx
+++ b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.tsx
@@ -10,6 +10,8 @@ import type { RefObject } from "preact";
import { lazy, Suspense } from "preact/compat";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+import type { CommandNames } from "../../../components/app_context";
+import type { MenuItem } from "../../../menus/context_menu";
import { t } from "../../../services/i18n";
import { renderMermaidSvg } from "../../../services/mermaid";
import type { SourceEmbedProps } from "../../../services/source_embeds";
@@ -18,6 +20,7 @@ import { useDebouncedValue } from "../../react/hooks";
import OverlayControlGroup, { OverlayFullscreenButton } from "../../react/OverlayControlGroup";
import { useZoomPanWheel } from "../../react/zoom_pan";
import { useZoomPanKeyboard } from "../../react/zoom_pan_keyboard";
+import { useEmbedLines } from "../code/CodeEmbed";
import { SplitLayout, useMountedPanes } from "../helpers/SplitEditor";
import { type DisplayMode, resolveDisplayMode } from "../helpers/split_editor_mode";
import {
@@ -67,7 +70,8 @@ export default function MermaidDiagram({ content, editor }: SourceEmbedProps) {
const { editorMounted, previewMounted } = useMountedPanes(mode);
const isFullscreen = useIsEmbedFullscreen(rootRef);
const hasFullscreenButton = useNeedsFullscreenButton(rootRef) && !isFullscreen;
- tools.setState(zoom, mode);
+ const lines = useEmbedLines(rootRef, null);
+ tools.setState(zoom, mode, lines.menuItems);
// A source saved elsewhere, or undone, replaces the shown one unless it has unsaved edits.
useEffect(() => {
@@ -107,6 +111,8 @@ export default function MermaidDiagram({ content, editor }: SourceEmbedProps) {
mime={MERMAID_ATTACHMENT_MIME}
tabWidth={undefined}
useTabs={undefined}
+ wrapLines={lines.wrapLines}
+ hasLineNumbers={lines.hasLineNumbers}
viewRef={viewRef}
onContentChange={setSource}
onReady={setupEditor}
@@ -165,16 +171,18 @@ class MermaidDiagramTools implements ContentEmbedToolProvider {
private zoom: SvgZoom | null = null;
private isDiagramShown = true;
private isSourceShown = false;
+ private menuItems: MenuItem<CommandNames>[] = [];
private listeners = new Set<() => void>();
private shownTools = "";
constructor(private readonly rootRef: RefObject<HTMLElement | null>) {}
- /** Follows the zoom state and the display mode of the latest render. */
- setState(zoom: SvgZoom, mode: DisplayMode) {
+ /** Follows the zoom state, the display mode and the menu items of the latest render. */
+ setState(zoom: SvgZoom, mode: DisplayMode, menuItems: MenuItem<CommandNames>[]) {
this.zoom = zoom;
this.isDiagramShown = mode !== "source";
this.isSourceShown = mode !== "preview";
+ this.menuItems = menuItems;
// Notifies after the render, as a listener updates the toolbar of the editor.
queueMicrotask(() => this.update());
}
@@ -232,6 +240,10 @@ class MermaidDiagramTools implements ContentEmbedToolProvider {
};
}
+ getMenuItems() {
+ return this.menuItems;
+ }
+
/** Fullscreen, while the title row of the embed, which has a button for it, is hidden. */
private getFullscreenTools(): ContentEmbedTool[] {
if (!needsFullscreenButton(this.rootRef.current?.closest<HTMLElement>(".include-note"))) {
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
index ae97b4f560..e72baa8e30 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.spec.tsx
@@ -446,7 +446,8 @@ describe("ReadOnlyText embedded notes", () => {
describe("ReadOnlyText Mermaid diagrams", () => {
const html = `<pre data-box-size="small" data-display-mode="source" data-hide-title="true"`
- + ` data-trilium-block-id="b1" style="--include-note-height:12em;">`
+ + ` data-trilium-block-id="b1" data-code-wrap-lines="true" data-code-line-numbers="false"`
+ + ` style="--include-note-height:12em;">`
+ `<code class="language-mermaid">graph TD;</code></pre>`
+ `<pre><code class="language-mermaid" data-trilium-display-mode="split"`
+ ` data-trilium-block-id="b2">graph LR;</code></pre>`
@@ -495,7 +496,10 @@ describe("ReadOnlyText Mermaid diagrams", () => {
{
language: "mermaid", source: "graph TD;", isReadOnly: true, boxSize: "small",
options: { isFocused: false }, isInPage: true,
- data: { boxSize: "small", displayMode: "source", hideTitle: "true", triliumBlockId: "b1" },
+ data: {
+ boxSize: "small", displayMode: "source", hideTitle: "true",
+ triliumBlockId: "b1", codeWrapLines: "true", codeLineNumbers: "false"
+ },
height: "12em"
},
{
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
index 88108dd33a..157f2bcbb5 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx
@@ -262,10 +262,13 @@ function applySourceEmbeds(container: HTMLDivElement) {
const figure = document.createElement("figure");
figure.className = "include-note";
- const { boxSize, displayMode } = pre.dataset;
+ const { boxSize, displayMode, codeWrapLines, codeLineNumbers } = pre.dataset;
figure.dataset.boxSize = boxSize === "small" || boxSize === "full" ? boxSize : "medium";
- if (displayMode) {
- figure.dataset.displayMode = displayMode;
+ const views = { displayMode, codeWrapLines, codeLineNumbers };
+ for (const [ name, value ] of Object.entries(views)) {
+ if (value) {
+ figure.dataset[name] = value;
+ }
}
figure.dataset.hideTitle = "true";
// Diagrams saved before the embed keep their block ID on the `<code>`.
diff --git a/apps/client/src/widgets/type_widgets/text/content_embed_menus.spec.tsx b/apps/client/src/widgets/type_widgets/text/content_embed_menus.spec.tsx
index 915783fc32..e782a970bc 100644
--- a/apps/client/src/widgets/type_widgets/text/content_embed_menus.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/content_embed_menus.spec.tsx
@@ -3,7 +3,8 @@ import { useRef } from "preact/hooks";
import { act } from "preact/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
-import contextMenu, { type ContextMenuOptions } from "../../../menus/context_menu";
+import type { CommandNames } from "../../../components/app_context";
+import contextMenu, { type ContextMenuOptions, type MenuItem } from "../../../menus/context_menu";
import {
type ContentEmbedMenu, ContentEmbedMenus, useContentEmbedMenus
} from "./content_embed_menus";
@@ -17,6 +18,7 @@ const LANGUAGE: ContentEmbedMenu = {
filterable: true
};
const WIDTH: ContentEmbedMenu = { id: "width", title: "Change width", text: "4", items: [] };
+const WRAP_ITEM: MenuItem<CommandNames> = { title: "Word wrap", items: [] };
const elements: HTMLElement[] = [];
@@ -128,9 +130,14 @@ describe("useContentEmbedMenus", () => {
expect(tools?.hasEditableFlag).toBe(true);
expect(tools?.getTools().map((tool) => tool.text)).toEqual([ "Python" ]);
- act(() => render(<Harness menus={[ LANGUAGE, WIDTH ]} root={root} />, root));
+ expect(tools?.getMenuItems?.()).toEqual([]);
+
+ act(() => render(
+ <Harness menus={[ LANGUAGE, WIDTH ]} menuItems={[ WRAP_ITEM ]} root={root} />, root
+ ));
expect(getContentEmbedTools(figure)).toBe(tools);
expect(tools?.getTools().map((tool) => tool.text)).toEqual([ "Python", "4" ]);
+ expect(tools?.getMenuItems?.()).toEqual([ WRAP_ITEM ]);
act(() => render(null, root));
expect(getContentEmbedTools(figure)).toBeNull();
@@ -141,10 +148,16 @@ describe("useContentEmbedMenus", () => {
});
});
+interface HarnessProps {
+ menus: ContentEmbedMenu[];
+ menuItems?: MenuItem<CommandNames>[];
+ root?: HTMLElement;
+}
+
/** Mounts `useContentEmbedMenus()` with a ref to `root`, or to nothing while `root` is unset. */
-function Harness({ menus, root }: { menus: ContentEmbedMenu[]; root?: HTMLElement }) {
+function Harness({ menus, menuItems, root }: HarnessProps) {
const rootRef: RefObject<HTMLElement | null> = useRef(root ?? null);
- useContentEmbedMenus(rootRef, menus);
+ useContentEmbedMenus(rootRef, menus, menuItems);
return null;
}
diff --git a/apps/client/src/widgets/type_widgets/text/content_embed_menus.ts b/apps/client/src/widgets/type_widgets/text/content_embed_menus.ts
index e6b365bb84..ed1266ac5d 100644
--- a/apps/client/src/widgets/type_widgets/text/content_embed_menus.ts
+++ b/apps/client/src/widgets/type_widgets/text/content_embed_menus.ts
@@ -1,6 +1,7 @@
import type { RefObject } from "preact";
import { useEffect, useState } from "preact/hooks";
+import type { CommandNames } from "../../../components/app_context";
import contextMenu, { type ContextMenuOptions, type MenuItem } from "../../../menus/context_menu";
import linkContextMenu from "../../../menus/link_context_menu";
import {
@@ -22,15 +23,17 @@ export interface ContentEmbedMenu {
/**
* Adds a button for each of `menus` to the toolbar of the embed around `rootRef`, besides the
- * Editable toggle. The buttons follow `menus` as they change.
+ * Editable toggle, and `menuItems` to the menu of the embed. Both follow their arguments as they
+ * change.
*/
export function useContentEmbedMenus(
rootRef: RefObject<HTMLElement | null>,
- menus: ContentEmbedMenu[]
+ menus: ContentEmbedMenu[],
+ menuItems: MenuItem<CommandNames>[] = []
) {
const [ provider ] = useState(() => new ContentEmbedMenus(rootRef));
- useEffect(() => provider.setMenus(menus));
+ useEffect(() => provider.setMenus(menus, menuItems));
useEffect(() => {
const root = rootRef.current;
@@ -44,6 +47,7 @@ export function useContentEmbedMenus(
export class ContentEmbedMenus implements ContentEmbedToolProvider {
readonly hasEditableFlag = true;
private menus: ContentEmbedMenu[] = [];
+ private menuItems: MenuItem<CommandNames>[] = [];
/** The menu that is open, whose button shows as on. */
private openMenuId: string | null = null;
/** The menu that closed last. */
@@ -54,11 +58,17 @@ export class ContentEmbedMenus implements ContentEmbedToolProvider {
constructor(private readonly rootRef: RefObject<HTMLElement | null>) {}
- setMenus(menus: ContentEmbedMenu[]) {
+ /** Sets the menus of the buttons, and the items of the menu of the embed. */
+ setMenus(menus: ContentEmbedMenu[], menuItems: MenuItem<CommandNames>[] = []) {
this.menus = menus;
+ this.menuItems = menuItems;
this.update();
}
+ getMenuItems() {
+ return this.menuItems;
+ }
+
getTools(): ContentEmbedTool[] {
return this.menus.map(({ id, title, text }) => ({
id,
diff --git a/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts b/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts
index f4e17fb735..96707147e9 100644
--- a/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts
+++ b/apps/client/src/widgets/type_widgets/text/content_embed_tools.ts
@@ -3,6 +3,8 @@ import type { RefObject } from "preact";
import { flushSync } from "preact/compat";
import { useEffect, useRef, useState } from "preact/hooks";
+import type { CommandNames } from "../../../components/app_context";
+import type { MenuItem } from "../../../menus/context_menu";
import type { FindTarget } from "../../merged_find";
/** A button that the content of an embed adds to the toolbar of the embed. */
@@ -48,6 +50,8 @@ export interface ContentEmbedToolProvider {
openMenu?(id: string, anchor: HTMLElement): void;
/** Calls `callback` when `getTools()` changes, until the returned function is called. */
subscribe(callback: () => void): () => void;
+ /** The items that the content adds to the menu of the embed, after Editable. */
+ getMenuItems?(): MenuItem<CommandNames>[];
/** The items of the embed toolbar to hide. The menu of the embed still offers them. */
hiddenToolbarItems?: readonly ContentEmbedToolbarItem[];
/**
@@ -116,7 +120,7 @@ export function watchContentEmbedTools(container: HTMLElement, callback: () => v
}
/** The buttons that the content of `embed` adds to its toolbar, or `null`. */
-export function getContentEmbedTools(embed: HTMLElement) {
+export function getContentEmbedTools(embed: Element) {
for (const [ element, provider ] of providers) {
if (embed.contains(element)) {
return provider;
@@ -350,6 +354,29 @@ export function useContentEmbedAttribute(
});
}
+/** The `"true"` or `"false"` attribute `name` of `embed`, or `undefined` while it is unset. */
+export function getContentEmbedFlag(embed: Element | null | undefined, name: string) {
+ const value = embed?.getAttribute(name);
+ return value == null ? undefined : value !== "false";
+}
+
+/**
+ * {@link getContentEmbedFlag} for the embed that contains `ref`, which follows its changes.
+ * `initial` until the content is in the embed.
+ */
+export function useContentEmbedFlag(
+ ref: RefObject<HTMLElement | null>,
+ name: string,
+ initial?: boolean
+) {
+ return useEmbedState(ref, {
+ initial,
+ outsideEmbed: initial,
+ attributes: [ name ],
+ read: (embed) => getContentEmbedFlag(embed, name)
+ });
+}
+
/**
* The display mode picked for the embed that contains `ref`, for content whose provider sets
* `hasDisplayModes`. `null` while none is picked, outside an embed, and until the content is in the
diff --git a/apps/client/src/widgets/type_widgets/text/utils.spec.ts b/apps/client/src/widgets/type_widgets/text/utils.spec.ts
index 52ecfb57e2..981a41f594 100644
--- a/apps/client/src/widgets/type_widgets/text/utils.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/utils.spec.ts
@@ -258,17 +258,27 @@ describe("loadEmbeddedAttachment", () => {
expect(lastMount().props).toMatchObject({ isFocusedOnMount: true });
});
- it("renders a code file in the language that its embed sets", async () => {
+ it("renders a code file or note in the language and lines that its embed sets", async () => {
const wrapper = createWrapper();
const embed = inPage(document.createElement("figure"));
embed.className = "include-note";
embed.setAttribute("data-code-language", "text/x-sh");
+ embed.setAttribute("data-code-wrap-lines", "false");
+ embed.setAttribute("data-code-line-numbers", "false");
embed.append(wrapper);
+ const getLastOptions = () =>
+ vi.mocked(content_renderer.getRenderedContent).mock.lastCall?.[1];
await loadEmbeddedAttachment("att1", $(wrapper), "full");
+ expect(getLastOptions()).toMatchObject({
+ codeLanguage: "text/x-sh", isCodeWrapped: false, hasCodeLineNumbers: false
+ });
- expect(vi.mocked(content_renderer.getRenderedContent).mock.lastCall?.[1])
- .toMatchObject({ codeLanguage: "text/x-sh" });
+ // A note keeps its language and line wrapping in its own labels.
+ await loadEmbeddedNote("noteY", $(wrapper), "full");
+ expect(getLastOptions()).toMatchObject({ hasCodeLineNumbers: false });
+ expect(getLastOptions()).not.toHaveProperty("codeLanguage");
+ expect(getLastOptions()).not.toHaveProperty("isCodeWrapped");
});
it("leaves the box alone for a deleted attachment", async () => {
diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.ts
index 5c02f5f092..ce6757a924 100644
--- a/apps/client/src/widgets/type_widgets/text/utils.ts
+++ b/apps/client/src/widgets/type_widgets/text/utils.ts
@@ -7,7 +7,7 @@ import linkContextMenu from "../../../menus/link_context_menu";
import content_renderer, {
type AttachmentEditor, CONTENT_RENDERERS, type NoteEditor
} from "../../../services/content_renderer";
-import { getEmbedCaption } from "../../../services/content_renderer_text";
+import { getEmbedCaption, getEmbedCodeView } from "../../../services/content_renderer_text";
import froca from "../../../services/froca";
import link, { ViewScope } from "../../../services/link";
import { getSourceEmbedTypeByLanguage } from "../../../services/source_embeds";
@@ -74,7 +74,8 @@ export async function loadEmbeddedNote(
hasDisplayModes: true,
noteEditor,
block,
- onBlockChange
+ onBlockChange,
+ hasCodeLineNumbers: getEmbedCodeView(el.closest(".include-note")).hasCodeLineNumbers
});
const box = h(ContentEmbed, {
@@ -140,7 +141,7 @@ export async function loadEmbeddedAttachment(
mediaEnvironment: "embedded",
hasDisplayModes: true,
attachmentEditor,
- codeLanguage: el.closest(".include-note")?.getAttribute("data-code-language") ?? undefined
+ ...getEmbedCodeView(el.closest(".include-note"))
});
const box = h(ContentEmbed, {
diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.json
index cf35b158c2..033b53d8e9 100644
--- a/apps/server/src/assets/help/help_content.json
+++ b/apps/server/src/assets/help/help_content.json
@@ -134,8 +134,8 @@
"_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>. 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 <em>Editable</em>. 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 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>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>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_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_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>",
"_help_UmgZAfcltxkS": "<p>Link previews turn a pasted URL into a rich, metadata-aware widget that can be displayed in three visual modes:</p><h2>Display modes</h2><p>A link preview can be displayed in one of three modes:</p><ul><li><strong>Inline</strong> — a link showing the site's favicon and page title (quite similar to&nbsp;<a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a>). Use this when you want the link to flow with the surrounding paragraph.</li><li><strong>Card</strong> — a block-level preview with thumbnail, title, description, and site name. Use this when the link is the focus of a paragraph.</li><li><strong>Embed</strong> — a block-level interactive embed.<ul><li>Currently supported for YouTube videos, which render interactively (via an <code>iframe</code>).</li><li>To prevent unwanted remote requests, the video is shown only after clicking on it first.</li></ul></li></ul><div class=\"trilium-multicolumn-layout\" data-trilium-column-ratios=\"1-1-1\"><div class=\"trilium-multicolumn-column\"><figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:251/42;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Link%20Previews_image.png\" width=\"251\" height=\"42\"><figcaption><em>Inline</em> link preview</figcaption></figure></div><div class=\"trilium-multicolumn-column\"><figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:1217/196;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Link%20Previews_image.png\" width=\"1217\" height=\"196\"><figcaption><em>Card</em> link preview</figcaption></figure></div><div class=\"trilium-multicolumn-column\"><figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:994/563;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Link%20Previews_image.png\" width=\"994\" height=\"563\"><figcaption><em>Embed</em> link preview</figcaption></figure></div></div><h2>Inserting a link preview</h2><p>There are three ways to create one:</p><h3>1. By pasting a URL</h3><p>A link preview is automatically created:</p><ul><li>By pasting the URL and pressing <kbd>Space</kbd>. This will create an <em>inline</em> link preview.</li><li>When at the start of a new paragraph, pressing <kbd>Enter</kbd> will create a <em>card</em> or an <em>embed</em> for YouTube URLs.</li></ul><p>To undo an automatic link preview, press <kbd>Ctrl</kbd>+<kbd>Z</kbd> immediately afterwards which keeps it as a plain link instead. Alternatively, once a link preview was created, click on the link and select <em>Plain link</em> from the link preview toolbar.</p><p>This automatic conversion can be disabled by going to&nbsp;<a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a>&nbsp;→ <em>Text Notes</em> and unchecking <em>Autogenerate link previews</em> from the <em>Features</em> section.</p><p>If the link is not accessible to the Trilium server (or the network request fails for any other reason), it will not be converted to a link preview.</p><aside class=\"admonition note\"><p>A URL is only auto-converted when the pasted text <em>is</em> the URL. Links with a display name (e.g. <a href=\"https://triliumnotes.org\">Trilium Notes website</a>) are left as plain links.</p></aside><h3>2. By using the \"Link preview\" toolbar button</h3><p>Click <em>Link preview</em> (<span class=\"tn-icon cke cke-trilium-link-preview\"></span>) in the formatting toolbar to open the <em>Link preview</em> popup. Paste the URL and choose the type of preview.</p><h3>3. By saving browser tabs from the Web Clipper</h3><p>When the&nbsp;<a class=\"reference-link\" href=\"#root/_help_MtPxeAWVAzMg\">Web Clipper</a>&nbsp;saves the tabs of a window, each tab becomes an <em>inline</em> link preview showing the title and favicon the browser displays for it. Because this data comes from the browser, pages behind a login keep their real title, and the Trilium server does not contact the saved pages.</p><p>When <em>Autogenerate link previews</em> is turned off, the tabs are saved as a list of plain links instead.</p><h2>Altering an existing link preview</h2><p>Click on an inserted link preview to select it, and a small toolbar will appear with the following options:</p><ul><li>The normal link operations (opening in a new tab, copying the link, unlinking).</li><li>A button to edit the title of the link preview. This is especially useful if the title is hidden behind a login screen.</li><li>A way to switch between the link preview modes (Inline, Card or Embed) as well as to convert it to a normal link instead.<ul><li>The Embed option is only enabled when the URL points to a supported service (YouTube today).</li></ul></li></ul><h2>Where the preview data comes from</h2><p>When you insert a link preview, Trilium fetches metadata once and stores it inside the note's HTML:</p><ul><li><strong>YouTube URLs</strong> — title, channel name, and thumbnail are fetched via YouTube's public oEmbed endpoint.</li><li><strong>All other URLs</strong> — Trilium fetches the page and reads OpenGraph tags (<code>og:title</code>, <code>og:description</code>, <code>og:image</code>, <code>og:site_name</code>), falling back to the page's <code>&lt;title&gt;</code> and <code>&lt;meta name=\"description\"&gt;</code>. The site's favicon is downloaded and inlined.</li></ul><p>Because the data is stored in the note itself, link previews continue to render correctly when you reopen the note, share/publish it, or export to HTML — without any further network requests.</p><p>The metadata is captured <strong>at insertion time</strong> and is not automatically refreshed. If the linked page later changes its title or thumbnail, you'll need to re-insert the link to pick up the new values. To refresh a link, simply create it again.</p><p>When accessing a&nbsp;<a class=\"reference-link\" href=\"#root/_help_WOcw2SLH6tbX\">Server Installation</a>, the data is fetched from the remote URL by the server and not the client.</p><h2>Known limitations</h2><ul><li>The Embed display mode currently only supports YouTube. Other video and media platforms fall back to a Card preview.</li><li>Pages that block automated fetches may produce a minimal preview (hostname only).</li><li>Link previews require the Trilium server to reach the target URL, so they won't generate previews for pages on networks the server can't see.</li></ul>",
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 f1fbe3817e..1a8a7098ff 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
@@ -66,7 +66,7 @@ To open an included note in a new tab, press the <span class="tn-icon bx bx-link
The <span class="tn-icon bx bx-dots-vertical-rounded"></span> _More actions_ 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.
-In a note being edited, the menu also has the commands of the include's toolbar: the _Size_ submenu, _Show title_ and _Show caption_, each checked while it is in effect, and _Convert to link_ 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 _Editable_, above _Size_. A Mermaid diagram, an included Markdown note and an embedded Markdown file also have _Source view_, _Split view_ and _Preview_ after _Editable_. For an embedded attachment they follow its first group of actions; for an included note they end the menu.
+In a note being edited, the menu also has the commands of the include's toolbar: the _Size_ submenu, _Show title_ and _Show caption_, each checked while it is in effect, and _Convert to link_ 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 _Editable_, above _Size_. An included code or Markdown note, an embedded code or Markdown file and a Mermaid diagram also have the _Word wrap_ and _Line numbers_ submenus after _Editable_ (see _Editing an include in place_ below). A Mermaid diagram, an included Markdown note and an embedded Markdown file also have _Source view_, _Split view_ and _Preview_ after these submenus. For an embedded attachment they follow its first group of actions; for an included note they end the menu.
To show an include of size _Medium_ or _Full_ on the whole screen, press the <span class="tn-icon bx bx-fullscreen"></span> _Fullscreen_ 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> _Edit excerpt_ button there instead; see <a class="reference-link" href="Block%20references.md">Block references</a>. To return, press <span class="tn-icon bx bx-exit"></span> _Exit fullscreen_ in the top-right corner, or <kbd>Esc</kbd>.
@@ -115,6 +115,9 @@ An included text note, an included code note and an embedded code file such as a
* 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.
+* The <span class="tn-icon cke cke-three-vertical-dots"></span> _More actions_ menu of an included code or Markdown note, an embedded code or Markdown file and a [Mermaid diagram](Insert%20buttons.md) has two more submenus after _Editable_, each with _Auto_, _On_ and _Off_. They change how the code editor shows the source, and for code the preview as well.
+ * _Word wrap_ wraps long lines instead of scrolling them. _Auto_ follows the setting in <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Code Notes_. For an included note, it sets the `#wrapLines` label of the note, as the _Word wrap_ submenu of its <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Note%20menu.md">Note menu</a> does for a code note. For an embedded file or a Mermaid diagram, it changes only this include.
+ * _Line numbers_ shows or hides the numbers at the start of each line. _Auto_ shows them, as a code note does. It changes only this include, for an included note as well.
* The changes are saved as you type, to the included note or to the attachment, as they would be in its own tab.
* An include of <a class="reference-link" href="Block%20references.md">Block references</a> edits only the referenced blocks.
* Editing is not available in a [read-only note](../../Basic%20Concepts%20and%20Features/Notes/Read-Only%20Notes.md), for an included note marked `#readOnly`, or for an attachment of another note.
@@ -127,6 +130,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 _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.
* While the source shows, the include has the height of its box size, or the height it was resized to. A _Full_ include gets a fixed height too, instead of fitting its content.
diff --git a/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md b/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md
index ef9c44f85b..aa834f0ceb 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md
@@ -53,6 +53,7 @@ A diagram shows in a box like the one of an included note, so it can be resized,
* The <span class="tn-icon bx bx-edit-alt"></span> _Editable_ 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.
* The buttons next to it choose what the diagram shows, as for a Mermaid note: <span class="tn-icon bx bx-code"></span> _Source view_ for the Mermaid source alone, <span class="tn-icon bx bxs-dock-left"></span> _Split view_ for the source with the diagram next to it, and <span class="tn-icon bx bx-show"></span> _Preview_ for the diagram alone. Its _More actions_ menu offers the same choice.
+* The _Word wrap_ and _Line numbers_ submenus of its _More actions_ menu change how the source shows, each with _Auto_, _On_ and _Off_, as for an included code note (see _Editing an include in place_ in <a class="reference-link" href="Include%20Note.md">Include Note</a>).
* A new diagram starts editable, in _Split view_. 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.
* 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 _Medium_ or _Full_ diagram also has a <span class="tn-icon bx bx-fullscreen"></span> _Fullscreen_ button there, or over the source in the _Source_ view.
* 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.
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
index ca39f1f1bf..d09f682b8f 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.spec.ts
@@ -1498,7 +1498,8 @@ describe("ContentEmbed code view", () => {
+ " data-box-size=\"full\">&nbsp;</figure>";
const CODE_VIEW = ATTACHMENT.replace("data-box-size=\"full\"", "data-box-size=\"full\""
+ " data-code-language=\"text/x-python\" data-code-tab-width=\"2\""
- + " data-code-indent-with-tabs=\"false\"");
+ + " data-code-indent-with-tabs=\"false\" data-code-wrap-lines=\"true\""
+ + " data-code-line-numbers=\"false\"");
let editor: ClassicEditor;
let loadEmbeddedAttachment: ReturnType<typeof vi.fn>;
@@ -1522,7 +1523,7 @@ describe("ContentEmbed code view", () => {
/** The `data-code-*` attributes of the rendered embed. */
function getRenderedCodeView() {
const embed = editor.editing.view.getDomRoot()?.querySelector("figure.include-note");
- return [ "language", "tab-width", "indent-with-tabs" ]
+ return [ "language", "tab-width", "indent-with-tabs", "wrap-lines", "line-numbers" ]
.map((name) => embed?.getAttribute(`data-code-${name}`) ?? null);
}
@@ -1536,15 +1537,16 @@ describe("ContentEmbed code view", () => {
expect(getModelData(editor.model, { withoutSelection: true })).toBe(
"<contentEmbed attachmentId=\"att1\" boxSize=\"full\" codeIndentWithTabs=\"false\""
- + " codeLanguage=\"text/x-python\" codeTabWidth=\"2\"></contentEmbed>"
+ + " codeLanguage=\"text/x-python\" codeLineNumbers=\"false\" codeTabWidth=\"2\""
+ + " codeWrapLines=\"true\"></contentEmbed>"
);
expect(editor.getData()).toBe(CODE_VIEW);
- expect(getRenderedCodeView()).toEqual([ "text/x-python", "2", "false" ]);
+ expect(getRenderedCodeView()).toEqual([ "text/x-python", "2", "false", "true", "false" ]);
editor.setData(ATTACHMENT);
expect(getModelData(editor.model, { withoutSelection: true })).not.toContain("code");
expect(editor.getData()).toBe(ATTACHMENT);
- expect(getRenderedCodeView()).toEqual([ null, null, null ]);
+ expect(getRenderedCodeView()).toEqual([ null, null, null, null, null ]);
});
it("sets and removes the settings of the selected embed as one undo step each", () => {
@@ -1553,31 +1555,38 @@ describe("ContentEmbed code view", () => {
const wrapper = editor.editing.view.getDomRoot()?.querySelector(".include-note-wrapper");
editor.execute(CODE_VIEW_COMMAND_NAME, {
- language: "text/x-python", tabWidth: 2, indentWithTabs: true
+ language: "text/x-python", tabWidth: 2, indentWithTabs: true, wrapLines: true,
+ lineNumbers: false
});
- expect(getRenderedCodeView()).toEqual([ "text/x-python", "2", "true" ]);
+ expect(getRenderedCodeView()).toEqual([ "text/x-python", "2", "true", "true", "false" ]);
expect(editor.getData()).toBe(CODE_VIEW.replace("\"false\"", "\"true\""));
- editor.execute(CODE_VIEW_COMMAND_NAME, { language: null, indentWithTabs: false });
- expect(getRenderedCodeView()).toEqual([ null, "2", "false" ]);
+ editor.execute(CODE_VIEW_COMMAND_NAME, {
+ language: null, indentWithTabs: false, wrapLines: false, lineNumbers: null
+ });
+ expect(getRenderedCodeView()).toEqual([ null, "2", "false", "false", null ]);
editor.execute("undo");
- expect(getRenderedCodeView()).toEqual([ "text/x-python", "2", "true" ]);
+ expect(getRenderedCodeView()).toEqual([ "text/x-python", "2", "true", "true", "false" ]);
editor.execute("undo");
- expect(getRenderedCodeView()).toEqual([ null, null, null ]);
+ expect(getRenderedCodeView()).toEqual([ null, null, null, null, null ]);
expect(editor.editing.view.getDomRoot()?.querySelector(".include-note-wrapper"))
.toBe(wrapper);
expect(loadEmbeddedAttachment).toHaveBeenCalledTimes(1);
});
- it("is enabled only on an embed of an attachment, whose included notes follow the note", () => {
+ it("sets only the line numbers of an included note, which follows the note otherwise", () => {
setModelData(editor.model, "<paragraph>foo[]</paragraph>");
expect(getCommand().isEnabled).toBe(false);
editor.execute(CODE_VIEW_COMMAND_NAME, { language: "text/x-python" });
insertContentEmbed(editor, "n1", "full");
- expect(getCommand().isEnabled).toBe(false);
- editor.execute(CODE_VIEW_COMMAND_NAME, { language: "text/x-python" });
+ expect(getCommand().isEnabled).toBe(true);
+ editor.execute(CODE_VIEW_COMMAND_NAME, {
+ language: "text/x-python", tabWidth: 2, indentWithTabs: true, wrapLines: true,
+ lineNumbers: false
+ });
+ expect(getRenderedCodeView()).toEqual([ null, null, null, null, "false" ]);
expect(editor.getData()).not.toContain("data-code-language");
editor.setData(ATTACHMENT);
diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
index 5e9eb74846..81bc3d22e8 100644
--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts
@@ -96,13 +96,16 @@ type EmbedFlag = typeof FLAG_ATTRIBUTES[number][0];
const DISPLAY_MODE_ATTRIBUTE = [ 'displayMode', 'data-display-mode' ] as const;
/**
- * How an embed of an attachment shows its code: the language, as a MIME type, the tab width, and
- * whether it indents with tabs. Each is saved in a `data-*` attribute while it is set.
+ * How an embed shows its code: the language, as a MIME type, the tab width, whether it indents with
+ * tabs, whether it wraps the lines, and whether it shows line numbers. Each is saved in a `data-*`
+ * attribute while it is set.
*/
const CODE_VIEW_ATTRIBUTES = [
[ 'codeLanguage', 'data-code-language' ],
[ 'codeTabWidth', 'data-code-tab-width' ],
- [ 'codeIndentWithTabs', 'data-code-indent-with-tabs' ]
+ [ 'codeIndentWithTabs', 'data-code-indent-with-tabs' ],
+ [ 'codeWrapLines', 'data-code-wrap-lines' ],
+ [ 'codeLineNumbers', 'data-code-line-numbers' ]
] as const;
/** The settings of `SetContentEmbedCodeViewCommand`. `null` removes a setting. */
@@ -110,6 +113,8 @@ export interface ContentEmbedCodeView {
language?: string | null;
tabWidth?: number | null;
indentWithTabs?: boolean | null;
+ wrapLines?: boolean | null;
+ lineNumbers?: boolean | null;
}
/** What the toolbar of an embed shows of it, for a menu offering the same commands. */
@@ -946,26 +951,32 @@ export class ToggleContentEmbedEditableCommand extends Command {
}
/**
- * Sets how the selected embed of an attachment shows its code. An embed of a note follows the
- * settings of the note instead.
+ * Sets how the selected embed shows its code. An embed of a note sets only the line numbers, and
+ * follows the other settings of the note.
*/
export class SetContentEmbedCodeViewCommand extends Command {
override refresh() {
- this.isEnabled = !!getSelectedContentEmbed( this.editor )?.getAttribute( 'attachmentId' );
+ this.isEnabled = !!getSelectedContentEmbed( this.editor );
}
/** Sets each setting given, and removes each given as `null`, as one undo step. */
- override execute( { language, tabWidth, indentWithTabs }: ContentEmbedCodeView ) {
+ override execute( {
+ language, tabWidth, indentWithTabs, wrapLines, lineNumbers
+ }: ContentEmbedCodeView ) {
const embed = getSelectedContentEmbed( this.editor );
/* v8 ignore next 3 -- the command is enabled only while an embed is selected */
if ( !embed ) {
return;
}
- const values = {
+ const values = embed.getAttribute( 'noteId' ) ? {
+ codeLineNumbers: lineNumbers
+ } : {
codeLanguage: language,
codeTabWidth: tabWidth,
- codeIndentWithTabs: indentWithTabs
+ codeIndentWithTabs: indentWithTabs,
+ codeWrapLines: wrapLines,
+ codeLineNumbers: lineNumbers
};
this.editor.model.change( writer => {
for ( const [ attribute, value ] of Object.entries( values ) ) {
@@ -1277,7 +1288,7 @@ function getFlagAttributes( element: ModelElement ): Record<string, string> {
}
/** The `data-*` attributes of the code view settings of `element`. */
-function getCodeViewAttributes( element: ModelElement ): Record<string, string> {
+export function getCodeViewAttributes( element: ModelElement ): Record<string, string> {
return Object.fromEntries( CODE_VIEW_ATTRIBUTES
.filter( ( [ setting ] ) => element.hasAttribute( setting ) )
.map( ( [ setting, dataAttribute ] ) => [
@@ -1286,7 +1297,7 @@ function getCodeViewAttributes( element: ModelElement ): Record<string, string>
}
/** The code view settings that the `data-*` attributes of a saved embed set. */
-function getCodeViewOfView( viewElement: ViewElement ): Record<string, string> {
+export function getCodeViewOfView( viewElement: ViewElement ): Record<string, string> {
return Object.fromEntries( CODE_VIEW_ATTRIBUTES
.filter( ( [ , dataAttribute ] ) => viewElement.hasAttribute( dataAttribute ) )
.map( ( [ setting, dataAttribute ] ) => [
diff --git a/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts b/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts
index b5d45d8f53..f96d7374e7 100644
--- a/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts
@@ -22,6 +22,7 @@ import ContentEmbedBoxSizeDropdown, {
import ContentEmbed, {
BOX_SIZE_COMMAND_NAME,
BOX_SIZES,
+ CODE_VIEW_COMMAND_NAME,
CONTENT_EMBED_MENU,
CONVERT_EMBED_TO_LINK_COMMAND,
TOGGLE_CAPTION_COMMAND_NAME,
@@ -112,6 +113,23 @@ describe("ContentEmbedInlineSource", () => {
expect(editor.getData()).toContain("--include-note-height:12em");
});
+ it("keeps how the embed shows its code on the <pre>, set by the code view command", () => {
+ const html = `<pre data-box-size="medium" data-hide-title="true"`
+ + ` data-code-wrap-lines="true" data-code-line-numbers="false">`
+ + `<code class="language-mermaid">x</code></pre>`;
+ editor.setData(html);
+
+ expect([ "codeWrapLines", "codeLineNumbers" ].map((name) => getEmbed().getAttribute(name)))
+ .toEqual([ "true", "false" ]);
+ expect(editor.getData()).toBe(html);
+
+ editor.model.change((writer) => writer.setSelection(getEmbed(), "on"));
+ expect(editor.commands.get(CODE_VIEW_COMMAND_NAME)?.isEnabled).toBe(true);
+ editor.execute(CODE_VIEW_COMMAND_NAME, { wrapLines: null, lineNumbers: true });
+ expect(editor.getData()).toBe(`<pre data-box-size="medium" data-hide-title="true"`
+ + ` data-code-line-numbers="true"><code class="language-mermaid">x</code></pre>`);
+ });
+
it("leaves a code block of another language alone", () => {
editor.setData(
`<pre><code class="language-javascript">let a;</code></pre>`
diff --git a/packages/ckeditor5/src/plugins/content_embed/inline_source.ts b/packages/ckeditor5/src/plugins/content_embed/inline_source.ts
index 2002533818..47e9529ffe 100644
--- a/packages/ckeditor5/src/plugins/content_embed/inline_source.ts
+++ b/packages/ckeditor5/src/plugins/content_embed/inline_source.ts
@@ -15,6 +15,8 @@ import {
import { SIZE_ATTRIBUTES } from '../resizable_widgets/resizable_widgets.js';
import {
type BoxSizeValue,
+ getCodeViewAttributes,
+ getCodeViewOfView,
getDisplayModeAttributes,
getDisplayModeOfView,
INLINE_BOX_SIZES,
@@ -155,7 +157,8 @@ export default class ContentEmbedInlineSource extends Plugin {
hideTitle: true,
...getModeOfSavedView( pre, code ),
...getFlagsOfView( pre ),
- ...getSizesOfView( pre )
+ ...getSizesOfView( pre ),
+ ...getCodeViewOfView( pre )
} );
if ( !api.safeInsert( embed, data.modelCursor ) ) {
return;
@@ -217,7 +220,10 @@ function downcastData( model: Model, embed: ModelElement, api: DowncastConversio
}
}
- const pre = writer.createContainerElement( 'pre', preAttributes );
+ const pre = writer.createContainerElement( 'pre', {
+ ...preAttributes,
+ ...getCodeViewAttributes( embed )
+ } );
const code = writer.createContainerElement( 'code', {
class: `language-${ embed.getAttribute( 'language' ) as string }`
} );
diff --git a/packages/codemirror/src/code_preview.css b/packages/codemirror/src/code_preview.css
index c86ec2d384..f5bb283cfd 100644
--- a/packages/codemirror/src/code_preview.css
+++ b/packages/codemirror/src/code_preview.css
@@ -44,6 +44,15 @@
white-space: pre-wrap;
overflow-wrap: anywhere;
}
+
+ &.code-preview-no-line-numbers > .code-preview-content {
+ padding-inline-start: 6px;
+ background: var(--code-preview-background);
+
+ > .code-preview-line::before {
+ content: none;
+ }
+ }
}
.code-preview-line::before {
diff --git a/packages/codemirror/src/code_preview.spec.ts b/packages/codemirror/src/code_preview.spec.ts
index 39b553576e..eb20142601 100644
--- a/packages/codemirror/src/code_preview.spec.ts
+++ b/packages/codemirror/src/code_preview.spec.ts
@@ -55,6 +55,9 @@ describe("renderCodePreview", () => {
const plain = render(null);
expect(plain.className).toBe("code-preview");
+ expect(parse(renderCodePreview(code, {
+ themes: slots, language: null, isWrapped: true, hasLineNumbers: false
+ })).className).toBe("code-preview code-preview-wrap code-preview-no-line-numbers");
expect(plain.getAttribute("style")).toBe("--code-preview-digits: 2");
expect(plain.querySelectorAll(".code-preview-line span").length).toBe(0);
expect(plain.querySelector(".code-preview-line")?.innerHTML).toBe("x &lt; 0");
diff --git a/packages/codemirror/src/code_preview.ts b/packages/codemirror/src/code_preview.ts
index e8af7f72a9..7391e12d6d 100644
--- a/packages/codemirror/src/code_preview.ts
+++ b/packages/codemirror/src/code_preview.ts
@@ -20,6 +20,8 @@ export interface CodePreviewOptions {
/** The language that highlights the code, or `null` to show it plain. */
language: Language | null;
isWrapped: boolean;
+ /** Whether to number the lines. Defaults to true. */
+ hasLineNumbers?: boolean;
}
const DEFAULT_THEME_ID = "default";
@@ -41,12 +43,16 @@ const loadedLanguages = new Map<string, Language | null>();
*/
export function renderCodePreview(
code: string,
- { themes, language, isWrapped }: CodePreviewOptions
+ { themes, language, isWrapped, hasLineNumbers = true }: CodePreviewOptions
) {
const text = code.replace(/\r\n?/g, "\n");
const lines = (language && highlightLines(text, language, themes))
?? text.split("\n").map(escapeHtml);
- const className = isWrapped ? "code-preview code-preview-wrap" : "code-preview";
+ const className = [
+ "code-preview",
+ ...(isWrapped ? [ "code-preview-wrap" ] : []),
+ ...(hasLineNumbers ? [] : [ "code-preview-no-line-numbers" ])
+ ].join(" ");
const attributes = themes
.map(({ theme, key }) => ` data-code-theme-${key}="${escapeHtml(theme.id)}"`)
.join("");
diff --git a/packages/codemirror/src/index.spec.ts b/packages/codemirror/src/index.spec.ts
index d3303a0467..05342d494a 100644
--- a/packages/codemirror/src/index.spec.ts
+++ b/packages/codemirror/src/index.spec.ts
@@ -265,6 +265,24 @@ describe("CodeMirror", () => {
expect(editor.getText()).toBe("");
});
+ it("shows line numbers unless configured off, and toggles them both ways", () => {
+ const hasLineNumbers = (view: CodeMirror) =>
+ !!view.dom.querySelector(".cm-lineNumbers");
+ editor = build();
+ expect(hasLineNumbers(editor)).toBe(true);
+ const gutter = editor.dom.querySelector(".cm-lineNumbers");
+ editor.setLineNumbers(true);
+ expect(editor.dom.querySelector(".cm-lineNumbers")).toBe(gutter);
+ editor.setLineNumbers(false);
+ expect(hasLineNumbers(editor)).toBe(false);
+ editor.setLineNumbers(true);
+ expect(hasLineNumbers(editor)).toBe(true);
+ editor.destroy();
+
+ editor = build({ lineNumbers: false });
+ expect(hasLineNumbers(editor)).toBe(false);
+ });
+
it("clamps the indent size to a sane range", () => {
editor = build();
diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.ts
index 5d74bc91a2..1fde02f558 100644
--- a/packages/codemirror/src/index.ts
+++ b/packages/codemirror/src/index.ts
@@ -62,6 +62,8 @@ export interface EditorConfig {
parent: HTMLElement;
placeholder?: string;
lineWrapping?: boolean;
+ /** Whether to show the line numbers in the gutter. Defaults to true. */
+ lineNumbers?: boolean;
vimKeybindings?: boolean;
readOnly?: boolean;
/** Disables some of the nice-to-have features (bracket matching, syntax highlighting, indentation markers) in order to improve performance. */
@@ -94,6 +96,8 @@ export default class CodeMirror extends EditorView {
private historyCompartment: Compartment;
private themeCompartment: Compartment;
private lineWrappingCompartment: Compartment;
+ private lineNumbersCompartment: Compartment;
+ private hasLineNumbers: boolean;
private keyboardSuggestionsCompartment: Compartment;
private indentUnitCompartment: Compartment;
private searchHighlightCompartment: Compartment;
@@ -115,6 +119,7 @@ export default class CodeMirror extends EditorView {
const historyCompartment = new Compartment();
const themeCompartment = new Compartment();
const lineWrappingCompartment = new Compartment();
+ const lineNumbersCompartment = new Compartment();
const keyboardSuggestionsCompartment = new Compartment();
const indentUnitCompartment = new Compartment();
const searchHighlightCompartment = new Compartment();
@@ -139,7 +144,7 @@ export default class CodeMirror extends EditorView {
typeCompletionCompartment.of([]),
completionSourceCompartment.of([]),
highlightActiveLine(),
- lineNumbers(),
+ lineNumbersCompartment.of(config.lineNumbers === false ? [] : lineNumbers()),
themeCompartment.of([
syntaxHighlighting(defaultHighlightStyle, { fallback: true })
]),
@@ -194,6 +199,8 @@ export default class CodeMirror extends EditorView {
this.historyCompartment = historyCompartment;
this.themeCompartment = themeCompartment;
this.lineWrappingCompartment = lineWrappingCompartment;
+ this.lineNumbersCompartment = lineNumbersCompartment;
+ this.hasLineNumbers = config.lineNumbers !== false;
this.keyboardSuggestionsCompartment = keyboardSuggestionsCompartment;
this.indentUnitCompartment = indentUnitCompartment;
this.searchHighlightCompartment = searchHighlightCompartment;
@@ -272,6 +279,15 @@ export default class CodeMirror extends EditorView {
});
}
+ setLineNumbers(isShown: boolean) {
+ if (isShown === this.hasLineNumbers) return;
+
+ this.hasLineNumbers = isShown;
+ this.dispatch({
+ effects: [ this.lineNumbersCompartment.reconfigure(isShown ? lineNumbers() : []) ]
+ });
+ }
+
setAllowKeyboardSuggestions(allow: boolean) {
this.dispatch({
effects: [ this.keyboardSuggestionsCompartment.reconfigure(allow ? proseKeyboardAttributes : noKeyboardSuggestions) ]