Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/text editor/content embed: add support for an unified undo/redo history across the host text note and its content embeds
Adorian Doran8e49f1712a58
diff --git a/.claude/skills/developing-content-embeds/SKILL.md b/.claude/skills/developing-content-embeds/SKILL.mdindex 6a66ef9b7d..122b45504c 100644--- a/.claude/skills/developing-content-embeds/SKILL.md+++ b/.claude/skills/developing-content-embeds/SKILL.md@@ -47,8 +47,10 @@ All three carry `boxSize`, `hideTitle`, `editable`, `displayMode` (`data-box-siz- **Inline source** (`inline_source.ts`, `ContentEmbedInlineSource`) keeps the document readableelsewhere: the note exports to Markdown as a fenced `mermaid` block, other apps render it, and- undo in the note undoes source edits (`setSource()` is one step of the editor's undo and does- **not** redraw the embed, which would remount its editor). It is converted only for languages in+ undo in the note undoes source edits through the shared undo history (see _Undo history_ below).+ `setSource()` writes outside the undo stack and does **not** redraw the embed, which would+ remount its editor. The plugin hands out one `InlineEmbedSource` per embed element, which keys+ its history. It is converted only for languages in`contentEmbed.inlineLanguages` (from `SOURCE_EMBED_TYPES` in `text/config.ts`); a code block ofanother language stays a code block.- **Legacy blocks** — a `<pre>` without `data-box-size` predates the embed (the old Mermaid@@ -138,6 +140,33 @@ embeds receive `SourceEmbedProps` (`content`, `editor`) whichever storage the sothe content to offer one: a toolbar tool while it can be edited, an `OverlayFullscreenButton`after the zoom buttons while read-only (no toolbar then). A read-only drawing still has none.+## Undo history++The edits made in an embed's CodeMirror (code, Markdown, Mermaid, inline or not) are steps of the+text editor's undo stack, in order with the text's own changes. Three layers:++- **`EmbedHistory`** (`packages/ckeditor5/src/plugins/content_embed/embed_history.ts`, required by+ `ContentEmbed`) is editor-agnostic. `push({ undo, redo })` adds a batch that only adds or removes+ the `embedHistoryStep` marker (`affectsData: false`): it fires `change`, which resets the typing+ buffer, but not `change:data`. The `revert` events of `undo`/`redo` run the step; a step that+ returns `false` is skipped and the command runs again. `isLatest()` tells the content whether+ its step can still grow. `undo()`/`redo()` are for keys pressed inside an embed: they focus the+ text editor when the reverted change was its own.+- **`SharedHistory`** (`packages/codemirror/src/shared_history.ts`) records the transactions of+ every view of one document, grouped as `history()` groups them, and applies a step to the view+ whose document matches, else through `write` while no view shows it (a remount in progress). A+ step whose document changed since does not apply. `view.setSharedHistory()` replaces the view's+ own `history()` and routes Mod-Z/Mod-Y/Mod-Shift-Z, the `historyUndo`/`historyRedo` input+ events and Vim's `u`/`Ctrl-R` to the host.+- **`EmbedHistories`** (`text/embed_history.ts`, one per `EditableText`) gives a `ContentHistory`+ (`host` + `write`) per note ID, attachment ID or `InlineEmbedSource`, as `ContentEditor.history`.+ It imports no CodeMirror at runtime: `CodeEmbedEditor` creates the `SharedHistory` on it, and+ attaches it while mounted, read-only included.++Content loaded from elsewhere goes through `view.loadText()`, which stays out of the history; a+`setText()` (re-indent) is a step. Another editor joins by pushing its own steps to `EmbedHistory`+through the same `host`. Included text notes and drawing canvases keep their own history.+## Recipe: a new source embed (a diagram language)1. Add a `SourceEmbedType` to `SOURCE_EMBED_TYPES` in `apps/client/src/services/source_embeds.ts`:@@ -148,8 +177,8 @@ embeds receive `SourceEmbedProps` (`content`, `editor`) whichever storage the soattachment icon map next to it; add the content type to the list in `content_renderer.ts`.3. Write the component on the note type's parts (see the rule above). For a split source/previewview, `SplitLayout` + `useMountedPanes()` + `EmbedSourcePane` (in `code/CodeEmbedEditor.tsx`)- give the layout, the divider, the error card, the stale badge and a source pane that keeps its- undo history behind the preview. Delay re-rendering with `useDebouncedValue()`. Give the root+ give the layout, the divider, the error card, the stale badge and a source pane that stays+ mounted behind the preview and shares the note's undo history. Delay re-rendering with `useDebouncedValue()`. Give the rootthe `include-note-box-height` class for the 10/20/50em heights per box size and full height infullscreen (content with a height of its own can fit it at Full instead, as`MarkdownEmbed.css` sets `height: auto` down to the split's columns), and round it with `--_include-note-content-*-radius` (edge to edge) or@@ -195,9 +224,8 @@ in-place drawings replaced the code blocks the boxes need.source and `setData()` then dropped the embed, whose later write went to the graveyard. Theeditor hands each held write to `InlineSourceSaves` (`text/attachment_saves.ts`), which marks thenote changed, and `getData()` in `EditableText` flushes it first — as `AttachmentSaves` does for- attachments. The text editor's Undo and Redo flush it too (`flushBeforeHistory()`): otherwise- Undo reverted the write before it, the embed ignored that while it held newer text, and the held- write then landed after the Undo and cleared Redo.+ attachments. The write is outside the undo stack, so it can land after an undo without clearing+ Redo; the undo step itself is recorded when the source changes (see _Undo history_).- **Non-interactive rendering must be finished when it returns.** A presentation slide snapshots`getRenderedContent()` and disposes it at once, so a mounted component that draws in an effectleaves it blank. Without `options.interactive`, draw a picture before returning@@ -219,7 +247,7 @@ in-place drawings replaced the code blocks the boxes need.included note.- **Switch editability in place, never by remounting.** `CodeMirror.tsx` follows its `readOnly`prop through `setReadOnly()`, which keeps the view, its scroll and selection, and starts a new- undo history. A `key` that remounted `CodeEmbedEditor` on the toggle painted an empty `<pre>` (a+ undo history unless the view has a shared one. A `key` that remounted `CodeEmbedEditor` on the toggle painted an empty `<pre>` (aFull box collapsed) and then CodeMirror's light default until `setTheme()` loaded the theme. Anembed renders read-only before it finds its figure, so this runs on every editable load too.`CodeMirror` keeps the `onContentChanged` it was created with, so `CodeEmbedEditor` reads thediff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.tsindex 2022e3a071..8a1aeb5e23 100644--- a/apps/client/src/services/content_renderer.spec.ts+++ b/apps/client/src/services/content_renderer.spec.ts@@ -158,6 +158,7 @@ import Component from "../components/component.js";import type { SaveState } from "../components/note_context.js";import FAttachment from "../entities/fattachment.js";import { buildNote } from "../test/easy-froca.js";+import EmbedHistories from "../widgets/type_widgets/text/embed_history.js";import {addContentDisposer,CONTENT_RENDERERS,@@ -547,6 +548,32 @@ describe("getRenderedContent editable code", () => {expect(attachmentEditor.release).toHaveBeenCalledWith(att.attachmentId);});+ it("gives the editor of a note or a file its undo history in the text note", async () => {+ const note = buildNote({+ title: "Script", type: "code", mime: "text/javascript", content: ""+ });+ const att = buildAttachment({ role: "file", mime: "application/json" });+ att.getBlob = (async () => ({ content: "{}" })) as any;+ const noteEditor = buildEditor();+ const attachmentEditor = buildEditor();+ const histories = new EmbedHistories(() => null);++ await getRenderedContent(note, { interactive: true, noteEditor, histories });+ await getRenderedContent(att, { interactive: true, attachmentEditor, histories });+ const [ noteHistory, fileHistory ] = codeEmbedComponent.mock.calls+ .map(([ props ]) => props.editor.history);+ expect(noteHistory).toBe(histories.get(note.noteId, vi.fn()));+ expect(fileHistory).toBe(histories.get(att.attachmentId, vi.fn()));++ // Content that no editor shows saves through the editor of the embed.+ noteHistory.write("a");+ fileHistory.write("b");+ expect(noteEditor.scheduleSave.mock.lastCall?.[0]).toBe(note);+ expect(noteEditor.scheduleSave.mock.lastCall?.[1]()).toBe("a");+ expect(attachmentEditor.scheduleSave.mock.lastCall?.[0]).toBe(att);+ expect(attachmentEditor.scheduleSave.mock.lastCall?.[1]()).toBe("b");+ });+it("highlights a code file in the language that 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;diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.tsindex d0a64dc0f3..dc0a591137 100644--- a/apps/client/src/services/content_renderer.ts+++ b/apps/client/src/services/content_renderer.ts@@ -23,6 +23,9 @@ 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 {+ ContentHistory, default as EmbedHistories+} from "../widgets/type_widgets/text/embed_history.js";import type { CodePreviewLines } from "./code_note_preview.js";import renderText, {postProcessRichContent, renderChildrenList, renderTextContent@@ -123,6 +126,8 @@ export interface RenderOptions {* Without it, that content is read-only.*/noteEditor?: NoteEditor;+ /** Keeps the undo steps of the content on the undo stack of the text note that shows it. */+ histories?: EmbedHistories;/** The component a JSX render note mounts under, by default the one of the closest `.component` element. */parentComponent?: Component;}@@ -564,6 +569,8 @@ export interface ContentEditor {getSaveState?(): SaveState | undefined;/** Calls `listener` when `getSaveState()` changes, until the returned call. */subscribeSaveState?(listener: () => void): () => void;+ /** The undo history that the content shares with the text note that shows it. */+ history?: ContentHistory;}/** `editor`, saving the changes to `attachment`. */@@ -585,7 +592,13 @@ function getContentEditor(options: RenderOptions): ContentEditor | undefined {if (entity instanceof FAttachment) {- return options.attachmentEditor && bindAttachmentEditor(options.attachmentEditor, entity);+ const editor = options.attachmentEditor;+ return editor && {+ ...bindAttachmentEditor(editor, entity),+ history: options.histories?.get(entity.attachmentId, (text) => {+ editor.scheduleSave(entity, () => text);+ })+ };}const editor = options.noteEditor;@@ -595,7 +608,10 @@ function getContentEditor(scheduleSave: (getContent, onSaved) => editor.scheduleSave(entity, getContent, onSaved),release: () => editor.release(entity.noteId),getSaveState: () => editor.getSaveState(entity.noteId),- subscribeSaveState: (listener) => editor.subscribeSaveState(listener)+ subscribeSaveState: (listener) => editor.subscribeSaveState(listener),+ history: options.histories?.get(entity.noteId, (text) => {+ editor.scheduleSave(entity, () => text);+ })} : undefined;}diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsxindex 904f046bb1..09331ca7ec 100644--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.spec.tsx@@ -1,3 +1,4 @@+import { AttributeEditor, EmbedHistory } from "@triliumnext/ckeditor5";import VanillaCodeMirror from "@triliumnext/codemirror";import moveVerticalIcon from "boxicons/svg/regular/bx-move-vertical.svg?raw";import { render } from "preact";@@ -24,6 +25,7 @@ import { ParentComponent } from "../../react/react_utils";import { CodeMirrorFindTarget } from "../../find_in_code";import { NoteSaves } from "../text/attachment_saves";import { getContentEmbedTools, getEmbedFindTarget } from "../text/content_embed_tools";+import EmbedHistories from "../text/embed_history";import CodeEmbed from "./CodeEmbed";vi.mock("../../../services/i18n", async (importOriginal) => ({@@ -163,6 +165,61 @@ describe("CodeEmbed", () => {expect(view.state.doc.toString()).toBe("#print(1)\nlog(2)");});+ it("keeps its edits on the text note's undo stack, read-only and remounted too", async () => {+ const element = document.createElement("div");+ document.body.append(element);+ const textEditor = await AttributeEditor.create(element, {+ licenseKey: "GPL", extraPlugins: [ EmbedHistory ]+ });+ const histories = new EmbedHistories(() => textEditor);+ const note = buildCodeNote("x");+ const editor = buildSavingEditor(note, histories);+ const { figure } = await mount(note, editor, { isEditable: true });+ let view = await findView(figure);+ const outside = vi.fn();+ figure.addEventListener("keydown", outside);++ // Content saved elsewhere loads outside the undo stack.+ note.getBlob = async () => buildBlob("a");+ const noteSaved = new LoadResults([]);+ noteSaved.addNoteContent(note.noteId, "any-component");+ await act(async () => {+ await parent.handleEvent("entitiesReloaded", { loadResults: noteSaved });+ });+ await vi.waitFor(() => expect(view.state.doc.toString()).toBe("a"));+ expect(textEditor.commands.get("undo")?.isEnabled).toBe(false);++ act(() => view.dispatch({ changes: { from: 1, insert: "b" }, userEvent: "input.type" }));+ act(() => textEditor.execute("undo"));+ expect([ view.state.doc.toString(), editor.getUnsavedContent() ]).toEqual([ "a", "a" ]);+ act(() => textEditor.execute("redo"));+ expect([ view.state.doc.toString(), editor.getUnsavedContent() ]).toEqual([ "ab", "ab" ]);++ // The undo keys of the embed undo the note, while read-only as well.+ await act(async () => {+ delete figure.dataset.editable;+ await Promise.resolve();+ });+ view = await findView(figure, true);+ act(() => pressKey(view.contentDOM, "z"));+ expect(view.state.doc.toString()).toBe("a");+ expect(outside).not.toHaveBeenCalled();++ // The next step applies to a remounted editor.+ const box = figure.querySelector(".include-note-content");+ if (box) act(() => render(null, box));+ figure.remove();+ const { figure: remounted } = await mount(note, editor, {+ isEditable: true, content: editor.getUnsavedContent()+ });+ view = await findView(remounted);+ act(() => pressKey(view.contentDOM, "y"));+ expect([ view.state.doc.toString(), editor.getUnsavedContent() ]).toEqual([ "ab", "ab" ]);++ await textEditor.destroy();+ element.remove();+ });+it("switches the same CodeMirror to editing and back, and releases the edits", async () => {const note = buildCodeNote("a");const editor = buildSavingEditor(note);@@ -683,16 +740,24 @@ function buildEditor(overrides: Partial<ContentEditor> = {}): ContentEditor {}/** An editor of `note` over real `NoteSaves`, which the embeds given it share as a host's do. */-function buildSavingEditor(note: FNote): ContentEditor {+function buildSavingEditor(note: FNote, histories?: EmbedHistories): ContentEditor {const saves = new NoteSaves(() => {}, undefined);return {canEdit: () => true,getUnsavedContent: () => saves.getUnsavedContent(note.noteId),scheduleSave: (getContent, onSaved) => saves.scheduleSave(note, getContent, onSaved),- release: () => saves.release(note.noteId)+ release: () => saves.release(note.noteId),+ history: histories?.get(note.noteId, (text) => saves.scheduleSave(note, () => text))};}+/** Presses Ctrl and `key` in `target`. */+function pressKey(target: HTMLElement, key: string) {+ target.dispatchEvent(new KeyboardEvent("keydown", {+ key, ctrlKey: true, bubbles: true, cancelable: true+ }));+}+/*** Runs the item `title` of the toolbar menu `id` of `figure`, from the "Re-indent" part of the* menu when `isReindent`. `contextMenu.show` must be mocked.diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsxindex c4f253aca7..dd411b57e4 100644--- a/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbed.tsx@@ -87,6 +87,7 @@ export default function CodeEmbed({note={note}ownerNote={entity instanceof FNote ? entity : entity.getNote()}editor={isEditing ? editor : undefined}+ history={editor?.history}content={content}mime={mime}tabWidth={settings.tabWidth}diff --git a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsxindex 6cd35f3e48..1cfea7b9d2 100644--- a/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx+++ b/apps/client/src/widgets/type_widgets/code/CodeEmbedEditor.tsx@@ -1,4 +1,5 @@import type VanillaCodeMirror from "@triliumnext/codemirror";+import { SharedHistory } from "@triliumnext/codemirror";import clsx from "clsx";import type { RefObject } from "preact";import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";@@ -9,6 +10,7 @@ import { CodeMirrorFindTarget } from "../../find_in_code";import { useNoteLabelOptionalBool, useTriliumOptionBool } from "../../react/hooks";import { registerEmbedFindTarget } from "../text/content_embed_tools";import { CaretNavigationContext, useEmbedCaretNavigation } from "../text/editable_embed";+import type { ContentHistory } from "../text/embed_history";import { CodeEditor } from "./Code";export interface CodeEmbedEditorProps {@@ -17,6 +19,8 @@ export interface CodeEmbedEditorProps {ownerNote?: FNote | null;/** Saves the edits, or `undefined` to show the content read-only. */editor: ContentEditor | undefined;+ /** The undo history that the content shares with the text note, also while read-only. */+ history?: ContentHistory;content: string;mime: string;/** The tab width, or `undefined` to follow the global option. */@@ -44,8 +48,8 @@ export interface CodeEmbedEditorProps {* `editor`, the content is read-only.*/export default function CodeEmbedEditor({- note, ownerNote, editor, content, mime, tabWidth, useTabs, wrapLines, hasLineNumbers, viewRef,- isShown = true, onClose, onChange, onReady+ note, ownerNote, editor, history, content, mime, tabWidth, useTabs, wrapLines, hasLineNumbers,+ viewRef, isShown = true, onClose, onChange, onReady}: CodeEmbedEditorProps) {const isLoadingRef = useRef(false);const [ vimKeymapEnabled ] = useTriliumOptionBool("vimKeymapEnabled");@@ -82,11 +86,19 @@ export default function CodeEmbedEditor({// Loading changes the document as well, which must not schedule a save.isLoadingRef.current = true;- view.setText(content);+ view.loadText(content);isLoadingRef.current = false;view.clearHistory();}, [ view, content ]);+ useLayoutEffect(() => {+ if (!view || !history) return;++ history.shared ??= new SharedHistory(history.host, history.write);+ view.setSharedHistory(history.shared);+ return () => view.setSharedHistory(null);+ }, [ view, history ]);+// Layout cleanups run as `editor` goes away and during the unmount, before CodeMirror is// destroyed, in the order of these hooks.useLayoutEffect(() => {@@ -163,6 +175,7 @@ export function EmbedSourcePane({><CodeEmbedEditoreditor={isEditing ? editor : undefined}+ history={editor?.history}isShown={isSourceShown}onClose={onContentChange}onChange={onContentChange}diff --git a/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx b/apps/client/src/widgets/type_widgets/code/CodeMirror.tsxindex 2da2af8213..bb75ed9626 100644--- a/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx+++ b/apps/client/src/widgets/type_widgets/code/CodeMirror.tsx@@ -52,7 +52,7 @@ export default function CodeMirror({ className, content, mime, editorRef: extern// React to text changes.useEffect(() => {const codeEditor = codeEditorRef.current;- codeEditor?.setText(content ?? "");+ codeEditor?.loadText(content ?? "");codeEditor?.setMimeType(mime);codeEditor?.clearHistory();}, [content]);diff --git a/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsx b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsxindex f97becc5bd..97700de740 100644--- a/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsx+++ b/apps/client/src/widgets/type_widgets/mermaid/MermaidDiagram.spec.tsx@@ -208,6 +208,28 @@ describe("MermaidDiagram", () => {expect(await findSourceView(figure)).toBe(view);});+ it("keeps the edits of its source on the text note's undo stack, read-only too", async () => {+ const host = {+ push: vi.fn(() => ({ isLatest: () => false })), undo: vi.fn(), redo: vi.fn()+ };+ const editor = { ...buildEditor(), history: { host, write: vi.fn() } };+ const { figure } = await mount({ editor, isEditable: true, displayMode: "split" });+ const view = await findSourceView(figure);++ act(() => view.dispatch({ changes: { from: 0, insert: "%% " } }));+ expect(host.push).toHaveBeenCalledOnce();++ await act(async () => {+ delete figure.dataset.editable;+ await Promise.resolve();+ });+ expect(await isSourceEditable(figure)).toBe(false);+ view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", {+ key: "z", ctrlKey: true, bubbles: true, cancelable: true+ }));+ expect(host.undo).toHaveBeenCalledOnce();+ });+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({diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 70cc96000c..3ad8320d5f 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -44,6 +44,7 @@ import AttachmentSaves, { InlineSourceSaves, useNoteEditor } from "./attachment_import CKEditor, { CKEditorApi, NotificationEventData, NotificationEventInfo } from "./CKEditor";import { enterContentEmbed, getContentEmbedTools } from "./content_embed_tools";import { useEmbedEditors } from "./editable_embed";+import EmbedHistories from "./embed_history";import getTemplates, { updateTemplateCache } from "./snippets.js";import linkEmbedService from "../../../services/link_embed";import { usesClassicToolbar } from "./toolbar";@@ -103,9 +104,13 @@ export default function EditableText({new AttachmentSaves(() => spacedUpdate.scheduleUpdate()));const [ inlineSourceSaves ] = useState(() =>new InlineSourceSaves(() => spacedUpdate.scheduleUpdate()));+ const [ embedHistories ] = useState(() => new EmbedHistories(() => editorRef.current));const noteEditor = useNoteEditor(noteContext);- const { noteEditor: embedNoteEditor, attachmentEditor: embedAttachmentEditor } =- useEmbedEditors({ noteEditor, attachmentEditor: attachmentSaves });+ const {+ noteEditor: embedNoteEditor, attachmentEditor: embedAttachmentEditor, histories+ } = useEmbedEditors({+ noteEditor, attachmentEditor: attachmentSaves, histories: embedHistories+ });const spacedUpdate = useEditorSpacedUpdate({note,noteContext,@@ -286,6 +291,7 @@ export default function EditableText({) {return loadEmbeddedNote(noteId, $el, boxSize, {noteEditor: embedNoteEditor,+ histories,block: embedBlock,onBlockChange});@@ -297,6 +303,7 @@ export default function EditableText({}return loadEmbeddedAttachment(attachmentId, $el, boxSize, {attachmentEditor: embedAttachmentEditor,+ histories,isFocused});},@@ -306,7 +313,9 @@ export default function EditableText({boxSize: string | undefined,options: { isFocused: boolean }) {- return loadInlineEmbed(source, $el, boxSize, { ...options, saves: inlineSourceSaves });+ return loadInlineEmbed(source, $el, boxSize, {+ ...options, saves: inlineSourceSaves, histories+ });},focusContentEmbed(attachmentId: string) {focusedAttachmentIdRef.current = attachmentId;@@ -409,7 +418,9 @@ export default function EditableText({useTriliumEvent("refreshEmbeddedNote", ({ noteId }) => {if (!containerRef.current) return;- refreshEmbeddedNote(containerRef.current, noteId, { noteEditor: embedNoteEditor });+ refreshEmbeddedNote(containerRef.current, noteId, {+ noteEditor: embedNoteEditor, histories+ });});useEffect(() => () => stopWatchingEmbedsRef.current?.(), []);@@ -664,7 +675,6 @@ export default function EditableText({editor.plugins.get("FileUploadEditing").on<FileUploadEvent>("upload", showFileUploadProgress);- inlineSourceSaves.flushBeforeHistory(editor);if (block !== undefined) {editor.plugins.get("BlockReferenceEditing").editRange();diff --git a/apps/client/src/widgets/type_widgets/text/SourceEmbed.spec.tsx b/apps/client/src/widgets/type_widgets/text/SourceEmbed.spec.tsxindex e15e5a1427..71867b970d 100644--- a/apps/client/src/widgets/type_widgets/text/SourceEmbed.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/SourceEmbed.spec.tsx@@ -5,6 +5,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import type { SourceEmbedProps } from "../../../services/source_embeds";import { InlineSourceSaves } from "./attachment_saves";+import EmbedHistories from "./embed_history";import { createInlineSourceEditor, InlineSourceEmbed } from "./SourceEmbed";/** An inline source as the text editor hands it over, which notifies its listeners on writes. */@@ -96,6 +97,19 @@ describe("createInlineSourceEditor", () => {it("cannot edit the source of a read-only text editor", () => {expect(createInlineSourceEditor(createSource("a", true)).canEdit()).toBe(false);});++ it("shares the undo history of a source with the text note, which writes it at once", () => {+ const source = createSource("a");+ const histories = new EmbedHistories(() => null);+ const history = createInlineSourceEditor(source, undefined, histories).history;++ expect(history).toBe(createInlineSourceEditor(source, undefined, histories).history);+ expect(createInlineSourceEditor(createSource("a"), undefined, histories).history)+ .not.toBe(history);+ expect(createInlineSourceEditor(source).history).toBeUndefined();+ history?.write("b");+ expect(source.setSource).toHaveBeenCalledExactlyOnceWith("b");+ });});describe("InlineSourceEmbed", () => {diff --git a/apps/client/src/widgets/type_widgets/text/SourceEmbed.tsx b/apps/client/src/widgets/type_widgets/text/SourceEmbed.tsxindex 2d6b8ab7d5..eb43bbf6e2 100644--- a/apps/client/src/widgets/type_widgets/text/SourceEmbed.tsx+++ b/apps/client/src/widgets/type_widgets/text/SourceEmbed.tsx@@ -7,6 +7,7 @@ import type FAttachment from "../../../entities/fattachment";import type FNote from "../../../entities/fnote";import type { ContentEditor } from "../../../services/content_renderer";import type { InlineSourceSaves } from "./attachment_saves";+import type EmbedHistories from "./embed_history";import type { SourceEmbedProps } from "../../../services/source_embeds";import { useSavedContent } from "../code/CodeEmbed";@@ -33,12 +34,17 @@ interface InlineSourceEmbedProps {component: ComponentType<SourceEmbedProps>;/** The writes that the text note saves first. */saves?: InlineSourceSaves;+ /** Keeps the undo steps of the source on the undo stack of the text note. */+ histories?: EmbedHistories;}/** The component of a source embed type, over a source kept inline in the text note. */-export function InlineSourceEmbed({ source, component: Component, saves }: InlineSourceEmbedProps) {+export function InlineSourceEmbed({+ source, component: Component, saves, histories+}: InlineSourceEmbedProps) {const content = useSyncExternalStore(source.subscribe, source.getSource);- const editor = useMemo(() => createInlineSourceEditor(source, saves), [ source, saves ]);+ const editor = useMemo(+ () => createInlineSourceEditor(source, saves, histories), [ source, saves, histories ]);useEffect(() => () => editor.release(), [ editor ]);return <Component content={content} editor={editor} />;@@ -46,12 +52,13 @@ export function InlineSourceEmbed({ source, component: Component, saves }: Inlin/*** The editor of a source kept inline, which writes the source into the text note a moment after- * it stops changing, each write one step of the text editor's undo. Until then `saves` holds the- * write, so that the text note makes it before it saves.+ * it stops changing. Until then `saves` holds the write, so that the text note makes it before it+ * saves.*/export function createInlineSourceEditor(source: InlineEmbedSource,- saves?: InlineSourceSaves+ saves?: InlineSourceSaves,+ histories?: EmbedHistories): ContentEditor {let getPending: (() => string) | undefined;let timeout: ReturnType<typeof setTimeout> | undefined;@@ -79,7 +86,8 @@ export function createInlineSourceEditor(onSaved?.(source.getSource());}, INLINE_SAVE_DELAY);},- release: flush+ release: flush,+ history: histories?.get(source, (text) => source.setSource(text))};}diff --git a/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts b/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.tsindex 1f1dbed2a3..b8c77516da 100644--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts@@ -1,5 +1,3 @@-import { AttributeEditor } from "@triliumnext/ckeditor5";-import { _setModelData } from "ckeditor5";import { h, render } from "preact";import { act } from "preact/test-utils";import { describe, expect, it, vi } from "vitest";@@ -297,38 +295,27 @@ describe("useNoteEditor", () => {});describe("InlineSourceSaves", () => {- it("makes the held writes before the text editor undoes or redoes, as a step of their own", async () => {- const element = document.createElement("div");- document.body.append(element);- const editor = await AttributeEditor.create(element, { licenseKey: "GPL" });- const type = (text: string) => editor.model.change((writer) => {- editor.model.insertContent(writer.createText(text));- });- const saves = new InlineSourceSaves(() => {});- saves.flushBeforeHistory(editor);+ it("schedules a save for a held write, and makes the writes still held on flush", () => {+ const scheduleUpdate = vi.fn();+ const saves = new InlineSourceSaves(scheduleUpdate);+ const made: string[] = [];// Holds a write that, like an inline source, leaves `saves` once made.const hold = (text: string) => {const write = () => {saves.delete(write);- type(text);+ made.push(text);};saves.add(write);+ return write;};- _setModelData(editor.model, "<paragraph>a[]</paragraph>");- type("b");- hold("c");- editor.execute("undo");- expect(editor.getData()).toBe("<p>ab</p>");-- editor.execute("redo");- expect(editor.getData()).toBe("<p>abc</p>");-- hold("d");- editor.execute("redo");- expect(editor.getData()).toBe("<p>abcd</p>");+ hold("a");+ const written = hold("b");+ written();+ expect(scheduleUpdate).toHaveBeenCalledTimes(2);- await editor.destroy();- element.remove();+ saves.flush();+ saves.flush();+ expect(made).toEqual([ "b", "a" ]);});});diff --git a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts b/apps/client/src/widgets/type_widgets/text/attachment_saves.tsindex b2830aed6a..00b5c70722 100644--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.ts@@ -1,4 +1,3 @@-import type { CKTextEditor } from "@triliumnext/ckeditor5";import { useCallback, useContext, useEffect, useRef, useState } from "preact/hooks";import type { default as NoteContext, SaveState } from "../../../components/note_context";@@ -251,17 +250,6 @@ export class InlineSourceSaves {write();}}-- /**- * Makes the held writes before `editor` undoes or redoes, so that a held write is a step of- * the undo history rather than a change made after it.- */- flushBeforeHistory(editor: Pick<CKTextEditor, "commands">) {- for (const name of [ "undo", "redo" ]) {- // Runs before the command checks `isEnabled`, which a held write can turn on.- editor.commands.get(name)?.on("execute", () => this.flush(), { priority: "highest" });- }- }}/**diff --git a/apps/client/src/widgets/type_widgets/text/embed_history.spec.ts b/apps/client/src/widgets/type_widgets/text/embed_history.spec.tsnew file mode 100644index 0000000000..d1d311659f--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/embed_history.spec.ts@@ -0,0 +1,44 @@+import { AttributeEditor, EmbedHistory } from "@triliumnext/ckeditor5";+import { describe, expect, it, vi } from "vitest";++import EmbedHistories from "./embed_history";++describe("EmbedHistories", () => {+ it("gives one history to each note, attachment or inline source", () => {+ const histories = new EmbedHistories(() => null);+ const write = vi.fn();+ const source = {};++ const note = histories.get("note1", write);+ expect(histories.get("note1", vi.fn())).toBe(note);+ expect(note.write).toBe(write);+ expect(histories.get("note2", write)).not.toBe(note);+ expect(histories.get(source, write)).toBe(histories.get(source, vi.fn()));+ expect(histories.get(source, write)).not.toBe(note);+ });++ it("keeps the steps on the undo stack of the text editor, once there is one", async () => {+ let editor: AttributeEditor | null = null;+ const { host } = new EmbedHistories(() => editor).get("note1", vi.fn());+ const step = { undo: vi.fn(() => true), redo: vi.fn(() => true) };++ expect(host.push(step).isLatest()).toBe(false);+ host.undo();+ host.redo();+ expect(step.undo).not.toHaveBeenCalled();++ const element = document.createElement("div");+ document.body.append(element);+ editor = await AttributeEditor.create(element, {+ licenseKey: "GPL", extraPlugins: [ EmbedHistory ]+ });+ expect(host.push(step).isLatest()).toBe(true);+ host.undo();+ expect(step.undo).toHaveBeenCalledOnce();+ host.redo();+ expect(step.redo).toHaveBeenCalledOnce();++ await editor.destroy();+ element.remove();+ });+});diff --git a/apps/client/src/widgets/type_widgets/text/embed_history.ts b/apps/client/src/widgets/type_widgets/text/embed_history.tsnew file mode 100644index 0000000000..2bf2cb9250--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/embed_history.ts@@ -0,0 +1,50 @@+import type { CKTextEditor } from "@triliumnext/ckeditor5";+import type { HostHistory, SharedHistory } from "@triliumnext/codemirror";++/** The undo history of a note, an attachment or an inline source that a text note embeds. */+export interface ContentHistory {+ /** The undo stack of the text note. */+ readonly host: HostHistory;+ /** Saves the content while no editor shows it. */+ readonly write: (text: string) => void;+ /** The history of the code editors of the content, which the first of them creates. */+ shared?: SharedHistory;+}++/**+ * The undo histories of the content in the embeds of a text note, which keep their steps on the+ * undo stack of the text editor.+ */+export default class EmbedHistories {+ private readonly byId = new Map<string, ContentHistory>();+ private readonly bySource = new WeakMap<object, ContentHistory>();+ private readonly host: HostHistory;++ constructor(getEditor: () => Pick<CKTextEditor, "plugins"> | null) {+ const getPlugin = () => getEditor()?.plugins.get("EmbedHistory");+ this.host = {+ push: (step) => getPlugin()?.push(step) ?? { isLatest: () => false },+ undo: () => getPlugin()?.undo(),+ redo: () => getPlugin()?.redo()+ };+ }++ /**+ * The history of the content that `key` identifies: the ID of a note or an attachment, or the+ * source of an inline embed. `write` saves the content while no editor shows it.+ */+ get(key: string | object, write: (text: string) => void): ContentHistory {+ const existing = typeof key === "string" ? this.byId.get(key) : this.bySource.get(key);+ if (existing) {+ return existing;+ }++ const history: ContentHistory = { host: this.host, write };+ if (typeof key === "string") {+ this.byId.set(key, history);+ } else {+ this.bySource.set(key, history);+ }+ return history;+ }+}diff --git a/apps/client/src/widgets/type_widgets/text/utils.spec.ts b/apps/client/src/widgets/type_widgets/text/utils.spec.tsindex 981a41f594..a93ba0de5e 100644--- a/apps/client/src/widgets/type_widgets/text/utils.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.spec.ts@@ -48,6 +48,7 @@ import ContentEmbed, {TinyContentEmbed,type TinyContentEmbedProps} from "./ContentEmbed";+import EmbedHistories from "./embed_history";import {getAttachmentHref,loadEmbeddedAttachment,@@ -243,9 +244,11 @@ describe("loadEmbeddedAttachment", () => {it("passes the attachment editor to the renderer, and the focus to the box", async () => {const attachmentEditor = { canEdit: vi.fn() } as never;+ const histories = new EmbedHistories(() => null);await loadEmbeddedAttachment("att1", $(createWrapper()), "medium", {attachmentEditor,+ histories,isFocused: true});@@ -253,7 +256,8 @@ describe("loadEmbeddedAttachment", () => {interactive: true,mediaEnvironment: "embedded",hasDisplayModes: true,- attachmentEditor+ attachmentEditor,+ histories});expect(lastMount().props).toMatchObject({ isFocusedOnMount: true });});@@ -403,8 +407,9 @@ describe("refreshEmbeddedNote", () => {+ `<section class="include-note" data-note-id="noteY" data-block="b1"></section>`+ `<figure class="include-note" data-note-id="other"></figure>`;const [ figure, section ] = [ ...container.children ];+ const histories = new EmbedHistories(() => null);- refreshEmbeddedNote(container, "noteY");+ refreshEmbeddedNote(container, "noteY", { histories });await vi.waitFor(() => {expect(content_renderer.mountInteractiveWidget).toHaveBeenCalledTimes(2);@@ -413,7 +418,8 @@ describe("refreshEmbeddedNote", () => {.map(([ , wrapper ]) => wrapper.parentElement);expect(mountedIn).toEqual([ figure, section ]);expect(vi.mocked(content_renderer.getRenderedContent).mock.calls- .map(([ , options ]) => options?.block)).toEqual([ undefined, "b1" ]);+ .map(([ , options ]) => [ options?.block, options?.histories ]))+ .toEqual([ [ undefined, histories ], [ "b1", histories ] ]);});});diff --git a/apps/client/src/widgets/type_widgets/text/utils.ts b/apps/client/src/widgets/type_widgets/text/utils.tsindex ce6757a924..df294d5e7e 100644--- a/apps/client/src/widgets/type_widgets/text/utils.ts+++ b/apps/client/src/widgets/type_widgets/text/utils.ts@@ -15,10 +15,13 @@ import utils from "../../../services/utils";import type { InlineSourceSaves } from "./attachment_saves";import { watchContentEmbedTools } from "./content_embed_tools";import ContentEmbed, { getNoteActions, TinyContentEmbed } from "./ContentEmbed";+import type EmbedHistories from "./embed_history";interface EmbeddedNoteOptions {/** Saves the changes that the content makes to the note, such as a code note. */noteEditor?: NoteEditor;+ /** Keeps the undo steps of the content on the undo stack of the text note. */+ histories?: EmbedHistories;/** The blocks of the note to show, a `block` link parameter. The whole note when left out. */block?: string;/** Points the embed at the blocks that its editor holds, once they change. */@@ -33,7 +36,7 @@ export async function loadEmbeddedNote(noteId: string,$el: JQuery<HTMLElement>,boxSize?: string,- { noteEditor, block, onBlockChange }: EmbeddedNoteOptions = {}+ { noteEditor, histories, block, onBlockChange }: EmbeddedNoteOptions = {}) {const note = await froca.getNote(noteId);if (!note) return;@@ -73,6 +76,7 @@ export async function loadEmbeddedNote(mediaEnvironment: "embedded",hasDisplayModes: true,noteEditor,+ histories,block,onBlockChange,hasCodeLineNumbers: getEmbedCodeView(el.closest(".include-note")).hasCodeLineNumbers@@ -93,6 +97,8 @@ export async function loadEmbeddedNote(interface EmbeddedAttachmentOptions {/** Saves the changes that the content makes to the attachment, such as a canvas drawing. */attachmentEditor?: AttachmentEditor;+ /** Keeps the undo steps of the content on the undo stack of the text note. */+ histories?: EmbedHistories;/** Whether the content takes the focus once the box is mounted. */isFocused?: boolean;}@@ -105,7 +111,7 @@ export async function loadEmbeddedAttachment(attachmentId: string,$el: JQuery<HTMLElement>,boxSize?: string,- { attachmentEditor, isFocused }: EmbeddedAttachmentOptions = {}+ { attachmentEditor, histories, isFocused }: EmbeddedAttachmentOptions = {}) {const attachment = await froca.getAttachment(attachmentId, true);if (!attachment) return;@@ -141,6 +147,7 @@ export async function loadEmbeddedAttachment(mediaEnvironment: "embedded",hasDisplayModes: true,attachmentEditor,+ histories,...getEmbedCodeView(el.closest(".include-note"))});@@ -156,6 +163,15 @@ export async function loadEmbeddedAttachment(await mountEmbedBox(el, box, $renderedContent);}+interface InlineEmbedOptions {+ /** Whether the content takes the focus once the box is mounted. */+ isFocused: boolean;+ /** The writes that the text note saves first. */+ saves?: InlineSourceSaves;+ /** Keeps the undo steps of the source on the undo stack of the text note. */+ histories?: EmbedHistories;+}+/*** Fills an embed box with what an embed that keeps its source in the note shows, through the* component of the `SourceEmbedType` of its language. The box has no title row.@@ -164,7 +180,7 @@ export async function loadInlineEmbed(source: InlineEmbedSource,$el: JQuery<HTMLElement>,boxSize: string | undefined,- { isFocused, saves }: { isFocused: boolean; saves?: InlineSourceSaves }+ { isFocused, saves, histories }: InlineEmbedOptions) {const type = getSourceEmbedTypeByLanguage(source.language);if (!type) return;@@ -176,7 +192,8 @@ export async function loadInlineEmbed(]);const $renderedContent = $('<div class="rendered-content">');const container = $('<div class="source-embed">').appendTo($renderedContent)[0];- await content_renderer.mountInteractiveWidget(h(InlineSourceEmbed, { source, component, saves }), container);+ await content_renderer.mountInteractiveWidget(+ h(InlineSourceEmbed, { source, component, saves, histories }), container);const box = h(ContentEmbed, {boxSize: boxSize ?? getEmbedBoxSize(el),diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.jsonindex d99684825e..560d53e402 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 <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a> 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 <span class=\"tn-icon bx bx-copy\"></span> button in the <a class=\"reference-link\" href=\"#root/_help_1P8QXI5edXNd\">Note buttons</a> area.</li><li>Go to a <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a> 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 <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 <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <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 <span class=\"tn-icon cke cke-trilium-ai\"></span> button in the <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 <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 <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 <a class=\"reference-link\" href=\"#root/_help_cRRrdZjgyhNc\">Privacy</a> 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 <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <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 <a class=\"reference-link\" href=\"#root/_help_VRoP0g1uHHc2\">In-editor AI assistant</a> for <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a> 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 <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> notes work too.</li><li>An empty note is ignored.</li><li><a class=\"reference-link\" href=\"#root/_help_MKmLg5x6xkor\">Archived Notes</a> 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 & \"render HTML\" note) or other more advanced use cases.</p><h2>Including a note</h2><p>In the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, look for the <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. For an included code or Markdown note and an embedded code or Markdown file, the <em>Box size</em> menu is the <span class=\"tn-icon bx bx-move-vertical\"></span> button, whose tooltip names the current size.</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 <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> (e.g. <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> will also display the results.</li><li><a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a> 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. Until then, a code note or file is shown read-only in the code editor, where its code can be selected and copied, and its blocks folded and unfolded with the arrows in its gutter. 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 stop editing.</li><li>While <em>Editable</em> is on, the arrow keys move the caret into the include and back out, as through the rest of the text. Entering from above or from the left puts the caret at the start of the include, and entering from below or from the right puts it at the end. A collapsed <em>Expandable</em> include is skipped.</li><li>While an included text note has the focus, the formatting toolbar applies to it. The notes it includes in turn stay read-only.</li><li>Code is edited in the same code editor as a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note, with its theme, indentation and line wrapping settings.</li><li>Typing <code>/</code> in the code lists the <a class=\"reference-link\" href=\"#root/_help_IEgsWp5hHH35\">Code Snippets</a> of its language, as in a code note.</li><li>The toolbar of an included code note or an embedded code file also has the language and indentation menus of the <a class=\"reference-link\" href=\"#root/_help_AlJ73vBCjWDw\">Status bar</a>, between <em>Editable</em> and the <span class=\"tn-icon bx bx-move-vertical\"></span> <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 <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.<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 <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> 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 <a class=\"reference-link\" href=\"#root/_help_SL5f1Auq7sVN\">Note types with split view</a>): <span class=\"tn-icon bx bx-code\"></span> <em>Source view</em>, <span class=\"tn-icon bx bxs-dock-left\"></span> <em>Split view</em> and <span class=\"tn-icon bx bx-show\"></span> <em>Preview</em>.</p><ul><li>To switch the view, press one of the three buttons in the title row of the include. In a note being edited, the toolbar of the include has the same buttons after <em>Editable</em>, and its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu has them as <em>Source view</em>, <em>Split view</em> and <em>Preview</em>.</li><li>Until a view is chosen, the include shows the <em>Preview</em>, and the <em>Split view</em> while <em>Editable</em> is on.</li><li>To edit the Markdown, turn on <em>Editable</em> (see <em>Editing an include in place</em> above). The source is edited in the code editor of a Markdown note, and the preview follows the changes as you type. While <em>Editable</em> is off, the source can be read and copied but not changed.</li><li>The source has the slash commands and the <code>@</code> and <code>[[</code> note links of a <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> note. A note created from the <code>@</code> or <code>[[</code> list goes under the included note, or for an embedded file under the note that includes it, and <code>/image</code> uploads the image to that same note.</li><li>The <em>Word wrap</em> and <em>Line numbers</em> submenus of the <em>More actions</em> menu change how the source shows, as for code (see <em>Editing an include in place</em> above).</li><li>As in a Markdown note, the preview scrolls along with the source and highlights the block where the cursor is, and <kbd>Ctrl</kbd>+<kbd>B</kbd>, <kbd>Ctrl</kbd>+<kbd>I</kbd>, <kbd>Ctrl</kbd>+<kbd>M</kbd> and <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd> format the selection.</li><li>In a note being edited, the view is saved with the include, so two includes of the same note can show different views. In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the view can be changed too, until the note is opened again.</li><li>While the source shows, the include has the height of its box size, or the height it was resized to. A <em>Full</em> include fits its content instead.</li><li><a class=\"reference-link\" href=\"#root/_help_McngOG2jbUWX\">Search in note</a> 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 <span class=\"tn-icon cke cke-plus\"></span> button in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> to reveal special inserable items and blocks such as symbols, Math expressions and separators.</p><h2>Bookmarks</h2><p>See the dedicated <a class=\"reference-link\" href=\"#root/_help_oSuaNgyyKnhu\">Anchors</a> 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 <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 <a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a> page.</p><h2>Math equations</h2><p>See the dedicated <a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a> 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 <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 <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</p><p>This feature is quite similar to the <a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a> note types and is meant as an alternative to it for simple diagrams. For more complex diagrams, use the <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a> 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 <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 <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 <span class=\"tn-icon cke cke-horizontal-line\"></span> button in the <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 <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 <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 & \"render HTML\" note) or other more advanced use cases.</p><h2>Including a note</h2><p>In the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, look for the <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. For an included code or Markdown note and an embedded code or Markdown file, the <em>Box size</em> menu is the <span class=\"tn-icon bx bx-move-vertical\"></span> button, whose tooltip names the current size.</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 <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> (e.g. <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> will also display the results.</li><li><a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a> 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. Until then, a code note or file is shown read-only in the code editor, where its code can be selected and copied, and its blocks folded and unfolded with the arrows in its gutter. 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 stop editing.</li><li>While <em>Editable</em> is on, the arrow keys move the caret into the include and back out, as through the rest of the text. Entering from above or from the left puts the caret at the start of the include, and entering from below or from the right puts it at the end. A collapsed <em>Expandable</em> include is skipped.</li><li>While an included text note has the focus, the formatting toolbar applies to it. The notes it includes in turn stay read-only.</li><li>Code is edited in the same code editor as a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note, with its theme, indentation and line wrapping settings.</li><li>Typing <code>/</code> in the code lists the <a class=\"reference-link\" href=\"#root/_help_IEgsWp5hHH35\">Code Snippets</a> of its language, as in a code note.</li><li>The toolbar of an included code note or an embedded code file also has the language and indentation menus of the <a class=\"reference-link\" href=\"#root/_help_AlJ73vBCjWDw\">Status bar</a>, between <em>Editable</em> and the <span class=\"tn-icon bx bx-move-vertical\"></span> <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 <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.<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>The changes made in the code editor of an include are part of the undo history of the note that includes it, together with the changes to its text, in the order they were made. This includes the source of included Markdown and of a <a href=\"#root/_help_CohkqWQC1iBv\">Mermaid diagram</a>.<ul><li><kbd>Ctrl</kbd>+<kbd>Z</kbd> undoes the last change of the note, and <kbd>Ctrl</kbd>+<kbd>Y</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd> redoes it, whether the caret is in the text or in an include, and also while <em>Editable</em> is off. The <span class=\"tn-icon cke cke-undo\"></span> <em>Undo</em> and <span class=\"tn-icon cke cke-redo\"></span> <em>Redo</em> buttons of the formatting toolbar do the same. With the Vim key bindings, <code>u</code> and <kbd>Ctrl</kbd>+<kbd>R</kbd> in an include do the same too.</li><li>The focus moves to the change that was undone or redone: into the code editor of the include, or back to the text.</li><li>Undoing a change of an included note saves the included note again. Once the included note has been changed elsewhere, for example in another tab, its earlier changes can no longer be undone from here, and undo skips them.</li><li>An included text note and a drawing canvas keep an undo history of their own.</li></ul></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 <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> 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 <a class=\"reference-link\" href=\"#root/_help_SL5f1Auq7sVN\">Note types with split view</a>): <span class=\"tn-icon bx bx-code\"></span> <em>Source view</em>, <span class=\"tn-icon bx bxs-dock-left\"></span> <em>Split view</em> and <span class=\"tn-icon bx bx-show\"></span> <em>Preview</em>.</p><ul><li>To switch the view, press one of the three buttons in the title row of the include. In a note being edited, the toolbar of the include has the same buttons after <em>Editable</em>, and its <span class=\"tn-icon cke cke-three-vertical-dots\"></span> <em>More actions</em> menu has them as <em>Source view</em>, <em>Split view</em> and <em>Preview</em>.</li><li>Until a view is chosen, the include shows the <em>Preview</em>, and the <em>Split view</em> while <em>Editable</em> is on.</li><li>To edit the Markdown, turn on <em>Editable</em> (see <em>Editing an include in place</em> above). The source is edited in the code editor of a Markdown note, and the preview follows the changes as you type. While <em>Editable</em> is off, the source can be read and copied but not changed.</li><li>The source has the slash commands and the <code>@</code> and <code>[[</code> note links of a <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> note. A note created from the <code>@</code> or <code>[[</code> list goes under the included note, or for an embedded file under the note that includes it, and <code>/image</code> uploads the image to that same note.</li><li>The <em>Word wrap</em> and <em>Line numbers</em> submenus of the <em>More actions</em> menu change how the source shows, as for code (see <em>Editing an include in place</em> above).</li><li>As in a Markdown note, the preview scrolls along with the source and highlights the block where the cursor is, and <kbd>Ctrl</kbd>+<kbd>B</kbd>, <kbd>Ctrl</kbd>+<kbd>I</kbd>, <kbd>Ctrl</kbd>+<kbd>M</kbd> and <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd> format the selection.</li><li>In a note being edited, the view is saved with the include, so two includes of the same note can show different views. In a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only note</a>, the view can be changed too, until the note is opened again.</li><li>While the source shows, the include has the height of its box size, or the height it was resized to. A <em>Full</em> include fits its content instead.</li><li><a class=\"reference-link\" href=\"#root/_help_McngOG2jbUWX\">Search in note</a> 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 <span class=\"tn-icon cke cke-plus\"></span> button in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> to reveal special inserable items and blocks such as symbols, Math expressions and separators.</p><h2>Bookmarks</h2><p>See the dedicated <a class=\"reference-link\" href=\"#root/_help_oSuaNgyyKnhu\">Anchors</a> 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 <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 <a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a> page.</p><h2>Math equations</h2><p>See the dedicated <a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a> 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 <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 <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</p><p>This feature is quite similar to the <a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a> note types and is meant as an alternative to it for simple diagrams. For more complex diagrams, use the <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a> 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 <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 <a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a>, which links to the Mermaid syntax.</li><li>The changes made to the source of a diagram are part of the undo history of the text note, in the order they were made. <kbd>Ctrl</kbd>+<kbd>Z</kbd> and <kbd>Ctrl</kbd>+<kbd>Y</kbd> undo and redo them from the source as well as from the text, as described in <em>Editing an include in place</em> in <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</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 <span class=\"tn-icon cke cke-horizontal-line\"></span> button in the <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 <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 <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> tools of the <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 <a class=\"reference-link\" href=\"#root/_help_gOKqSJgXLcIj\">Icon Packs</a> are also supported.<ul><li>For emojis, prefer the Emoji functionality from <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> which changes the icon.</li><li><span class=\"tn-icon bx bx-reflect-horizontal\"></span> 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 <a class=\"reference-link\" href=\"#root/_help_GnhlmrATVqcH\">Microsoft OneNote</a> importer also makes use of them for the <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 <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a> look for the <span class=\"tn-icon bx bx-plus\"></span> icon and then the <span class=\"tn-icon bx bx-sticker\"></span> icon.</li><li>Via <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 <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 <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\"><span class=\"tn-icon bx bx-star\"></span></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 <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, <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><br></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 <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 <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <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 <a class=\"reference-link\" href=\"#root/_help_MtPxeAWVAzMg\">Web Clipper</a> 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><title></code> and <code><meta name=\"description\"></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 <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.mdindex 45b4459d23..de74fc7cb2 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@@ -120,6 +120,11 @@ An included text note, an included code note and an embedded code file such as a* _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.+* The changes made in the code editor of an include are part of the undo history of the note that includes it, together with the changes to its text, in the order they were made. This includes the source of included Markdown and of a [Mermaid diagram](Insert%20buttons.md).+ * <kbd>Ctrl</kbd>+<kbd>Z</kbd> undoes the last change of the note, and <kbd>Ctrl</kbd>+<kbd>Y</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Z</kbd> redoes it, whether the caret is in the text or in an include, and also while _Editable_ is off. The <span class="tn-icon cke cke-undo"></span> _Undo_ and <span class="tn-icon cke cke-redo"></span> _Redo_ buttons of the formatting toolbar do the same. With the Vim key bindings, `u` and <kbd>Ctrl</kbd>+<kbd>R</kbd> in an include do the same too.+ * The focus moves to the change that was undone or redone: into the code editor of the include, or back to the text.+ * Undoing a change of an included note saves the included note again. Once the included note has been changed elsewhere, for example in another tab, its earlier changes can no longer be undone from here, and undo skips them.+ * An included text note and a drawing canvas keep an undo history of their own.* 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.* <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/Navigation/Search%20in%20note.md">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 _Editable_ is on.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.mdindex aa834f0ceb..23d5568f42 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@@ -58,7 +58,7 @@ A diagram shows in a box like the one of an included note, so it can be resized,* 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.* While the source shows, the <span class="tn-icon bx bx-help-circle"></span> _Mermaid syntax help_ button at the end of the toolbar opens the help on <a class="reference-link" href="../Mermaid%20Diagrams.md">Mermaid Diagrams</a>, which links to the Mermaid syntax.-* Undo in the text note also undoes the changes made to the source of a diagram.+* The changes made to the source of a diagram are part of the undo history of the text note, in the order they were made. <kbd>Ctrl</kbd>+<kbd>Z</kbd> and <kbd>Ctrl</kbd>+<kbd>Y</kbd> undo and redo them from the source as well as from the text, as described in _Editing an include in place_ in <a class="reference-link" href="Include%20Note.md">Include Note</a>.The source of the diagram stays in the note as a Mermaid code block, so the diagram is exported to Markdown as a `mermaid` code block that other applications can show.diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 4aeb225c60..dbd7392216 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -22,6 +22,10 @@ export type {ContentEmbedCodeView, ContentEmbedState} from "./plugins/content_embed/content_embed.js";export type { EmbedEdge } from "./plugins/content_embed/content_embed_caret.js";+export { default as EmbedHistory } from "./plugins/content_embed/embed_history.js";+export type {+ EmbedHistoryEntry, EmbedHistoryStep+} from "./plugins/content_embed/embed_history.js";export type { InlineEmbedSource } from "./plugins/content_embed/inline_source.js";export type { AttachmentLinkChange } from "./plugins/referencelink.js";export type { default as TriliumEmojiMention, EmojiSuggestion } from "./plugins/mention/emoji_mention.js";diff --git a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts b/packages/ckeditor5/src/plugins/content_embed/content_embed.tsindex 81bc3d22e8..6a8ff48dc4 100644--- a/packages/ckeditor5/src/plugins/content_embed/content_embed.ts+++ b/packages/ckeditor5/src/plugins/content_embed/content_embed.ts@@ -33,6 +33,7 @@ import { encodeBlockParameter, parseBlockRange } from '@triliumnext/commons';import { getAttachmentId, getNoteId } from '../referencelink.js';import ResizableWidgets, { SIZE_ATTRIBUTES } from '../resizable_widgets/resizable_widgets.js';import { restoreRendererFocusOnInput } from '../widget_utils.js';+import EmbedHistory from './embed_history.js';import ContentEmbedInlineSource, { isInlineSourceEmbed } from './inline_source.js';import './nested_editor_events.js';@@ -180,7 +181,7 @@ export default class ContentEmbed extends Plugin {declare public isSelectedEmbedInline: boolean;static get requires() {- return [ ContentEmbedEditing, ContentEmbedUI, ContentEmbedInlineSource ];+ return [ ContentEmbedEditing, ContentEmbedUI, ContentEmbedInlineSource, EmbedHistory ];}static get pluginName() {diff --git a/packages/ckeditor5/src/plugins/content_embed/embed_history.spec.ts b/packages/ckeditor5/src/plugins/content_embed/embed_history.spec.tsnew file mode 100644index 0000000000..3ba755145d--- /dev/null+++ b/packages/ckeditor5/src/plugins/content_embed/embed_history.spec.ts@@ -0,0 +1,139 @@+import {+ _getModelData as getModelData,+ type ClassicEditor,+ Essentials,+ Paragraph+} from "ckeditor5";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { createTestEditor } from "../../../test/editor-kit.js";+import EmbedHistory, { type EmbedHistoryStep } from "./embed_history.js";++describe("EmbedHistory", () => {+ let editor: ClassicEditor;+ let history: EmbedHistory;++ beforeEach(async () => {+ editor = await createTestEditor([ Essentials, Paragraph, EmbedHistory ]);+ history = editor.plugins.get(EmbedHistory);+ // Starts with an empty undo stack.+ editor.setData("<p></p>");+ });++ function createStep(isApplied = true) {+ return {+ undo: vi.fn<EmbedHistoryStep["undo"]>(() => isApplied),+ redo: vi.fn<EmbedHistoryStep["redo"]>(() => isApplied)+ };+ }++ function type(text: string) {+ editor.execute("insertText", { text });+ }++ function getText() {+ return getModelData(editor.model, { withoutSelection: true });+ }++ it("keeps a step on the undo stack without changing the data", () => {+ editor.setData("<p>a</p>");+ const step = createStep();+ const onDataChange = vi.fn();+ editor.model.document.on("change:data", onDataChange);++ history.push(step);+ expect(editor.getData()).toBe("<p>a</p>");+ expect(onDataChange).not.toHaveBeenCalled();++ for (let i = 1; i <= 2; i++) {+ editor.execute("undo");+ expect(step.undo).toHaveBeenCalledTimes(i);+ editor.execute("redo");+ expect(step.redo).toHaveBeenCalledTimes(i);+ }+ expect(editor.getData()).toBe("<p>a</p>");+ expect(onDataChange).not.toHaveBeenCalled();+ });++ it("keeps the order of the steps and the typing around them", () => {+ const step = createStep();+ type("a");+ history.push(step);+ type("b");++ editor.execute("undo");+ expect(getText()).toBe("<paragraph>a</paragraph>");+ expect(step.undo).not.toHaveBeenCalled();+ editor.execute("undo");+ expect(step.undo).toHaveBeenCalledOnce();+ expect(getText()).toBe("<paragraph>a</paragraph>");+ editor.execute("undo");+ expect(getText()).toBe("<paragraph></paragraph>");++ editor.execute("redo");+ editor.execute("redo");+ expect(step.redo).toHaveBeenCalledOnce();+ editor.execute("redo");+ expect(getText()).toBe("<paragraph>ab</paragraph>");++ // A new step clears the redo stack.+ editor.execute("undo");+ history.push(createStep());+ expect(editor.commands.get("redo")?.isEnabled).toBe(false);+ });++ it("tells whether a step is still the last change of the undo stack", () => {+ const first = history.push(createStep());+ expect(first.isLatest()).toBe(true);+ type("a");+ expect(first.isLatest()).toBe(false);++ const second = history.push(createStep());+ editor.execute("undo");+ expect(second.isLatest()).toBe(false);++ const third = history.push(createStep());+ editor.setData("<p>b</p>");+ expect(third.isLatest()).toBe(false);+ });++ it("skips a step that no longer applies, on to the next change", () => {+ const step = createStep(false);+ type("a");+ history.push(step);++ editor.execute("undo");+ expect(step.undo).toHaveBeenCalledOnce();+ expect(getText()).toBe("<paragraph></paragraph>");++ editor.execute("redo");+ expect(getText()).toBe("<paragraph>a</paragraph>");+ editor.execute("redo");+ expect(step.redo).toHaveBeenCalledOnce();+ expect(editor.commands.get("redo")?.isEnabled).toBe(false);+ });++ it("focuses the text editor when an embed undoes or redoes a change of the text", () => {+ const focus = vi.spyOn(editor.editing.view, "focus");+ const step = createStep();+ type("a");+ history.push(step);++ history.undo();+ expect(step.undo).toHaveBeenCalledOnce();+ expect(focus).not.toHaveBeenCalled();+ history.undo();+ expect(getText()).toBe("<paragraph></paragraph>");+ expect(focus).toHaveBeenCalledOnce();+ // Nothing left to undo.+ history.undo();+ expect(focus).toHaveBeenCalledOnce();++ history.redo();+ expect(getText()).toBe("<paragraph>a</paragraph>");+ expect(focus).toHaveBeenCalledTimes(2);+ history.redo();+ expect(step.redo).toHaveBeenCalledOnce();+ expect(focus).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/ckeditor5/src/plugins/content_embed/embed_history.ts b/packages/ckeditor5/src/plugins/content_embed/embed_history.tsnew file mode 100644index 0000000000..da081ecc0b--- /dev/null+++ b/packages/ckeditor5/src/plugins/content_embed/embed_history.ts@@ -0,0 +1,155 @@+import {+ type Batch,+ type ModelWriter,+ Plugin,+ UndoEditing,+ type UndoRedoBaseCommandRevertEvent+} from "ckeditor5";++/** A change made in the content of an embed, kept as a step of the text editor's undo. */+export interface EmbedHistoryStep {+ /** Reverts the change. Returns `false` when the content changed since, to skip the step. */+ undo(): boolean;+ /** Makes the change again. Returns `false` when the content changed since. */+ redo(): boolean;+}++/** A step that {@link EmbedHistory.push} added to the undo stack. */+export interface EmbedHistoryEntry {+ /** Whether no other change entered the undo stack after the step, so it can still grow. */+ isLatest(): boolean;+}++type HistoryCommandName = "undo" | "redo";++const STEP_MARKER = "embedHistoryStep";++/**+ * Keeps the changes made in the content of embeds, such as the code editor of an included note,+ * on the undo stack of the text editor. A step is a batch that only adds or removes a marker that+ * does not affect the data. Undoing or redoing that batch undoes or redoes the step.+ */+export default class EmbedHistory extends Plugin {+ private readonly steps = new WeakMap<Batch, EmbedHistoryStep>();+ private lastBatch: Batch | null = null;+ private isStepApplied = false;+ private isStepSkipped = false;++ static get requires() {+ return [ UndoEditing ] as const;+ }++ static get pluginName() {+ return "EmbedHistory" as const;+ }++ init() {+ const editor = this.editor;++ this.listenTo(editor.model, "applyOperation", (_evt, [ operation ]) => {+ if (operation.isDocumentOperation && operation.batch?.isUndoable) {+ this.lastBatch = operation.batch;+ }+ });+ this.listenTo(editor.data, "set", () => {+ this.lastBatch = null;+ });++ for (const name of [ "undo", "redo" ] as const) {+ const command = editor.commands.get(name);+ /* v8 ignore next 3 -- `UndoEditing` registers both commands */+ if (!command) {+ continue;+ }++ this.listenTo<UndoRedoBaseCommandRevertEvent>(command, "revert",+ (_evt, reverted, reverting) => this.revert(name, reverted, reverting));+ // Runs after the command, to go on to the next item of the stack.+ this.listenTo(command, "execute", () => {+ if (this.isStepSkipped) {+ this.isStepSkipped = false;+ if (command.isEnabled) {+ editor.execute(name);+ }+ }+ }, { priority: "low" });+ }+ }++ /** Adds `step` on top of the undo stack, and clears the redo stack. */+ push(step: EmbedHistoryStep): EmbedHistoryEntry {+ const model = this.editor.model;+ const batch = model.createBatch();+ this.steps.set(batch, step);+ model.enqueueChange(batch, (writer) => toggleStepMarker(writer));++ return { isLatest: () => this.lastBatch === batch };+ }++ /**+ * Undoes the last change of the note, for the content of an embed. The text editor takes the+ * focus when the change was one of its own.+ */+ undo() {+ this.runFromEmbed("undo");+ }++ /** Redoes the last undone change of the note, for the content of an embed. */+ redo() {+ this.runFromEmbed("redo");+ }++ private runFromEmbed(name: HistoryCommandName) {+ const editor = this.editor;+ if (!editor.commands.get(name)?.isEnabled) {+ return;+ }++ this.isStepApplied = false;+ editor.execute(name);+ if (!this.isStepApplied) {+ editor.editing.view.focus();+ }+ }++ private revert(name: HistoryCommandName, reverted: Batch, reverting: Batch) {+ const step = this.steps.get(reverted);+ if (!step) {+ return;+ }++ this.steps.set(reverting, step);+ const isApplied = name === "undo" ? step.undo() : step.redo();+ if (isApplied) {+ this.isStepApplied = true;+ } else {+ this.isStepSkipped = true;+ }+ }+}++/** Adds the step marker, or removes it, at the start of the document. */+function toggleStepMarker(writer: ModelWriter) {+ const model = writer.model;+ if (model.markers.has(STEP_MARKER)) {+ writer.removeMarker(STEP_MARKER);+ return;+ }++ const root = model.document.getRoot();+ /* v8 ignore next 3 -- a text editor always has its main root */+ if (!root) {+ return;+ }+ writer.addMarker(STEP_MARKER, {+ range: writer.createRange(writer.createPositionAt(root, 0)),+ usingOperation: true,+ affectsData: false+ });+}++declare module "ckeditor5" {+ interface PluginsMap {+ [ EmbedHistory.pluginName ]: EmbedHistory;+ }+}diff --git a/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts b/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.tsindex f96d7374e7..026ba1b8f6 100644--- a/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts+++ b/packages/ckeditor5/src/plugins/content_embed/inline_source.spec.ts@@ -142,7 +142,7 @@ describe("ContentEmbedInlineSource", () => {expect(model).not.toContain("javascript");});- it("has the host render the source, and writes its changes as steps of the undo", () => {+ it("has the host render the source, and writes its changes outside the undo stack", () => {editor.setData(`<pre><code class="language-mermaid">graph TD;</code></pre>`);expect(loadInlineEmbed).toHaveBeenCalledOnce();@@ -159,14 +159,18 @@ describe("ContentEmbedInlineSource", () => {source.subscribe(listener);source.setSource("graph LR;");expect(getEmbed().getAttribute("source")).toBe("graph LR;");+ expect(source.getSource()).toBe("graph LR;");expect(listener).toHaveBeenCalledOnce();-- editor.execute("undo");- expect(getEmbed().getAttribute("source")).toBe("graph TD;");- expect(source.getSource()).toBe("graph TD;");- expect(listener).toHaveBeenCalledTimes(2);+ // The host keeps the undo steps of the source in `EmbedHistory`.+ expect(editor.commands.get("undo")?.isEnabled).toBe(false);// Writing the source does not draw the embed again, which would remount its editor.expect(loadInlineEmbed).toHaveBeenCalledOnce();++ // A box drawn again gets the same source, which keys the undo steps of its editor.+ editor.model.change((writer) => writer.setSelection(getEmbed(), "on"));+ editor.execute(BOX_SIZE_COMMAND_NAME, { value: "full" });+ expect(loadInlineEmbed).toHaveBeenCalledTimes(2);+ expect(getLoadedSource(1)).toBe(source);});it("ignores a write of the same source, and stops calling a listener that unsubscribed", () => {diff --git a/packages/ckeditor5/src/plugins/content_embed/inline_source.ts b/packages/ckeditor5/src/plugins/content_embed/inline_source.tsindex 47e9529ffe..21cb92a06c 100644--- a/packages/ckeditor5/src/plugins/content_embed/inline_source.ts+++ b/packages/ckeditor5/src/plugins/content_embed/inline_source.ts@@ -27,13 +27,13 @@ export const INSERT_INLINE_EMBED_COMMAND = 'insertInlineEmbed';/*** The source of an embed that keeps its content in the note, as the host reads and changes it.- * The editor's undo and other changes to the source reach the host through `subscribe()`.+ * Changes to the source made outside the host reach it through `subscribe()`.*/export interface InlineEmbedSource {/** The language that the source is written in, such as `mermaid`. */readonly language: string;getSource(): string;- /** Replaces the source, as one step of the editor's undo. */+ /** Replaces the source. The host keeps the undo steps of its changes in `EmbedHistory`. */setSource( source: string ): void;/** Calls `callback` when the source changes, until the returned function is called. */subscribe( callback: () => void ): () => void;@@ -69,6 +69,8 @@ const SIZE_PROPERTIES = [export default class ContentEmbedInlineSource extends Plugin {/** The listeners of each embed's source, by embed. */private readonly listeners = new WeakMap<ModelElement, Set<() => void>>();+ /** The source of each embed, the same object each time the embed renders. */+ private readonly sources = new WeakMap<ModelElement, InlineEmbedSource>();/** The embeds inserted by {@link INSERT_INLINE_EMBED_COMMAND}, whose content takes the focus. */private readonly focusedEmbeds = new WeakSet<ModelElement>();@@ -111,6 +113,15 @@ export default class ContentEmbedInlineSource extends Plugin {}private getSource( embed: ModelElement ): InlineEmbedSource {+ let source = this.sources.get( embed );+ if ( !source ) {+ source = this.createSource( embed );+ this.sources.set( embed, source );+ }+ return source;+ }++ private createSource( embed: ModelElement ): InlineEmbedSource {const editor = this.editor;const listeners = this.listeners;@@ -123,7 +134,9 @@ export default class ContentEmbedInlineSource extends Plugin {|| root.rootName === '$graveyard' || embed.getAttribute( 'source' ) === source ) {return;}- editor.model.change( writer => writer.setAttribute( 'source', source, embed ) );+ editor.model.enqueueChange( { isUndoable: false }, writer => {+ writer.setAttribute( 'source', source, embed );+ } );},subscribe: callback => {let callbacks = listeners.get( embed );diff --git a/packages/codemirror/src/index.spec.ts b/packages/codemirror/src/index.spec.tsindex d26c664262..e1b43b3991 100644--- a/packages/codemirror/src/index.spec.ts+++ b/packages/codemirror/src/index.spec.ts@@ -3,6 +3,7 @@ import { undo } from "@codemirror/commands";import { indentUnit } from "@codemirror/language";import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";import { EditorView, showTooltip, type ViewUpdate } from "@codemirror/view";+import { CodeMirror as VimEditor, getCM } from "@replit/codemirror-vim";import { afterEach, describe, expect, it, vi } from "vitest";vi.mock("./type_completion/index.js", async (importOriginal) => {@@ -11,7 +12,9 @@ vi.mock("./type_completion/index.js", async (importOriginal) => {});import { hostedCompletion } from "./extensions/hosted_completion.js";-import CodeMirror, { type EditorConfig, getThemeById, SCRIPT_MIME_BACKEND } from "./index.js";+import CodeMirror, {+ type EditorConfig, getThemeById, type HostHistory, SCRIPT_MIME_BACKEND, SharedHistory+} from "./index.js";import { buildTypeCompletion } from "./type_completion/index.js";let editor: CodeMirror | undefined;@@ -427,6 +430,102 @@ describe("CodeMirror", () => {editor = build({ readOnly: true });expect(() => editor?.clearHistory()).not.toThrow();});++ it("loads content outside the undo history", () => {+ editor = build();+ editor.loadText("loaded");+ expect(editor.getText()).toBe("loaded");+ expect(undo(editor)).toBe(false);+ });+ });++ describe("shared history", () => {+ it("records into the shared history and leaves its own, until it is detached", () => {+ editor = build();+ const { host, history } = createSharedHistory();+ editor.setText("own");++ editor.setSharedHistory(history);+ editor.setSharedHistory(history);+ editor.setText("shared");+ expect(host.push).toHaveBeenCalledOnce();+ expect(undo(editor)).toBe(false);+ editor.clearHistory();+ expect(pressKey(editor, "z", { ctrlKey: true })).toBe(true);+ expect(host.undo).toHaveBeenCalledOnce();++ // A read-only editor still runs the shared history.+ editor.setReadOnly(true);+ expect(pressKey(editor, "z", { ctrlKey: true })).toBe(true);+ expect(host.undo).toHaveBeenCalledTimes(2);+ editor.setReadOnly(false);++ const detach = vi.spyOn(history, "detach");+ editor.setSharedHistory(null);+ expect(detach).toHaveBeenCalledWith(editor);+ expect(editor.runSharedHistory("undo")).toBe(false);+ editor.setText("own again");+ expect(undo(editor)).toBe(true);+ expect(host.push).toHaveBeenCalledOnce();+ });++ it("runs the shared history from the undo and redo keys and input events", () => {+ editor = build();+ const { host, history } = createSharedHistory();+ editor.setSharedHistory(history);+ const outside = vi.fn();+ editor.dom.parentElement?.addEventListener("keydown", outside);++ expect(pressKey(editor, "z", { ctrlKey: true })).toBe(true);+ expect(pressKey(editor, "y", { ctrlKey: true })).toBe(true);+ const redoKey = { ctrlKey: true, shiftKey: true, keyCode: 90 };+ expect(pressKey(editor, "Z", redoKey)).toBe(true);+ expect(host.undo).toHaveBeenCalledOnce();+ expect(host.redo).toHaveBeenCalledTimes(2);+ expect(outside).not.toHaveBeenCalled();++ for (const inputType of [ "historyUndo", "historyRedo", "insertText" ]) {+ editor.contentDOM.dispatchEvent(+ new InputEvent("beforeinput", { inputType, bubbles: true, cancelable: true }));+ }+ expect(host.undo).toHaveBeenCalledTimes(2);+ expect(host.redo).toHaveBeenCalledTimes(3);+ });++ it("runs the shared history from Vim, and the editor's own without one", () => {+ editor = build({ vimKeybindings: true });+ const cm = getCM(editor);+ expect(cm).not.toBeNull();+ if (!cm) return;+ editor.setText("typed");++ VimEditor.commands.undo(cm);+ expect(editor.getText()).toBe("");+ VimEditor.commands.redo(cm);+ expect(editor.getText()).toBe("typed");++ const { host, history } = createSharedHistory();+ editor.setSharedHistory(history);+ VimEditor.commands.undo(cm);+ VimEditor.commands.redo(cm);+ expect(host.undo).toHaveBeenCalledOnce();+ expect(host.redo).toHaveBeenCalledOnce();+ expect(editor.getText()).toBe("typed");+ });++ it("leaves the shared history as it is destroyed, with the document it shows", () => {+ editor = build();+ const { host, history, write } = createSharedHistory();+ editor.setSharedHistory(history);+ editor.setText("a");+ const dispatch = vi.spyOn(editor, "dispatch");+ editor.destroy();+ editor = undefined;++ host.undo();+ expect(dispatch).not.toHaveBeenCalled();+ expect(write).toHaveBeenCalledWith("");+ });});describe("cursor placement", () => {@@ -824,6 +923,27 @@ function build(config: Partial<EditorConfig> = {}): CodeMirror {return new CodeMirror({ parent, ...config });}+/** A shared history over a host that undoes the last step it was given. */+function createSharedHistory() {+ const steps: Parameters<HostHistory["push"]>[0][] = [];+ const host = {+ push: vi.fn((step: Parameters<HostHistory["push"]>[0]) => {+ steps.push(step);+ return { isLatest: () => false };+ }),+ undo: vi.fn(() => steps.pop()?.undo()),+ redo: vi.fn()+ };+ const write = vi.fn();+ return { host, history: new SharedHistory(host, write), write };+}++/** Presses `key` in `view`. Returns whether the editor handled it. */+function pressKey(view: CodeMirror, key: string, init: KeyboardEventInit = {}) {+ return !view.contentDOM.dispatchEvent(+ new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...init }));+}+/** The `.cm-gutters` rules of `view`, the one that takes effect first. */function getGutterRules(view: CodeMirror) {return view.state.facet(EditorView.styleModule)diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.tsindex 924dea7f24..4603bf34b9 100644--- a/packages/codemirror/src/index.ts+++ b/packages/codemirror/src/index.ts@@ -2,22 +2,26 @@ import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";import { EditorView, highlightActiveLine, keymap, lineNumbers, placeholder, tooltips, ViewPlugin, ViewUpdate, type EditorViewConfig, KeyBinding } from "@codemirror/view";import { defaultHighlightStyle, StreamLanguage, syntaxHighlighting, indentUnit, bracketMatching, foldGutter, codeFolding } from "@codemirror/language";import {- Compartment, EditorSelection, EditorState, Prec, StateEffect, type Extension+ Compartment, EditorSelection, EditorState, Prec, StateEffect, Transaction, type Extension} from "@codemirror/state";import { highlightSelectionMatches } from "@codemirror/search";import { autocompletion, completionStatus, type CompletionSource } from "@codemirror/autocomplete";-import { vim } from "@replit/codemirror-vim";+import { CodeMirror as VimEditor, vim } from "@replit/codemirror-vim";import { indentationMarkers } from "@replit/codemirror-indentation-markers";import byMimeType, { MIME_ALIASES } from "./syntax_highlighting.js";import smartIndentWithTab from "./extensions/custom_tab.js";import type { ThemeDefinition } from "./color_themes.js";import { createSearchHighlighter, SearchHighlighter, searchMatchHighlightTheme } from "./find_replace.js";import { isHostedCompletionShown } from "./extensions/hosted_completion.js";+import type SharedHistory from "./shared_history.js";import {buildTypeCompletion, type ScriptApiContext, type TypeCompleter} from "./type_completion/index.js";export { default as ColorThemes, type ThemeDefinition, type ThemeVariant, getThemeById } from "./color_themes.js";+export {+ default as SharedHistory, type HostHistory, type HostHistoryStep+} from "./shared_history.js";export {isScriptMime, type ScriptApiContext, SCRIPT_MIME_BACKEND, SCRIPT_MIME_FRONTEND,type TypeCompletionEntry@@ -113,6 +117,7 @@ export default class CodeMirror extends EditorView {private typeCompletionCompartment: Compartment;private completionSourceCompartment: Compartment;private searchPlugin?: SearchHighlighter | null;+ private sharedHistory: SharedHistory | null = null;private namedCompartments = new Map<string, Compartment>();/** Named completion sources aggregated into the editor's single autocompletion. */private completionSources = new Map<string, CompletionSource>();@@ -218,12 +223,49 @@ export default class CodeMirror extends EditorView {}#onDocumentUpdated(v: ViewUpdate) {+ for (const tr of v.transactions) {+ this.sharedHistory?.record(tr);+ }if (v.docChanged) {this.config.onContentChanged?.();}for (const listener of this.#updateListeners) listener(v);}+ /**+ * Keeps the undo history in `history`, which the editor shares with its host, such as the text+ * note that embeds it. With `null`, the editor keeps a history of its own.+ */+ setSharedHistory(history: SharedHistory | null) {+ if (history === this.sharedHistory) return;++ this.sharedHistory?.detach(this);+ this.sharedHistory = history;+ history?.attach(this);+ this.dispatch({+ effects: [ this.historyCompartment.reconfigure(this.buildHistory(this.state.readOnly)) ]+ });+ }++ /** Undoes or redoes in the shared history. Returns `false` when the editor has none. */+ runSharedHistory(name: "undo" | "redo") {+ if (!this.sharedHistory) return false;++ this.sharedHistory.host[name]();+ return true;+ }++ override destroy() {+ this.sharedHistory?.detach(this);+ this.sharedHistory = null;+ super.destroy();+ }++ private buildHistory(isReadOnly: boolean): Extension {+ if (this.sharedHistory) return sharedHistoryKeys(this);+ return isReadOnly ? [] : history();+ }+#updateListeners: Array<(v: ViewUpdate) => void> = [];/**@@ -254,12 +296,22 @@ export default class CodeMirror extends EditorView {}setText(content: string) {+ this.replaceText(content, false);+ }++ /** Replaces the content with content loaded from elsewhere, outside the undo history. */+ loadText(content: string) {+ this.replaceText(content, true);+ }++ private replaceText(content: string, isLoad: boolean) {const transaction = this.state.update({changes: {from: 0,to: this.state.doc.length,insert: content || "",- }+ },+ annotations: Transaction.addToHistory.of(!isLoad)});// Dispatching a full-document replacement maps the viewport onto the whole new document.// A visible editor's next measure shrinks it back, but an editor inside a display:none@@ -299,7 +351,7 @@ export default class CodeMirror extends EditorView {this.editabilityCompartment.reconfigure(buildEditability(isReadOnly, this.config.placeholder)),- this.historyCompartment.reconfigure(isReadOnly ? [] : history())+ this.historyCompartment.reconfigure(this.buildHistory(isReadOnly))]});}@@ -354,7 +406,7 @@ export default class CodeMirror extends EditorView {* Clears the history of undo/redo. Generally useful when changing to a new document.*/clearHistory() {- if (this.state.readOnly) {+ if (this.state.readOnly || this.sharedHistory) {return;}@@ -627,6 +679,43 @@ export default class CodeMirror extends EditorView {}}+// Vim's `u` and `Ctrl-R` run these commands, which use the shared history of an editor first.+for (const name of [ "undo", "redo" ] as const) {+ const run = VimEditor.commands[name];+ VimEditor.commands[name] = (cm) => {+ if (!(cm.cm6 instanceof CodeMirror && cm.cm6.runSharedHistory(name))) {+ run(cm);+ }+ };+}++const HISTORY_INPUT_TYPES: Record<string, "undo" | "redo" | undefined> = {+ historyUndo: "undo",+ historyRedo: "redo"+};++/** The undo and redo keys and input events of `view`, which run its shared history. */+function sharedHistoryKeys(view: CodeMirror): Extension {+ const undo = () => view.runSharedHistory("undo");+ const redo = () => view.runSharedHistory("redo");+ return [+ Prec.high(keymap.of([+ { key: "Mod-z", run: undo, stopPropagation: true },+ { key: "Mod-y", run: redo, stopPropagation: true },+ { key: "Mod-Shift-z", run: redo, stopPropagation: true }+ ])),+ EditorView.domEventHandlers({+ beforeinput(event) {+ const name = HISTORY_INPUT_TYPES[event.inputType];+ if (!name) return false;++ event.preventDefault();+ return view.runSharedHistory(name);+ }+ })+ ];+}+/** Identifies a type-completion build by its MIME type and the context flags that are set. */function typeCompletionKey(mime: string, context: ScriptApiContext) {const flags = Object.entries(context)diff --git a/packages/codemirror/src/shared_history.spec.ts b/packages/codemirror/src/shared_history.spec.tsnew file mode 100644index 0000000000..d5cdb966a6--- /dev/null+++ b/packages/codemirror/src/shared_history.spec.ts@@ -0,0 +1,231 @@+import { EditorSelection, Transaction, type TransactionSpec } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import SharedHistory, { type HostHistory, type HostHistoryStep } from "./shared_history.js";++let views: EditorView[] = [];+let now = 0;++beforeEach(() => {+ now = 1_000;+ vi.spyOn(Date, "now").mockImplementation(() => now);+});++afterEach(() => {+ for (const view of views) {+ view.destroy();+ }+ views = [];+ vi.restoreAllMocks();+});++describe("SharedHistory", () => {+ it("groups typing into one step, as the history of CodeMirror does", () => {+ const host = createHost();+ const { view } = setUp(host, "");++ type(view, 0, "a");+ now += 100;+ view.dispatch({});+ type(view, 1, "b");+ expect(host.done).toHaveLength(1);++ // A pause starts a new step.+ now += 600;+ type(view, 2, "c");+ expect(host.done).toHaveLength(2);++ // So do a change away from the last one, a paste and a selection move.+ type(view, 0, "x");+ type(view, 1, "y", "input.paste");+ view.dispatch({ selection: EditorSelection.cursor(2) });+ type(view, 2, "z");+ expect(host.done).toHaveLength(5);++ // And a change of the host made in between.+ host.pushOther();+ type(view, 1, "w");+ expect(host.done).toHaveLength(7);++ // Composition joins the step before it.+ type(view, 2, "q", "input.type.compose");+ now += 600;+ type(view, 3, "r", "input.type.compose");+ expect(host.done).toHaveLength(7);++ // A change that the user did not type does not.+ view.dispatch({ changes: { from: 4, insert: "s" } });+ expect(host.done).toHaveLength(8);+ });++ it("starts a new step for each editor of the document", () => {+ const host = createHost();+ const { view, history } = setUp(host, "");+ const other = createView("", (tr) => history.record(tr));+ history.attach(other);++ type(view, 0, "a");+ type(other, 0, "b");+ expect(host.done).toHaveLength(2);+ });++ it("undoes and redoes a step in the editor that shows it, with its selection", async () => {+ const host = createHost();+ const { view, write, history } = setUp(host, "start");+ const focus = vi.spyOn(view, "focus");+ const otherView = createView("unrelated");+ history.attach(otherView);++ view.dispatch({ selection: EditorSelection.cursor(5) });+ type(view, 5, "!");+ type(view, 6, "?");+ host.undo();+ expect(view.state.doc.toString()).toBe("start");+ expect(view.state.selection.main.head).toBe(5);+ expect(otherView.state.doc.toString()).toBe("unrelated");+ expect(write).toHaveBeenLastCalledWith("start");+ // The undo is not a step of its own.+ expect(host.done).toHaveLength(0);+ await Promise.resolve();+ expect(focus).toHaveBeenCalledOnce();++ host.redo();+ expect(view.state.doc.toString()).toBe("start!?");+ expect(view.state.selection.main.head).toBe(7);+ expect(write).toHaveBeenLastCalledWith("start!?");+ expect(host.done).toHaveLength(1);+ });++ it("changes the document through `write` while no editor shows it", () => {+ const host = createHost();+ const { view, write, history } = setUp(host, "a");++ type(view, 1, "b");+ history.detach(view);+ host.undo();+ expect(write).toHaveBeenLastCalledWith("a");++ // An editor that shows the document again takes the redo.+ const remounted = createView("a");+ history.attach(remounted);+ host.redo();+ expect(remounted.state.doc.toString()).toBe("ab");+ expect(write).toHaveBeenLastCalledWith("ab");+ });++ it("skips a step once the document changed outside the history", () => {+ const host = createHost();+ const { view, write, history } = setUp(host, "a");++ type(view, 1, "b");+ load(view, "changed elsewhere");+ expect(host.done).toHaveLength(1);+ expect(host.undo()).toBe(false);+ expect(view.state.doc.toString()).toBe("changed elsewhere");+ expect(write).not.toHaveBeenCalled();++ // Also while no editor shows the document.+ type(view, 0, "x");+ history.detach(view);+ load(view, "changed again");+ history.attach(view);+ history.detach(view);+ expect(host.undo()).toBe(false);++ // A step whose document was never shown does not apply either.+ const orphan = new SharedHistory(host, write);+ const unattached = createView("");+ orphan.record(unattached.state.update({ changes: { from: 0, insert: "a" } }));+ expect(host.undo()).toBe(false);+ });++ it("leaves loaded content out of the history, and ends the step before it", () => {+ const host = createHost();+ const { view } = setUp(host, "");++ type(view, 0, "a");+ load(view, "a");+ expect(host.done).toHaveLength(1);+ type(view, 1, "b");+ expect(host.done).toHaveLength(2);+ });+});++interface FakeHost extends HostHistory {+ done: HostHistoryStep[];+ undone: HostHistoryStep[];+ undo(): boolean;+ redo(): boolean;+ /** Pushes a change of the host itself. */+ pushOther(): void;+}++/** A host whose stack runs one step per undo or redo. */+function createHost(): FakeHost {+ const done: HostHistoryStep[] = [];+ const undone: HostHistoryStep[] = [];+ return {+ done,+ undone,+ push(step) {+ done.push(step);+ undone.length = 0;+ return { isLatest: () => done.at(-1) === step && !undone.length };+ },+ undo() {+ const step = done.pop();+ undone.push(...(step ? [ step ] : []));+ return !!step?.undo();+ },+ redo() {+ const step = undone.pop();+ done.push(...(step ? [ step ] : []));+ return !!step?.redo();+ },+ pushOther() {+ done.push({ undo: () => true, redo: () => true });+ }+ };+}++function setUp(host: HostHistory, doc: string) {+ const write = vi.fn();+ const history = new SharedHistory(host, write);+ const view = createView(doc, (tr) => history.record(tr));+ history.attach(view);+ return { view, write, history };+}++function createView(doc: string, record?: (tr: Transaction) => void) {+ const parent = document.createElement("div");+ document.body.append(parent);+ const view = new EditorView({+ doc,+ parent,+ dispatchTransactions: (transactions, target) => {+ for (const tr of transactions) {+ record?.(tr);+ }+ target.update(transactions);+ }+ });+ views.push(view);+ return view;+}++function type(view: EditorView, at: number, text: string, userEvent = "input.type") {+ view.dispatch({+ changes: { from: at, insert: text },+ selection: EditorSelection.cursor(at + text.length),+ userEvent+ });+}++function load(view: EditorView, text: string) {+ const spec: TransactionSpec = {+ changes: { from: 0, to: view.state.doc.length, insert: text },+ annotations: Transaction.addToHistory.of(false)+ };+ view.dispatch(spec);+}diff --git a/packages/codemirror/src/shared_history.ts b/packages/codemirror/src/shared_history.tsnew file mode 100644index 0000000000..edcb25d1f2--- /dev/null+++ b/packages/codemirror/src/shared_history.ts@@ -0,0 +1,145 @@+import { type ChangeSet, type EditorSelection, type Text, Transaction } from "@codemirror/state";+import type { EditorView } from "@codemirror/view";++/** A change of a document, kept as a step of the host's undo stack. */+export interface HostHistoryStep {+ /** Reverts the change. Returns `false` when the document changed since. */+ undo(): boolean;+ /** Makes the change again. Returns `false` when the document changed since. */+ redo(): boolean;+}++/** The undo stack of the host that shows the editors, such as the text note that embeds them. */+export interface HostHistory {+ /** Adds `step` on top of the stack. `isLatest()` tells whether the step can still grow. */+ push(step: HostHistoryStep): { isLatest(): boolean };+ undo(): void;+ redo(): void;+}++interface Step {+ before: Text;+ after: Text;+ changes: ChangeSet;+ selectionBefore: EditorSelection;+ selectionAfter: EditorSelection;+}++interface OpenStep {+ step: Step;+ entry: { isLatest(): boolean };+ time: number;+}++/** The longest pause between two changes of one step, in milliseconds, as in `history()`. */+const NEW_STEP_DELAY = 500;+/** The changes that join the step before them, as in `history()`. */+const JOINABLE_EVENT = /^(input\.type|delete)($|\.)/;++/**+ * The undo history of a document, such as an embedded note, kept on the undo stack of `host`. Each+ * editor of the document records into it. While no editor shows the document, a step changes it+ * through `write`.+ */+export default class SharedHistory {+ private readonly views = new Set<EditorView>();+ /** The document of the last editor detached, for steps applied while no editor shows it. */+ private doc: Text | undefined;+ private open: OpenStep | undefined;++ constructor(readonly host: HostHistory, private readonly write: (text: string) => void) {}++ attach(view: EditorView) {+ this.views.add(view);+ }++ detach(view: EditorView) {+ this.views.delete(view);+ this.doc = view.state.doc;+ this.open = undefined;+ }++ /** Records a transaction of an attached editor. */+ record(tr: Transaction) {+ if (!tr.docChanged) {+ if (tr.selection) {+ this.open = undefined;+ }+ return;+ }++ const time = Date.now();+ if (tr.annotation(Transaction.addToHistory) === false) {+ this.open = undefined;+ } else if (this.open && canJoin(this.open, tr, time)) {+ const { step } = this.open;+ step.changes = step.changes.compose(tr.changes);+ step.after = tr.newDoc;+ step.selectionAfter = tr.newSelection;+ this.open.time = time;+ } else {+ const step: Step = {+ before: tr.startState.doc,+ after: tr.newDoc,+ changes: tr.changes,+ selectionBefore: tr.startState.selection,+ selectionAfter: tr.newSelection+ };+ const entry = this.host.push({+ undo: () => this.apply(step, true),+ redo: () => this.apply(step, false)+ });+ this.open = { step, entry, time };+ }+ }++ private apply(step: Step, isUndo: boolean) {+ const from = isUndo ? step.after : step.before;+ const to = isUndo ? step.before : step.after;+ const view = [ ...this.views ].find((candidate) => candidate.state.doc.eq(from));+ if (view) {+ view.dispatch({+ changes: isUndo ? step.changes.invert(step.before) : step.changes,+ selection: isUndo ? step.selectionBefore : step.selectionAfter,+ scrollIntoView: true,+ annotations: Transaction.addToHistory.of(false)+ });+ // Deferred until after the Undo button of the toolbar focuses the text editor.+ queueMicrotask(() => view.focus());+ } else if (this.views.size || !this.doc?.eq(from)) {+ return false;+ }++ this.open = undefined;+ this.doc = to;+ this.write(to.toString());+ return true;+ }+}++/** Whether `tr` continues the typing of `open`, as `history()` groups its events. */+function canJoin(open: OpenStep, tr: Transaction, time: number) {+ const userEvent = tr.annotation(Transaction.userEvent);+ return open.entry.isLatest()+ && open.step.after === tr.startState.doc+ && (userEvent === "input.type.compose" || (+ !!userEvent && JOINABLE_EVENT.test(userEvent)+ && time - open.time < NEW_STEP_DELAY+ && isAdjacent(open.step.changes, tr.changes)+ ));+}++/** Whether the ranges that `next` changes touch those that `previous` produced. */+function isAdjacent(previous: ChangeSet, next: ChangeSet) {+ const ranges: number[] = [];+ previous.iterChangedRanges((_fromA, _toA, fromB, toB) => ranges.push(fromB, toB));+ let isTouching = false;+ next.iterChangedRanges((fromA, toA) => {+ for (let i = 0; i < ranges.length; i += 2) {+ if (toA >= ranges[i] && fromA <= ranges[i + 1]) {+ isTouching = true;+ }+ }+ });+ return isTouching;+}