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/link: add title mirroring support for heading links
Adorian Doranccc299415db7
diff --git a/apps/client/src/services/block_excerpts.spec.ts b/apps/client/src/services/block_excerpts.spec.tsindex 08fe1ebb6f..07ccc4c136 100644--- a/apps/client/src/services/block_excerpts.spec.ts+++ b/apps/client/src/services/block_excerpts.spec.ts@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest";import { buildNote } from "../test/easy-froca";import {- getBlockExcerpt, getCachedBlockReferenceLabel, loadBlockReferenceLabel+ getBlockExcerpt, getBlockReferenceLabel, getCachedBlockReferenceLabel, loadBlockReferenceLabel} from "./block_excerpts.js";vi.mock("./i18n.js", () => ({ t: (key: string) => key }));@@ -10,7 +10,7 @@ vi.mock("./i18n.js", () => ({ t: (key: string) => key }));const CONTENT = "<p data-trilium-block-id=\"a\">First block\n text</p>"+ "<ul><li><p data-trilium-block-id=\"b\">Second</p></li></ul>"+ "<figure class=\"image\" data-trilium-block-id=\"img\"><img src=\"x.png\"></figure>";-const FIRST_LABEL = { text: "First block text", isBroken: false };+const FIRST_LABEL = { text: "First block text", isBroken: false, isHeading: false };describe("loadBlockReferenceLabel", () => {it("labels blocks by their text, and a missing block as broken", async () => {@@ -19,15 +19,18 @@ describe("loadBlockReferenceLabel", () => {expect(await loadBlockReferenceLabel(note, "a")).toEqual(FIRST_LABEL);expect(await loadBlockReferenceLabel(note, "a:b")).toEqual({text: "First block text … Second",- isBroken: false+ isBroken: false,+ isHeading: false});expect(await loadBlockReferenceLabel(note, "img")).toEqual({text: "block_reference.untitled",- isBroken: false+ isBroken: false,+ isHeading: false});expect(await loadBlockReferenceLabel(note, "a:gone")).toEqual({text: "block_reference.broken",- isBroken: true+ isBroken: true,+ isHeading: false});});@@ -79,6 +82,49 @@ describe("loadBlockReferenceLabel", () => {});});+describe("getBlockReferenceLabel", () => {+ it("labels the blocks of a content as it is, and a heading by all of its text", () => {+ const root = document.createElement("div");+ const long = "A heading " + "word ".repeat(20).trimEnd();+ root.innerHTML = `<h2 data-trilium-block-id="h">${long}</h2>`+ + "<p data-trilium-block-id=\"p\">Text</p><h3 data-trilium-block-id=\"empty\"></h3>";++ expect(getBlockReferenceLabel(root, "h")).toEqual({+ text: long, isBroken: false, isHeading: true+ });+ expect(getBlockReferenceLabel(root, "empty")).toEqual({+ text: "block_reference.untitled", isBroken: false, isHeading: true+ });+ // A range reads in document order, however its ends are written.+ const range = getBlockReferenceLabel(root, "p:h");+ expect(range).toEqual(getBlockReferenceLabel(root, "h:p"));+ expect(range).toMatchObject({ isBroken: false, isHeading: false });+ expect(range.text.endsWith("… … Text")).toBe(true);+ for (const block of [ "gone", "h:gone", "" ]) {+ expect(getBlockReferenceLabel(root, block)).toEqual({+ text: "block_reference.broken", isBroken: true, isHeading: false+ });+ }++ root.querySelector("h2")?.append(" renamed");+ expect(getBlockReferenceLabel(root, "h").text).toBe(`${long} renamed`);+ });++ it("leaves out the labels of block references, which can repeat the text itself", () => {+ const root = document.createElement("div");+ root.innerHTML = "<h2 data-trilium-block-id=\"a\">See "+ + "<a class=\"reference-link\" href=\"#root/n?block=a\">See Other</a> and "+ + "<a class=\"reference-link\" href=\"#root/n?block=b\">Other</a> in "+ + "<a class=\"reference-link\" href=\"#root/m\">Note</a></h2>"+ + "<h2 data-trilium-block-id=\"b\">Other "+ + "<a class=\"reference-link\" href=\"#root/n?block=a\">See and in Note</a></h2>";++ expect(getBlockReferenceLabel(root, "a").text).toBe("See and in Note");+ expect(getBlockReferenceLabel(root, "b").text).toBe("Other");+ expect(root.querySelectorAll("a")).toHaveLength(4);+ });+});+describe("getBlockExcerpt", () => {it("shortens a long text, sharing the length between the two ends of a range", () => {const long = document.createElement("p");diff --git a/apps/client/src/services/block_excerpts.ts b/apps/client/src/services/block_excerpts.tsindex 01de14ed3b..f070dd8a29 100644--- a/apps/client/src/services/block_excerpts.ts+++ b/apps/client/src/services/block_excerpts.ts@@ -1,17 +1,21 @@import "./block_reference.css";-import { resolveBlockReference } from "@triliumnext/commons";+import { BLOCK_ID_ATTRIBUTE, parseBlockRange } from "@triliumnext/commons";import type FNote from "../entities/fnote.js";import { t } from "./i18n.js";const MAX_CACHED_NOTES = 20;const EXCERPT_LENGTH = 60;+const HEADING_TAG = /^H[1-6]$/;+const BLOCK_LINK = "a.reference-link[href*=\"block=\"]";/** What a reference link shows for the blocks it points at. */export interface BlockReferenceLabel {text: string;isBroken: boolean;+ /** Whether the blocks are one heading, whose whole text the label holds. */+ isHeading: boolean;}interface CachedContent {@@ -28,7 +32,7 @@ const cache = new Map<string, CachedContent>();*/export async function loadBlockReferenceLabel(note: FNote, block: string) {const content = await loadContent(note);- return content ? getLabel(content, block) : null;+ return content ? getBlockReferenceLabel(content, block) : null;}/** The label of {@link loadBlockReferenceLabel}, if the content of `note` is loaded already. */@@ -38,7 +42,7 @@ export function getCachedBlockReferenceLabel(note: FNote, block: string) {return null;}- return getLabel(cached.content, block);+ return getBlockReferenceLabel(cached.content, block);}/** A short text of the blocks from `start` to `end`. */@@ -52,13 +56,46 @@ export function getBlockExcerpt(start: Element, end: Element) {return texts.join(" … ") || t("block_reference.untitled");}-function getLabel(content: Document, block: string): BlockReferenceLabel {- const { start, end } = resolveBlockReference<Element>(content.body, block);- if (!start || !end) {- return { text: t("block_reference.broken"), isBroken: true };+/**+ * The label of a reference to `block`, a `block` link parameter, of the blocks under `root`, such+ * as the content of an editor.+ */+export function getBlockReferenceLabel(root: ParentNode, block: string): BlockReferenceLabel {+ const blocks = findBlocks(root, block);+ if (!blocks) {+ return { text: t("block_reference.broken"), isBroken: true, isHeading: false };+ }++ const [ start, end ] = blocks;+ if (start === end && HEADING_TAG.test(start.tagName)) {+ const text = getText(start) || t("block_reference.untitled");+ return { text, isBroken: false, isHeading: true };+ }++ return { text: getBlockExcerpt(start, end), isBroken: false, isHeading: false };+}++/**+ * The first and the last block that `block` points at under `root`, in document order, as+ * `resolveBlockReference()` finds them. A selector reaches the blocks with an id without a walk+ * through every node.+ */+function findBlocks(root: ParentNode, block: string): [ Element, Element ] | null {+ const range = parseBlockRange(block);+ if (!range) {+ return null;+ }++ const blocks = [ ...root.querySelectorAll(`[${BLOCK_ID_ATTRIBUTE}]`) ];+ const indexOf = (id: string) =>+ blocks.findIndex((element) => element.getAttribute(BLOCK_ID_ATTRIBUTE) === id);+ const start = indexOf(range.startId);+ const end = indexOf(range.endId);+ if (start < 0 || end < 0) {+ return null;}- return { text: getBlockExcerpt(start, end), isBroken: false };+ return [ blocks[Math.min(start, end)], blocks[Math.max(start, end)] ];}function loadContent(note: FNote) {@@ -97,12 +134,23 @@ function loadContent(note: FNote) {return entry.loaded;}-/** The text of `element`; a tab is named by its title. */+/**+ * The text of `element`; a tab is named by its title. The labels of the block references in it are+ * left out, since they hold the text of a block, which can be this one.+ */function getText(element: Element) {const title = element.matches(".trilium-tab")? element.querySelector(":scope > .trilium-tab-title"): null;- return ((title ?? element).textContent ?? "").replace(/\s+/g, " ").trim();+ let source = title ?? element;+ if (source.querySelector(BLOCK_LINK)) {+ source = source.cloneNode(true) as Element;+ for (const link of source.querySelectorAll(BLOCK_LINK)) {+ link.remove();+ }+ }++ return (source.textContent ?? "").replace(/\s+/g, " ").trim();}function truncate(text: string, maxLength: number) {diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.tsindex 4183280539..7c811d5882 100644--- a/apps/client/src/services/link.spec.ts+++ b/apps/client/src/services/link.spec.ts@@ -1316,6 +1316,32 @@ describe("block references", () => {expect($elsewhere.find("small").text()).toBe("First block");});+ it("labels a reference to blocks of the content it is in from that content", async () => {+ const note = buildNote({+ title: "Source", content: "<h2 data-trilium-block-id=\"h\">Saved</h2>" + content+ });+ const live = document.createElement("div");+ live.innerHTML = "<h2 data-trilium-block-id=\"h\">Live heading</h2>" + content;+ const href = (block: string) => `#root/${note.noteId}?block=${block}`;+ const $heading = $("<span>");+ const $paragraph = $("<span>");+ const $saved = $("<span>");++ await linkService.loadReferenceLinkTitle($heading, href("h"), undefined, undefined, live);+ await linkService.loadReferenceLinkTitle($paragraph, href("b1"), undefined, undefined, live);+ await linkService.loadReferenceLinkTitle($saved, href("h"), note.noteId);++ // A heading reads as its text alone, without an icon.+ expect($heading.html()).toBe("Live heading");+ expect($paragraph.text()).toBe("First block");+ expect($paragraph.children("span.tn-icon.bx.bx-paragraph")).toHaveLength(1);+ expect($saved.html()).toBe("Saved");+ expect(linkService.getReferenceLinkTitleSync(href("h"), "Stored", live))+ .toBe("Live heading");+ expect(linkService.getReferenceLinkTitleSync(href("gone"), "Stored", live))+ .toBe("block_reference.broken");+ });+it("adds no label to a reference to the blocks of a note that cannot be read", async () => {const note = buildNote({ title: "Code", type: "code", content });const $el = $("<span>");diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.tsindex 972079015d..2af403f405 100644--- a/apps/client/src/services/link.ts+++ b/apps/client/src/services/link.ts@@ -5,7 +5,9 @@ import {import appContext, { type NoteCommandData } from "../components/app_context.js";import { openInCurrentNoteContext } from "../components/note_context.js";import linkContextMenuService from "../menus/link_context_menu.js";-import { getCachedBlockReferenceLabel, loadBlockReferenceLabel } from "./block_excerpts.js";+import {+ getBlockReferenceLabel, getCachedBlockReferenceLabel, loadBlockReferenceLabel+} from "./block_excerpts.js";import cssClassManager from "./css_class_manager.js";import froca from "./froca.js";import { t } from "./i18n.js";@@ -723,14 +725,16 @@ function linkContextMenu(e: PointerEvent) {/*** Fills `$el` with the label of the reference link to `href`. A link to blocks of `hostNoteId`, the- * note the link is in, shows only the text of the blocks. A link to a note that does not exist- * shows `storedTitle`, the title the content holds for it.+ * note the link is in, shows only the text of the blocks, read from `content` when it holds them,+ * as an editor does. A link to a note that does not exist shows `storedTitle`, the title the+ * content holds for it.*/async function loadReferenceLinkTitle($el: JQuery<HTMLElement>,href: string | null | undefined = null,hostNoteId?: string,- storedTitle?: string+ storedTitle?: string,+ content?: ParentNode | null) {const $link = $el[0].tagName === "A" ? $el : $el.find("a");@@ -752,12 +756,15 @@ async function loadReferenceLinkTitle(const subjectId = viewScope?.card || noteId;const note = subjectId ? await froca.getNote(subjectId, true) : null;- if (viewScope?.block && note && noteId === hostNoteId) {- const label = await loadBlockReferenceLabel(note, viewScope.block);+ if (viewScope?.block && note && (content || noteId === hostNoteId)) {+ const label = content+ ? getBlockReferenceLabel(content, viewScope.block)+ : await loadBlockReferenceLabel(note, viewScope.block);if (label) {- $el.text(label.text)- .toggleClass("block-reference-broken", label.isBroken)- .prepend($("<span>").addClass("tn-icon bx bx-paragraph"));+ $el.text(label.text).toggleClass("block-reference-broken", label.isBroken);+ if (!label.isHeading) {+ $el.prepend($("<span>").addClass("tn-icon bx bx-paragraph"));+ }return;}}@@ -840,14 +847,21 @@ async function getReferenceLinkTitle(href: string) {/*** The label of the reference link to `href`, from the notes already in froca. A link to a note that- * is not there gets `storedTitle`, the title the content holds for it.+ * is not there gets `storedTitle`, the title the content holds for it. A link to blocks of+ * `content`, the content the link is in, gets their text.*/-function getReferenceLinkTitleSync(href: string, storedTitle?: string) {+function getReferenceLinkTitleSync(+ href: string, storedTitle?: string, content?: ParentNode | null+) {const { noteId, viewScope } = parseNavigationStateFromUrl(href);if (!noteId) {return storedTitle || MISSING_NOTE_TITLE;}+ if (content && viewScope?.block) {+ return getBlockReferenceLabel(content, viewScope.block).text;+ }+const note = froca.getNoteFromCache(viewScope?.card || noteId);if (!note) {return storedTitle || MISSING_NOTE_TITLE;diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex b21530e300..2ab5954e6f 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -81,7 +81,8 @@"anchors": "Headings & anchors","target_anchor": "Anchors","headings": "Headings",- "no_headings_or_anchors": "This note doesn't contain any headings or anchors."+ "no_headings_or_anchors": "This note doesn't contain any headings or anchors.",+ "title_from_heading": "If not set, will always reflect the heading's text"},"branch_prefix": {"edit_branch_prefix": "Edit branch prefix",diff --git a/apps/client/src/widgets/dialogs/edit_link.spec.tsx b/apps/client/src/widgets/dialogs/edit_link.spec.tsxindex 3d55fd06d7..b8229926a9 100644--- a/apps/client/src/widgets/dialogs/edit_link.spec.tsx+++ b/apps/client/src/widgets/dialogs/edit_link.spec.tsx@@ -565,7 +565,7 @@ describe("EditLinkDialog", () => {.toBe("add_link.no_headings_or_anchors");});- it("lists the headings as a tree above the anchors, and links one by its title", async () => {+ it("lists the headings as a tree above the anchors, and links one mirroring it", async () => {const intro = createHeading("Intro", 2);const linux = createHeading("Linux", 4);await open({@@ -596,7 +596,7 @@ describe("EditLinkDialog", () => {await act(async () => headingRows()[2]?.click());expect(checkedHeading()).toBe("Linux");- expect(field("text")?.placeholder).toBe("Linux");+ expect(field("text")?.placeholder).toBe("add_link.title_from_heading");// A heading and an anchor are one choice.await act(async () => anchorRows()[0]?.click());expect([ checkedHeading(), checkedAnchor() ]).toStrictEqual([ undefined, "top" ]);@@ -605,14 +605,23 @@ describe("EditLinkDialog", () => {expect(linux.createLinkPath).not.toHaveBeenCalled();await submit();expect(linux.createLinkPath).toHaveBeenCalledOnce();- expect(addLink).toHaveBeenLastCalledWith("root/note?block=Linux", "Linux");+ expect(addLink).toHaveBeenLastCalledWith("root/note?block=Linux", null);await open({ headings: [ intro ] });await act(async () => choice()[2]?.click());await act(async () => headingRows()[0]?.click());- await type(field("text"), "Read the intro");+ await type(field("text"), " Read the intro ");await submit();expect(addLink).toHaveBeenLastCalledWith("root/note?block=Intro", "Read the intro");++ // A selection keeps its text, and a selection without one takes the heading's.+ for (const [ text, title ] of [ [ "some words", "some words" ], [ "", "Intro" ] ]) {+ await open({ text, hasSelection: true, headings: [ intro ] });+ await act(async () => choice()[2]?.click());+ await act(async () => headingRows()[0]?.click());+ await submit();+ expect(addLink).toHaveBeenLastCalledWith("root/note?block=Intro", title);+ }});it("opens an edited heading link on its heading, scrolled to the middle of the list", async () => {@@ -644,6 +653,12 @@ describe("EditLinkDialog", () => {expect(container.querySelector(".edit-link-targets")?.scrollTop).toBe(300);await submit();expect(addLink).toHaveBeenLastCalledWith("root/note?block=Usage", "See usage");++ // A link that mirrors its heading opens with no title, and keeps mirroring it.+ await open({ anchors: [], headings: [ usage ], currentHeading: usage });+ expect(field("text")?.value).toBe("");+ await submit();+ expect(addLink).toHaveBeenLastCalledWith("root/note?block=Usage", null);});});diff --git a/apps/client/src/widgets/dialogs/edit_link.tsx b/apps/client/src/widgets/dialogs/edit_link.tsxindex 3086355866..a9ea19c95c 100644--- a/apps/client/src/widgets/dialogs/edit_link.tsx+++ b/apps/client/src/widgets/dialogs/edit_link.tsx@@ -406,11 +406,15 @@ function useEditLinkForm(opts: EditLinkOpts | undefined) {if (!opts) return;if (target === "anchor") {- // A link without a text of its own reads as the heading or the anchor's name. `true`- // keeps the href of an anchor link as it is.if (heading) {- opts.addLink(heading.createLinkPath(), linkTitle.trim() || heading.title);+ // `null` makes a reference link, which shows the current text of the heading.+ const title = opts.hasSelection+ ? opts.text || heading.title+ : linkTitle.trim() || null;+ opts.addLink(heading.createLinkPath(), title);} else if (anchor) {+ // A link without a text of its own reads as the anchor's name. `true` keeps the+ // href of an anchor link as it is.opts.addLink(`#${anchor}`, linkTitle.trim() || anchor, true);}return;@@ -459,7 +463,9 @@ function useEditLinkForm(opts: EditLinkOpts | undefined) {/** The text the link reads as while the title field is empty. */function getTitlePlaceholder() {- if (target === "anchor") return heading?.title || anchor || undefined;+ if (target === "anchor") {+ return heading ? t("add_link.title_from_heading") : anchor || undefined;+ }if (target === "note") return t("add_link.title_from_note");return isPreview ? t("add_link.page_title"): suggestion?.externalLink ?? t("add_link.title_from_url");diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts b/apps/client/src/widgets/type_widgets/text/EditableText.spec.tsindex 286499cc1e..9f6b31618b 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts@@ -573,13 +573,17 @@ describe("getEditLinkOpts", () => {expect(opts.currentHeading).toBe(opts.headings?.[0]);expect(opts.currentLink).toBeUndefined();- // A reference link keeps the Note page, as does a link to another note, to a range of- // blocks or to a block that is not a heading.- for (const [ href, isReference ] of [- [ "#root/abc?block=a", true ], [ "#root/def?block=a", false ],- [ "#root/abc?block=a:b", false ], [ "#root/abc?block=b", false ], [ "#root/abc", false ]- ] as const) {- const other = edit(href, isReference);+ // A reference link has no title of its own, so that it keeps showing the heading.+ const reference = edit("#root/abc?block=a", true);+ expect(reference.currentHeading).toBe(reference.headings?.[0]);+ expect(reference.currentTitle).toBeUndefined();++ // A link to another note, to a range of blocks or to a block that is not a heading keeps+ // the Note page.+ for (const href of [+ "#root/def?block=a", "#root/abc?block=a:b", "#root/abc?block=b", "#root/abc"+ ]) {+ const other = edit(href);expect(other.currentHeading).toBeUndefined();expect(other.currentLink?.notePath).toMatch(/^root\/(abc|def)/);}diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex e99eee39de..bafc6d8787 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -614,8 +614,7 @@ export function getEditLinkOpts(const headings = notePath ? getLinkHeadings(api, notePath) : undefined;const currentLink = api.getCurrentLink();if (currentLink) {- // A reference link opens on the Note page, which keeps it mirroring the heading.- const currentHeading = notePath && headings && !currentLink.isReference+ const currentHeading = notePath && headings? findLinkedHeading(currentLink.href, headings, notePath): undefined;return {diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex 4f87b37ab3..ee537a348f 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -547,16 +547,17 @@ describe("CK config - tables", () => {let noteId = "n1";const referenceLink = (await buildConfig(baseOpts({ getNoteId: () => noteId }))).referenceLink;const element = document.createElement("span");+ const content = document.createElement("div");- referenceLink?.renderTitle?.(element, "#root/n2", "Stored");+ referenceLink?.renderTitle?.(element, "#root/n2", "Stored", content);noteId = "n3";referenceLink?.renderTitle?.(element, "#root/n2");expect(referenceLink?.getTitle).toBe(linkService.getReferenceLinkTitle);expect(referenceLink?.getTitleSync).toBe(linkService.getReferenceLinkTitleSync);expect(loadTitle.mock.calls.map(([ $el, ...rest ]) => [ $el[0], ...rest ])).toEqual([- [ element, "#root/n2", "n1", "Stored" ],- [ element, "#root/n2", "n3", undefined ]+ [ element, "#root/n2", "n1", "Stored", content ],+ [ element, "#root/n2", "n3", undefined, undefined ]]);});diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 00d7396d2e..3d0359715e 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -253,8 +253,10 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfireferenceLink: {getTitle: linkService.getReferenceLinkTitle,getTitleSync: linkService.getReferenceLinkTitleSync,- renderTitle: (element, href, storedTitle) => {- void linkService.loadReferenceLinkTitle($(element), href, opts.getNoteId?.(), storedTitle);+ renderTitle: (element, href, storedTitle, content) => {+ void linkService.loadReferenceLinkTitle(+ $(element), href, opts.getNoteId?.(), storedTitle, content+ );},fixLink: (storedTitle, fix) => {void opts.triggerHostCommand?.("showEditLinkDialog", {diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.jsonindex 2fc1d9774c..66e99775c3 100644--- a/apps/server/src/assets/help/help_content.json+++ b/apps/server/src/assets/help/help_content.json@@ -118,7 +118,7 @@"_help_oSuaNgyyKnhu": "<aside class=\"admonition note\"><p>This feature used to be called <em>Bookmarks</em> (as it is the official name in the editor we are using), but in order not to collide with the concept of <a class=\"reference-link\" href=\"#root/_help_u3YFHC9tQlpm\">Bookmarks</a>, we have renamed it to <em>Anchors.</em></p></aside><p>Anchors allows creating <a href=\"#root/_help_QEAPj01N5f7w\">links</a> to a certain part of a note, such as referencing a particular heading or section within a note.</p><p>This feature was introduced in TriliumNext v0.94.0 and augmented in v0.103.0 to support linking across notes.</p><h2>Interaction</h2><ul><li>To create an anchor:<ul><li>Place the cursor at the desired position where to place the anchor.</li><li>Look for the <span class=\"tn-icon bx bx-plus\"></span> button in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, and then press the <span class=\"tn-icon cke cke-bookmark\"></span> button.</li><li>Alternatively, use <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a> and look for <em>anchor</em>.</li></ul></li><li>To place a link to an anchor in the same note:<ul><li>Place the cursor at the desired position of the link, or select the text to turn into a link.</li><li>Press <kbd>Ctrl</kbd>+<kbd>K</kbd> or the <span class=\"tn-icon cke cke-link\"></span> button in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, then select <em>Headings & anchors</em> at the top of the <a href=\"#root/_help_QEAPj01N5f7w\"><em>Add link</em> dialog</a>.</li><li>Under <em>Anchors</em>, click the desired anchor to check it. Optionally, type a <em>Link title</em>; without one, the link shows the anchor's name.</li><li>Press <kbd>Enter</kbd> or <em>Add link</em> to confirm.</li></ul></li><li>Clicking a link to an anchor of the same note scrolls to the anchor and briefly highlights the block that holds it, while editing as well as in read-only notes and on shared pages.</li><li>To change a link to an anchor, place the cursor inside it and press <kbd>Ctrl</kbd>+<kbd>K</kbd>. Since v0.107.0, the <em>Edit link</em> dialog opens on <em>Headings & anchors</em>, with the linked anchor checked.</li></ul><aside class=\"admonition tip\"><p>To link to a heading of the same note, no anchor is needed: pick the heading under <em>Headings</em> in the same dialog. See <a href=\"#root/_help_klC3ilXa9kUE\">Linking to a heading</a> for details.</p></aside><h2>Linking across notes</h2><p>Trilium v0.103.0 introduces cross-note Anchors, which makes it possible to create <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> which point to a specific anchor in that document.</p><h3>Compatibility with documents from previous versions</h3><p>For notes created prior to Trilium v0.103.0, you might notice that the Anchors might not be identified. This limitation is intentional in order not to have to re-process all the notes, looking for anchors.</p><p>To fix this, simply go that note and make any change (e.g. inserting a space), this will trigger the recalculation of the links.</p><h3>Linking to anchors through the <em>Add link</em> dialog</h3><ol><li>Create an anchor in the target note using the same process as described above.</li><li>In another note, press <kbd>Ctrl</kbd>+<kbd>L</kbd> to insert an internal link. Select the target note containing Anchors.</li><li>If the target note contains Anchors, a section will appear underneath the note selector with the list of Anchors.</li><li>Add the link normally.</li></ol><p>Clicking on a reference link pointing to an anchor will automatically scroll to the desired section.</p><h3>Linking to anchors through the bookmark toolbar</h3><ol><li>Create an anchor in the target note using the same process as described above.</li><li>Click on the anchor to reveal the anchor's floating toolbar.</li><li>Click on the <span class=\"tn-icon cke cke-trilium-copy\"></span> <em>Copy anchor reference link</em> button.</li><li>Go to the note where to insert the link and press <kbd>Ctrl</kbd>+<kbd>V</kbd>.</li></ol><aside class=\"admonition note\"><p>Use this method only to insert <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> between two documents. To link to an anchor on the same note, use the <em>Add link</em> dialog (<kbd>Ctrl</kbd>+<kbd>K</kbd>) and select <em>Headings & anchors</em> at its top instead.</p></aside>","_help_oI7GoyilXXAr": "<h2>Automatic replacements</h2><p>As you type in a text note, certain character sequences are replaced with the typographic symbol they represent. Typing <code>(c)</code> gives you <code>©</code>, <code>...</code> gives you <code>…</code>, and <code>\"quote\"</code> gives you <code>“quote”</code>.</p><p>These replacements are not applied inside code blocks or inline code, and pasted text is never affected, only text you type. If you have pasted a code snippet, or written one inside a code block, its characters are left exactly as they are.</p><h3>Undoing a replacement</h3><p>Once an automatic replacement takes place, it can be undone by:</p><ul><li>Pressing <kbd>Backspace</kbd> immediately after a replacement undoes it and restores what you typed.<ul><li>Note that this consumes the undo, so a further <kbd>Ctrl</kbd>+<kbd>Z</kbd> might delete your typed text.</li><li>Pressing <kbd>Space</kbd> or changing the cursor position disables this functionality.</li></ul></li><li>Pressing <kbd>Ctrl</kbd>+<kbd>Z</kbd>, which works even after pressing space.</li></ul><h3>Replacement groups & configuration</h3><p>Each group can be turned off in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text notes</em> → <em>Automatic replacements</em>.</p><figure class=\"table\"><table><thead><tr><th>Group</th><th>What it replaces</th></tr></thead><tbody><tr><td>Punctuation</td><td><code>...</code> with an ellipsis (<code>…</code>), and <code>--</code> and <code>---</code> <em>surrounded by spaces</em> with an en dash (<code>–</code>) and an em dash (<code>—</code>)</td></tr><tr><td>Mathematical symbols</td><td>fractions such as <code>1/2</code> with <code>½</code>, and the operators <code><=</code>, <code>>=</code>, <code>!=</code>, <code><-</code> and <code>-></code> with <code>≤</code>, <code>≥</code>, <code>≠</code>, <code>←</code> and <code>→</code></td></tr><tr><td>Copyright and trademark</td><td><code>(c)</code>, <code>(r)</code> and <code>(tm)</code> with <code>©</code>, <code>®</code> and <code>™</code></td></tr><tr><td>Quotation marks</td><td>straight quotes with typographic ones — see below</td></tr></tbody></table></figure><h2>Quotation marks</h2><p>Quotation marks are configured separately from the rest, with one setting for the <strong>double</strong> quote key and one for the <strong>single</strong> quote key, because which pair belongs on which key differs between conventions: British typography traditionally sets a quotation in <code>‘…’</code> where American sets it in <code>“…”</code>.</p><p>Each offers:</p><ul><li><em>Based on the note's content language</em> (the default) — English gives <code>“quote”</code>, German <code>„quote“</code>, French <code>« quote »</code>, Japanese <code>「quote」</code>. See <a class=\"reference-link\" href=\"#root/_help_veGu4faJErEM\">Content language & Right-to-left support</a> for how a note's language is decided.</li><li><em>Disabled,</em> straight quotes stay straight.</li><li>A specific pair_:_ <code>“…”</code>, <code>‘…’</code>, <code>„…“</code>, <code>„…”</code>, <code>«…»</code>, <code>« … »</code>, <code>‹…›</code>, <code>「…」</code>, <code>『…』</code>. Choosing one applies it to every note, regardless of its content language.</li></ul><h2>Custom replacements</h2><p>You can add your own under <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text notes</em> → <em>Automatic replacements</em> → <em>Custom replacements</em>. Type the text to replace and the replacement, then press Enter. Existing ones are shown as chips and removed with the × on each.</p><p>A custom replacement is applied when the text is typed as a whole word and followed by a space, so longer words that begin with it are left alone — a <code>TN</code> replacement does not rewrite the end of <code>BTN</code>, and <code>TNT</code> can still be typed.</p><p>Capitalization follows what you type, unless the replacement has capitals of its own:</p><figure class=\"table\"><table><thead><tr><th><strong>Replacement you defined</strong></th><th><strong>You type</strong></th><th><strong>You get</strong></th></tr></thead><tbody><tr><td><code>teh</code> → <code>the</code></td><td><code>teh</code> / <code>Teh</code> / <code>TEH</code></td><td><code>the</code> / <code>The</code> / <code>THE</code></td></tr><tr><td><code>TN</code> → <code>Trilium Notes</code></td><td><code>TN</code> or <code>tn</code></td><td><code>Trilium Notes</code> (unchanged, it has capitals)</td></tr></tbody></table></figure><p>Of note:</p><ul><li>The text to replace is matched literally; it is not a pattern.</li><li>Typing a \"text to replace\" that already exists in the list of replacements will update the existing one instead. It's not possible to have multiple replacements for the same text.</li><li>The same “text to replace” with different capitalization (e.g. <code>TN</code> and <code>tn</code> co-existing) doesn't work because it would interfere with the capitalization rules above.</li></ul><h2>Characters that only look replaced (ligatures)</h2><p>If you see <code>!=</code> displayed as <code>≠</code> or <code>-></code> as <code>→</code> inside a code block, that is not a replacement since replacements never run there (unless a code block is applied to an existing text). It is a <em>font ligature</em>: the default monospace font draws certain character pairs as a single symbol. The underlying text is unchanged, and copying it out gives you back <code>!=</code> and <code>-></code>.</p><p>This can be turned off with <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a><em>→ Appearance → Fonts → Programming ligatures.</em></p>","_help_NwBbFdNZ9h7O": "<h2>Block quotes</h2><p>As the name suggests, block quotes can be useful to cite one or more paragraphs.</p><p>To create a block quote, press <span class=\"tn-icon cke cke-quote\"></span> from the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>. It's also possible to type <kbd>></kbd>, followed by a space to create one (but only if the cursor is at the beginning of a line).</p><p>Inside the quote block, other block items can be inserted such as tables, images, or even other block quotes or admonitions.</p><h2>Admonitions</h2><p>Admonitions are a way to highlight information to the reader. Other names for it include <em>call-outs</em> and <em>info/warning/alert boxes</em>.</p><figure class=\"image image-style-align-center\"><img style=\"aspect-ratio:959/547;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Block%20quotes%20%26%20admonitions_image.png\" width=\"959\" height=\"547\"></figure><p>From a functional point of view, admonitions act very similarly to a block quote, just with different styling. This includes the ability to insert other elements in it such as headings, tables, images, etc.</p><h3>Inserting a new admonition</h3><p>In the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>:</p><p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Block%20quotes%20%26%20admonitions_image.png\"></p><p>It's possible to insert an admonition simply by typing:</p><ul><li><code>!!! note</code></li><li><code>!!! tip</code></li><li><code>!!! important</code></li><li><code>!!! caution</code></li><li><code>!!! warning</code></li></ul><p>In addition to that, it's also possible to type <code>!!!</code> followed by any text, case in which a default admonition type will appear (note) with the entered text inside it.</p><h3>Interaction</h3><p>By design, admonitions act very similar to block quotes.</p><ul><li>Selecting a text and pressing the admonition button will turn that text into an admonition.</li><li>If selecting multiple admonitions, pressing the admonition button will automatically merge them into one.</li></ul><p>Inside an admonition:</p><ul><li>Pressing <kbd>Backspace</kbd> while the admonition is empty will remove it.</li><li>Pressing <kbd>Enter</kbd> will start a new paragraph. Pressing it twice will exit out of the admonition.</li><li>Headings and other block content including tables can be inserted inside the admonition.</li></ul><h3>Types of admonitions</h3><p>There are currently five types of admonitions: <em>Note</em>, <em>Tip</em>, <em>Important</em>, <em>Caution</em>, <em>Warning</em>.</p><p>These types were inspired by GitHub's support for this feature and there are currently no plans for adjusting it or allowing the user to customize them.</p><h3>Markdown support</h3><p>See <a class=\"reference-link\" href=\"#root/_help_rJ9grSgoExl9\">Supported syntax</a>.</p>",- "_help_klC3ilXa9kUE": "<p>Block references are <a href=\"#root/_help_QEAPj01N5f7w\">links</a> to a block of a text note, such as a paragraph, a heading, a list item or a table, or to a range of consecutive blocks. A block reference can be pasted in another note as a link, or turned into an <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a> that shows only the referenced blocks.</p><h2>Copying a reference</h2><ol><li>Place the cursor in the block to reference. To reference several consecutive blocks, select them.</li><li>Right-click the block handle, the sequence of dots to the left of the block (see <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>). Alternatively, right-click the text and open the <em>Copy</em> submenu.</li><li>Select <em>Copy reference to this block</em>, or <em>Copy reference to these blocks</em> for a selection. The referenced blocks flash briefly.</li><li>Go to the note where to insert the link and press <kbd>Ctrl</kbd>+<kbd>V</kbd>.</li></ol><p>Inside a <a class=\"reference-link\" href=\"#root/_help_EK2ckIZ74tbT\">Content tabs</a> block, the reference points to the whole block. To link to a single tab, use <em>Copy link to tab</em> instead. Inside a <a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a>, the reference points to the blocks in the column, and an include shows them without the layout around them.</p><p>The link shows the title of the note, followed by the beginning of the referenced text. A link to blocks of the same note shows only the beginning of the referenced text.</p><p>If the note is <a href=\"#root/_help_R9pX4DGra2Vt\">shared</a>, the menu of the block handle also offers <em>Copy public link to this block</em>. It copies the web address of the shared page with the reference added, to send to people who read the note outside Trilium. Opening the address scrolls the shared page to the referenced blocks and flashes them. On a shared page, a link to blocks of another shared note does the same.</p><p>The <em>Paste</em> submenu of the context menu offers two more ways to insert a copied reference:</p><ul><li><em>Paste reference as a link</em> inserts only the link, even when the reference was copied as plain text or along with other content.</li><li><em>Paste reference as an excerpt</em> inserts an include of the referenced blocks, as described below.</li></ul><p>In a browser, the context menu of the text editor opens only when right-clicking selected text. Elsewhere the browser shows its own menu.</p><h2>Linking to a heading</h2><p>Since v0.107.0, a link to a heading of the same note can be created from the <em>Add link</em> dialog:</p><ul><li>Place the cursor at the desired position of the link, or select the text to turn into a link.</li><li>Press <kbd>Ctrl</kbd>+<kbd>K</kbd> or the <span class=\"tn-icon cke cke-link\"></span> button in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, then select <em>Headings & anchors</em> at the top of the dialog.</li><li>Under <em>Headings</em>, click the desired heading to check it. Sub-headings are listed under their heading, which can be collapsed. Optionally, type a <em>Link title</em>; without one, the link shows the text of the heading.</li><li>Press <kbd>Enter</kbd> or <em>Add link</em> to confirm.</li></ul><p>The link is a block reference to the heading, so it keeps working when the heading is renamed or moved. The text of the link stays as it was. To change the link, place the cursor inside it and press <kbd>Ctrl</kbd>+<kbd>K</kbd>: the dialog opens on <em>Headings & anchors</em>, with the heading checked.</p><h2>Following a reference</h2><p>Clicking a block reference opens the note, scrolls to the referenced blocks and flashes them. If a referenced block was deleted, an error message is shown instead, along with the blocks of the range that still exist.</p><p>A link to blocks of the note it is in, such as a link to a heading, scrolls to them and flashes them without leaving the note, as a link within a web page does. This works in read-only notes and on shared pages too. While editing, clicking the link shows its popup: press <em>Jump to heading</em> there, or <em>Open note</em> for other blocks.</p><h2>Including the referenced blocks</h2><p>To show the referenced blocks inside another note, right-click the link in a note being edited and select <em>Convert link to note excerpt</em>, or paste the copied reference with <em>Paste</em> → <em>Paste reference as an excerpt</em>. The include shows only the referenced blocks, not the rest of the note, and marks them with an <em>Excerpt</em> badge in its title. It starts at the <em>Full</em> box size, so all the referenced blocks are visible. To see the whole note, press the <span class=\"tn-icon bx bx-link-external\"></span> button in the same title, which opens the note in a new tab. Converting the include back to a link keeps the reference.</p><p>To edit the referenced blocks without leaving the note, press the <span class=\"tn-icon bx bx-pencil\"></span> <em>Edit excerpt</em> button in the title of the include, or turn on <em>Editable</em> (<span class=\"tn-icon bx bx-edit-alt\"></span>) in its toolbar, as for any <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>. Press the button again to stop editing. The changes are saved to the referenced blocks, and the rest of the note stays as it is. The button is grayed out where the blocks cannot be edited, such as in a read-only note. An excerpt has no <em>Fullscreen</em> button.</p><p>If a referenced block was deleted, the include shows <em>Broken reference</em>.</p><h2>Limitations</h2><ul><li>References can be copied only from a note being edited, and not in the mobile layout.</li><li>An include of a range that covers only part of a list or a quote, such as from its second item to a paragraph after it, cannot be edited in place.</li><li>Deleting a block breaks the references to it.</li><li>Block references are not kept when exporting to Markdown. On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, a block reference opens the whole note.</li></ul>",+ "_help_klC3ilXa9kUE": "<p>Block references are <a href=\"#root/_help_QEAPj01N5f7w\">links</a> to a block of a text note, such as a paragraph, a heading, a list item or a table, or to a range of consecutive blocks. A block reference can be pasted in another note as a link, or turned into an <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a> that shows only the referenced blocks.</p><h2>Copying a reference</h2><ol><li>Place the cursor in the block to reference. To reference several consecutive blocks, select them.</li><li>Right-click the block handle, the sequence of dots to the left of the block (see <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>). Alternatively, right-click the text and open the <em>Copy</em> submenu.</li><li>Select <em>Copy reference to this block</em>, or <em>Copy reference to these blocks</em> for a selection. The referenced blocks flash briefly.</li><li>Go to the note where to insert the link and press <kbd>Ctrl</kbd>+<kbd>V</kbd>.</li></ol><p>Inside a <a class=\"reference-link\" href=\"#root/_help_EK2ckIZ74tbT\">Content tabs</a> block, the reference points to the whole block. To link to a single tab, use <em>Copy link to tab</em> instead. Inside a <a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a>, the reference points to the blocks in the column, and an include shows them without the layout around them.</p><p>The link shows the title of the note, followed by the beginning of the referenced text. A link to blocks of the same note shows only the beginning of the referenced text, and a link to a heading of the same note shows the whole heading.</p><p>If the note is <a href=\"#root/_help_R9pX4DGra2Vt\">shared</a>, the menu of the block handle also offers <em>Copy public link to this block</em>. It copies the web address of the shared page with the reference added, to send to people who read the note outside Trilium. Opening the address scrolls the shared page to the referenced blocks and flashes them. On a shared page, a link to blocks of another shared note does the same.</p><p>The <em>Paste</em> submenu of the context menu offers two more ways to insert a copied reference:</p><ul><li><em>Paste reference as a link</em> inserts only the link, even when the reference was copied as plain text or along with other content.</li><li><em>Paste reference as an excerpt</em> inserts an include of the referenced blocks, as described below.</li></ul><p>In a browser, the context menu of the text editor opens only when right-clicking selected text. Elsewhere the browser shows its own menu.</p><h2>Linking to a heading</h2><p>Since v0.107.0, a link to a heading of the same note can be created from the <em>Add link</em> dialog:</p><ul><li>Place the cursor at the desired position of the link, or select the text to turn into a link.</li><li>Press <kbd>Ctrl</kbd>+<kbd>K</kbd> or the <span class=\"tn-icon cke cke-link\"></span> button in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, then select <em>Headings & anchors</em> at the top of the dialog.</li><li>Under <em>Headings</em>, click the desired heading to check it. Sub-headings are listed under their heading, which can be collapsed. Optionally, type a <em>Link title</em>.</li><li>Press <kbd>Enter</kbd> or <em>Add link</em> to confirm.</li></ul><p>When the link title is not set, the link displays the text of the heading. If the heading gets changed, the link is renamed automatically to the new text, shortly after you stop typing. A link with a title of its own keeps that title.</p><p>The link is a block reference to the heading, so it keeps working when the heading is moved. To change the link, click it and press the <span class=\"tn-icon cke cke-pencil\"></span> <em>Edit link</em> button in its popup. For a link with a title of its own, placing the cursor inside it and pressing <kbd>Ctrl</kbd>+<kbd>K</kbd> works too. The dialog opens on <em>Headings & anchors</em>, with the heading checked. Emptying the <em>Link title</em> there makes the link display the text of the heading again.</p><h2>Following a reference</h2><p>Clicking a block reference opens the note, scrolls to the referenced blocks and flashes them. If a referenced block was deleted, an error message is shown instead, along with the blocks of the range that still exist.</p><p>A link to blocks of the note it is in, such as a link to a heading, scrolls to them and flashes them without leaving the note, as a link within a web page does. This works in read-only notes and on shared pages too. While editing, clicking the link shows its popup: press <em>Jump to heading</em> there, or <em>Open note</em> for other blocks.</p><h2>Including the referenced blocks</h2><p>To show the referenced blocks inside another note, right-click the link in a note being edited and select <em>Convert link to note excerpt</em>, or paste the copied reference with <em>Paste</em> → <em>Paste reference as an excerpt</em>. The include shows only the referenced blocks, not the rest of the note, and marks them with an <em>Excerpt</em> badge in its title. It starts at the <em>Full</em> box size, so all the referenced blocks are visible. To see the whole note, press the <span class=\"tn-icon bx bx-link-external\"></span> button in the same title, which opens the note in a new tab. Converting the include back to a link keeps the reference.</p><p>To edit the referenced blocks without leaving the note, press the <span class=\"tn-icon bx bx-pencil\"></span> <em>Edit excerpt</em> button in the title of the include, or turn on <em>Editable</em> (<span class=\"tn-icon bx bx-edit-alt\"></span>) in its toolbar, as for any <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>. Press the button again to stop editing. The changes are saved to the referenced blocks, and the rest of the note stays as it is. The button is grayed out where the blocks cannot be edited, such as in a read-only note. An excerpt has no <em>Fullscreen</em> button.</p><p>If a referenced block was deleted, the include shows <em>Broken reference</em>.</p><h2>Limitations</h2><ul><li>References can be copied only from a note being edited, and not in the mobile layout.</li><li>An include of a range that covers only part of a list or a quote, such as from its second item to a paragraph after it, cannot be edited in place.</li><li>Deleting a block breaks the references to it.</li><li>Block references are not kept when exporting to Markdown. On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, a block reference opens the whole note.</li></ul>","_help_4n4oQUVbnOxa": "<p>Collapsible blocks are sections of content that can be expanded and collapsed, letting you hide detail until it's needed.</p><p>A collapsible block consists of:</p><ul><li><strong>An always-visible header</strong>, containing:<ul><li><strong>An arrow</strong> that expands or collapses the block when clicked.</li><li><strong>A summary line</strong> that acts as the block's title. With the cursor in the summary line, press <kbd>Ctrl</kbd>+<kbd>Enter</kbd> to expand or collapse the block.</li><li><strong>A drag handle</strong> for repositioning the block within the note.</li></ul></li><li><strong>The body</strong>, which is hidden while the block is collapsed. It can hold any kind of content, including nested collapsible blocks. To break out of a collapsible block and continue typing outside it, press <kbd>Enter</kbd> twice at the end of the block.</li></ul><p>You can use the arrow keys to move freely with the cursor between the summary line, the block's body, and the text around the block.</p><h2>Inserting a collapsible block</h2><p>In the formatting bar, go to <em>Insert</em> → <em>Collapsible Block</em>.</p><aside class=\"admonition tip\"><p>Place multiple collapsible blocks one after another to create an accordion, where each block can be expanded or collapsed independently.</p></aside>","_help_veGu4faJErEM": "<p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Content%20language%20%26%20Right-to-left%20support_image.jpg\"></p><p>The content language determines:</p><ul><li>The spell-checking of the note, when in a browser. The desktop installation has a dedicated spellchecking section.</li><li>Whether the text is displayed from right-to-left, for languages such as Arabic, Hebrew, etc.</li><li>How typed quotes are <a href=\"#root/_help_oI7GoyilXXAr\">automatically replaced</a> (e.g. English uses <code>“text”</code>, whereas some languages use <code>«text»</code>). This applies only if <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text</em> → <em>Single/Double quotation marks</em> is set to <em>Based on note's content language</em>.</li><li>Which languages are offered by the <a class=\"reference-link\" href=\"#root/_help_VRoP0g1uHHc2\">In-editor AI assistant</a> for translation.</li><li>The language and the text direction the content is marked with on a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, which screen readers and browsers follow.</li></ul><h2>Setting the language of a single note</h2><p>To set the language of the content of a <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a> note, there is a language selector in the <a class=\"reference-link\" href=\"#root/_help_AlJ73vBCjWDw\">Status bar</a> indicated by a <span class=\"tn-icon bx bx-globe\"></span> icon.</p><h2>Adjusting the list of languages</h2><p>By default, no language is configured. To configure them, go to <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Language & Region</em> → <em>Content languages</em>, or select the <em>Configure languages...</em> item when setting the language. The enabled languages are listed by their native names, sorted alphabetically, which is also the order the language selector shows them in. Here you can:</p><ul><li>Add a language by pressing the <span class=\"tn-icon bx bx-plus\"></span> <em>Add a language</em> button (<em>Add another language</em> once one is enabled), which also shows how many languages are left, and then selecting it.</li><li>Press the <span class=\"tn-icon bx bx-x\"></span> button beside a language to remove it from the list.</li></ul><h2>Default content language</h2><p>Notes that do not have a language of their own follow <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Language & Region</em> → <em>Default content language</em>. It is set to English initially, and can be set to any content language, or to <em>Based on the application's language</em>.</p><p>If a note has a language set, it always takes precedence over the default.</p>","_help_EK2ckIZ74tbT": "<p>Content tabs group several titled panels of content into one block that shows a single panel at a time. They suit content that comes in variants (such as installation steps for each operating system or the same snippet in several programming languages).</p><p>A tabs block consists of:</p><ul><li><strong>A single row of tab titles</strong>, above the panel or, when the tabs are aligned at the bottom, below it. The title of the panel that is showing is highlighted.</li><li><strong>The panel of the active tab.</strong> A panel can hold any kind of content (including nested tabs blocks).</li></ul><h2>Inserting a tabs block</h2><ul><li>In the formatting bar, go to <em>Insert</em> → <em>Tabs</em>.</li><li>Alternatively, type <code>/tabs</code> and press <kbd>Enter</kbd>, as described in <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>.</li></ul><p>A new block contains two tabs, named “Tab 1” and “Tab 2”. Any content that was selected prior to inserting the tabs will be moved into the first tab. The title of the first tab is selected, so typing replaces it.</p><h2>Scrolling through the titles</h2><p>When the titles of a block do not fit on their row, a <span class=\"tn-icon bx bx-chevron-left\"></span> button and a <span class=\"tn-icon bx bx-chevron-right\"></span> button appear at its ends:</p><ul><li>To scroll the titles, click one of the buttons. Holding a button down scrolls the titles continuously until it is released.</li><li>On a touch screen, the titles can also be swiped sideways.</li></ul><p>Whenever another tab is shown (for example by clicking its title, by moving the cursor into it or by following a link to it), the row scrolls so that its whole title is visible. This works the same while editing, in read-only notes and on shared pages.</p><h2>Editing tabs</h2><ul><li>To show a tab, click its title or move the cursor into it.</li><li>To move from a title into its panel, press <kbd>Enter</kbd>.</li><li>The label of a tab can be formatted just like normal text, including support for <a class=\"reference-link\" href=\"#root/_help_hD8GawVuazff\">Icons</a>.</li></ul><p>While the cursor is inside a tabs block, a toolbar appears above it with the following buttons:</p><ul><li><span class=\"tn-icon cke cke-plus\"></span> <em>(Add tab)</em> inserts a tab after the current one and selects its title.</li><li><span class=\"tn-icon cke cke-remove\"></span> <em>(Remove tab)</em> removes the current tab. Removing the last tab removes the whole block.</li><li><span class=\"tn-icon cke cke-chevron-right bx-flip-horizontal\"></span> <em>(Move tab left)</em> and <span class=\"tn-icon cke cke-chevron-right\"></span> (<em>Move tab right)</em> change the order of the tabs.</li><li><span class=\"tn-icon cke cke-link\"></span> <em>(Copy link to tab)</em> copies a link to the current tab, as described below.</li><li><span class=\"tn-icon cke cke-trilium-tabs\"></span> <em>(Tab alignment)</em> places the tab titles above the panel (<em>Align tabs at top</em>, the default) or below it (<em>Align tabs at bottom</em>).</li></ul><p>The tab that is showing is not saved with the note: every tabs block opens on its first tab.</p><h3>Adding tabs</h3><p>While the cursor is in a tab, either in its title or in its panel, you can use these key combinations:</p><ul><li><kbd>Ctrl</kbd> + <kbd>Enter</kbd>: Add a tab after the current one.</li><li><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Enter</kbd>: Add a tab before the current one.</li></ul><p>The new tab is shown and its title is selected, so typing replaces it.</p><p><kbd>Ctrl</kbd> + <kbd>Enter</kbd> keeps its usual function on a link, in a to-do item and in the title of a collapsible block, and <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Enter</kbd> in a to-do item.</p><h3>Reordering tabs</h3><p>While the cursor is in a tab, either in its title or in its panel, you can use these key combinations:</p><ul><li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Right</kbd>: Move the tab to the right.</li><li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Left</kbd>: Move the tab to the left.</li><li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Home</kbd>: Make it the first tab.</li><li><kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>End</kbd>: Make it the last tab.</li></ul><h2>Moving content between tabs</h2><p>To move content to another tab, select it in the panel, and then use these key combinations:</p><ul><li><kbd>Ctrl</kbd> + <kbd>Right</kbd>: Move to the tab on the right.</li><li><kbd>Ctrl</kbd> + <kbd>Left</kbd>: Move to the tab on the left.</li><li><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>End</kbd>: Move to the last tab.</li><li><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Home</kbd>: Move to the first tab.</li></ul><p>The tab that receives the content is shown, with the content still selected, so pressing the key again moves it on to the next tab. Paragraphs, list items, tables and other blocks move whole, even when only part of them is selected. Content moved to a tab on the left goes to the end of that tab, and content moved to a tab on the right goes to its start, so it keeps its place in the reading order.</p><p>Without a selection, or with a selection in a tab title, these keys keep their usual function: moving the cursor by word, or selecting up to the start or end of the tab.</p><p>When a tabs block and a <a class=\"reference-link\" href=\"#root/_help_wYDzQ1fBFgfT\">Multicolumn layout</a> are nested in one another, the key combinations act on the one closest to the cursor.</p><h2>Reading tabs</h2><p>In <a class=\"reference-link\" href=\"#root/_help_CoFPLs3dRlXc\">Read-Only Notes</a> and on <a class=\"reference-link\" href=\"#root/_help_R9pX4DGra2Vt\">Sharing</a>, tabs blocks work as tabs as well:</p><ul><li>To show a tab, click its title, or focus it and press <kbd>Enter</kbd> or <kbd>Space</kbd>.</li><li>To move between the titles of a block, use the arrow keys, <kbd>Home</kbd> and <kbd>End</kbd>.</li></ul><p>A tab without a title shows “Tab title” in place of one.</p><p>In read-only notes, a title too long for its tab fades out where it is cut off. To read the rest of it, swipe it sideways or drag it with the mouse.</p><h2>Linking to a tab</h2><p>A link can point to a single tab, much like a link to a block (see <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>):</p><ol><li>Place the cursor in the tab, either in its title or in its panel.</li><li>Press <em>Copy link to tab</em> (<span class=\"tn-icon cke cke-link\"></span>) in the toolbar of the tabs block. Alternatively, right-click the text and select <em>Copy</em> → <em>Copy link to this tab</em>. The tab flashes briefly.</li><li>Go to the note where to insert the link and press <kbd>Ctrl</kbd>+<kbd>V</kbd>.</li></ol><p>The link shows the title of the note, followed by the title of the tab. Clicking it opens the note, shows the tab and flashes it. As with any block reference, the link can be turned into an <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a> that shows only that tab.</p><p>Links to a tab can be copied only from a note being edited. On a <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a>, such a link opens the whole note.</p><h2>Content in hidden tabs</h2><p>Content inside a tab that is not showing is still reachable (both while editing and while reading). The tab that holds it is shown when:</p><ul><li>searching the note with <kbd>Ctrl</kbd>+<kbd>F</kbd> highlights a match inside it;</li><li>a link points to an anchor or a block inside it (see <a class=\"reference-link\" href=\"#root/_help_oSuaNgyyKnhu\">Anchors</a> and <a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a>);</li><li>an entry of the <a class=\"reference-link\" href=\"#root/_help_BFvAtE74rbP6\">Table of contents</a> or the <a class=\"reference-link\" href=\"#root/_help_AxshuNRegLAv\">Highlights list</a> points inside it;</li><li>on a shared page, the address of the page points to a heading or an anchor inside it.</li></ul><p>Tab titles are not headings, so they do not appear in the table of contents; headings inside a panel do.</p><h2>Printing and exporting</h2><ul><li>When printing or <a href=\"#root/_help_NRnIZmSMc5sj\">exporting to PDF</a>, every tab is printed, one after another, each with its title above its panel, whatever the tab alignment.</li><li>Markdown export and import write tabs blocks in the content tabs syntax of Material for MkDocs, described in <a class=\"reference-link\" href=\"#root/_help_rJ9grSgoExl9\">Supported syntax</a>. <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> notes use the same syntax, show the blocks as tabs in their preview and insert them with <code>/tabs</code>. That syntax has no tab alignment, so tabs aligned at the bottom are exported as regular tabs.</li><li>Anywhere the tabs cannot work as tabs (such as an HTML export opened elsewhere), a tabs block reads as a sequence of titled sections.</li></ul>",diff --git a/docs/User Guide/User Guide/Note Types/Text/Block references.md b/docs/User Guide/User Guide/Note Types/Text/Block references.mdindex 7427df768c..88a523b1d2 100644--- a/docs/User Guide/User Guide/Note Types/Text/Block references.md+++ b/docs/User Guide/User Guide/Note Types/Text/Block references.md@@ -10,7 +10,7 @@ Block references are [links](Links.md) to a block of a text note, such as a paraInside a <a class="reference-link" href="Content%20tabs.md">Content tabs</a> block, the reference points to the whole block. To link to a single tab, use _Copy link to tab_ instead. Inside a <a class="reference-link" href="Multicolumn%20layout.md">Multicolumn layout</a>, the reference points to the blocks in the column, and an include shows them without the layout around them.-The link shows the title of the note, followed by the beginning of the referenced text. A link to blocks of the same note shows only the beginning of the referenced text.+The link shows the title of the note, followed by the beginning of the referenced text. A link to blocks of the same note shows only the beginning of the referenced text, and a link to a heading of the same note shows the whole heading.If the note is [shared](../../Advanced%20Usage/Sharing.md), the menu of the block handle also offers _Copy public link to this block_. It copies the web address of the shared page with the reference added, to send to people who read the note outside Trilium. Opening the address scrolls the shared page to the referenced blocks and flashes them. On a shared page, a link to blocks of another shared note does the same.@@ -27,10 +27,12 @@ Since v0.107.0, a link to a heading of the same note can be created from the _Ad* Place the cursor at the desired position of the link, or select the text to turn into a link.* Press <kbd>Ctrl</kbd>+<kbd>K</kbd> or the <span class="tn-icon cke cke-link"></span> button in the <a class="reference-link" href="Formatting%20toolbar.md">Formatting toolbar</a>, then select _Headings & anchors_ at the top of the dialog.-* Under _Headings_, click the desired heading to check it. Sub-headings are listed under their heading, which can be collapsed. Optionally, type a _Link title_; without one, the link shows the text of the heading.+* Under _Headings_, click the desired heading to check it. Sub-headings are listed under their heading, which can be collapsed. Optionally, type a _Link title_.* Press <kbd>Enter</kbd> or _Add link_ to confirm.-The link is a block reference to the heading, so it keeps working when the heading is renamed or moved. The text of the link stays as it was. To change the link, place the cursor inside it and press <kbd>Ctrl</kbd>+<kbd>K</kbd>: the dialog opens on _Headings & anchors_, with the heading checked.+When the link title is not set, the link displays the text of the heading. If the heading gets changed, the link is renamed automatically to the new text, shortly after you stop typing. A link with a title of its own keeps that title.++The link is a block reference to the heading, so it keeps working when the heading is moved. To change the link, click it and press the <span class="tn-icon cke cke-pencil"></span> _Edit link_ button in its popup. For a link with a title of its own, placing the cursor inside it and pressing <kbd>Ctrl</kbd>+<kbd>K</kbd> works too. The dialog opens on _Headings & anchors_, with the heading checked. Emptying the _Link title_ there makes the link display the text of the heading again.## Following a referencediff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.tsindex 58754c54ed..9557fcc68c 100644--- a/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts@@ -3,13 +3,13 @@ import {BlockToolbar, type ClassicEditor, CodeBlock, Essentials, Heading, List, type ModelNode,Paragraph, Table} from "ckeditor5";-import { describe, expect, it, vi } from "vitest";+import { describe, expect, it, onTestFinished, vi } from "vitest";import { createTestEditor, createTestEditorOf } from "../../../test/editor-kit.js";import BlockDragHandle from "../block_drag_handle.js";import Multicolumn from "../multicolumn/multicolumn.js";import BlockReference from "./block_reference.js";-import { assignBlockId } from "./block_reference_editing.js";+import { assignBlockId, type LinkedBlockChangedEvent } from "./block_reference_editing.js";const PLUGINS = [Essentials, Paragraph, Heading, BlockQuote, CodeBlock, List, Table, BlockReference@@ -260,6 +260,118 @@ describe("BlockReference", () => {});});+ describe("linkedBlockChanged", () => {+ const CONTENT = "<heading1 blockId=\"h\">Intro[]</heading1>"+ + "<blockQuote blockId=\"q\"><paragraph>Quote</paragraph></blockQuote>"+ + "<paragraph>Plain</paragraph>";++ /** An editor with `modelData`, and the ids each `linkedBlockChanged` reports since. */+ async function watch(modelData = CONTENT) {+ const editor = await createTestEditor(PLUGINS);+ vi.useFakeTimers();+ onTestFinished(() => {+ vi.useRealTimers();+ });+ setModelData(editor.model, modelData);+ const reports: (string[] | null)[] = [];+ editor.plugins.get("BlockReferenceEditing").on<LinkedBlockChangedEvent>(+ "linkedBlockChanged",+ (_evt, blockIds) => reports.push(blockIds && [ ...blockIds ].sort())+ );+ vi.runAllTimers();+ reports.length = 0;+ return { editor, reports };+ }++ function type(editor: ClassicEditor, block: ModelNode) {+ editor.model.change((writer) => writer.setSelection(block, "end"));+ editor.execute("insertText", { text: "!" });+ }++ it("reports the blocks with an id whose text changed once editing pauses", async () => {+ const { editor, reports } = await watch();++ editor.execute("insertText", { text: "!" });+ vi.advanceTimersByTime(299);+ editor.execute("insertText", { text: "?" });+ vi.advanceTimersByTime(299);+ expect(reports).toStrictEqual([]);+ vi.advanceTimersByTime(1);+ expect(reports).toStrictEqual([ [ "h" ] ]);++ // A block counts for the blocks around it, and a pause reports all of them at once.+ type(editor, getBlock(editor, 1).getChild(0) as ModelNode);+ type(editor, getBlock(editor, 0));+ vi.runAllTimers();+ expect(reports).toStrictEqual([ [ "h" ], [ "h", "q" ] ]);+ });++ it("reports nothing for blocks without an id, for formatting or for a redraw", async () => {+ const { editor, reports } = await watch();++ type(editor, getBlock(editor, 2));+ editor.execute("enter");+ editor.execute("insertTable", { rows: 1, columns: 1 });+ editor.model.change((writer) => writer.setAttribute(+ "bold", true, writer.createRangeIn(getBlock(editor, 0))+ ));+ editor.editing.reconvertItem(getBlock(editor, 0));+ vi.runAllTimers();+ expect(reports).toStrictEqual([]);++ type(editor, getBlock(editor, 0));+ vi.runAllTimers();+ expect(reports).toStrictEqual([ [ "h" ] ]);+ });++ it("reports a block that gets or loses its id, or that is removed", async () => {+ const { editor, reports } = await watch(+ "<heading1 blockId=\"h\">Intro</heading1><paragraph blockId=\"p\">Text</paragraph>"+ );+ const report = (change: Parameters<typeof editor.model.change>[0]) => {+ editor.model.change(change);+ vi.runAllTimers();+ return reports.at(-1);+ };++ expect(report((writer) => writer.setAttribute("blockId", "n", getBlock(editor, 1))))+ .toStrictEqual([ "n", "p" ]);+ expect(report((writer) => writer.removeAttribute("blockId", getBlock(editor, 1))))+ .toStrictEqual([ "n" ]);+ expect(report((writer) => writer.remove(getBlock(editor, 0)))).toStrictEqual([ "h" ]);+ });++ it("reports any block once a block that holds others is inserted or removed", async () => {+ const { editor, reports } = await watch();++ type(editor, getBlock(editor, 0));+ editor.model.change((writer) => writer.remove(getBlock(editor, 1)));+ vi.runAllTimers();+ editor.model.change((writer) => writer.setSelection(getBlock(editor, 1), "end"));+ editor.execute("blockQuote");+ type(editor, getBlock(editor, 0));+ vi.runAllTimers();++ expect(reports).toStrictEqual([ null, null ]);+ });++ it("reports nothing once it is destroyed", async () => {+ const { editor } = await watch();+ const plugin = editor.plugins.get("BlockReferenceEditing");+ // `destroy()` also removes the listeners, so the report is caught where it is fired.+ const fire = vi.spyOn(plugin, "fire");++ editor.execute("insertText", { text: "!" });+ vi.runAllTimers();+ expect(fire).toHaveBeenCalledExactlyOnceWith("linkedBlockChanged", new Set([ "h" ]));+ editor.execute("insertText", { text: "!" });+ plugin.destroy();+ vi.runAllTimers();++ expect(fire).toHaveBeenCalledExactlyOnceWith("linkedBlockChanged", new Set([ "h" ]));+ });+ });+describe("range editor", () => {it("gives an id to a new block at either edge, and returns the range", async () => {const editor = await createRangeEditor(diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.tsindex a88747789e..2da31d13f7 100644--- a/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts@@ -12,6 +12,9 @@ const BLOCK_ID_LENGTH = 12;const BLOCK_ID_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";const EDGES = [ "first", "last" ] as const;+/** How long the blocks stay unchanged before `linkedBlockChanged` reports them. */+const LINKED_BLOCK_DELAY = 300;+type Edge = typeof EDGES[number];/** The blocks that a reference made from the selection points at. */@@ -21,6 +24,15 @@ export interface BlockReferenceTarget {count: number;}+/**+ * Fired once the editing pauses, with the ids of the blocks whose content changed, or with `null`+ * when any block can have changed.+ */+export type LinkedBlockChangedEvent = {+ name: "linkedBlockChanged";+ args: [ blockIds: ReadonlySet<string> | null ];+};+/*** Stores the id of a referenced block as `data-trilium-block-id`, and keeps each id unique in the* document.@@ -29,6 +41,11 @@ export default class BlockReferenceEditing extends Plugin {private isRangeEditor = false;+ /** The ids that the next `linkedBlockChanged` reports, or `null` for any block. */+ private changedBlockIds: Set<string> | null = new Set();++ private changeTimer: ReturnType<typeof setTimeout> | undefined;+static get pluginName() {return "BlockReferenceEditing" as const;}@@ -64,6 +81,12 @@ export default class BlockReferenceEditing extends Plugin {editor.model.document.registerPostFixer((writer) =>this.isRangeEditor && giveIdsToEdgeBlocks(editor.model, writer));editor.commands.add("assignBlockReference", new AssignBlockReferenceCommand(editor));+ this.listenTo(editor.model.document, "change:data", () => this.collectChangedBlocks());+ }++ override destroy() {+ clearTimeout(this.changeTimer);+ super.destroy();}/**@@ -85,6 +108,23 @@ export default class BlockReferenceEditing extends Plugin {const endId = getEdgeId(model, "last", preferred?.endId);return startId && endId ? { startId, endId } : null;}++ /** Adds the blocks of the last change to the next report, which waits for a pause. */+ private collectChangedBlocks() {+ const blockIds = getChangedBlockIds(this.editor.model);+ if (blockIds && !blockIds.size) {+ return;+ }++ this.changedBlockIds = blockIds && this.changedBlockIds+ && new Set([ ...this.changedBlockIds, ...blockIds ]);+ clearTimeout(this.changeTimer);+ this.changeTimer = setTimeout(() => {+ const changed = this.changedBlockIds;+ this.changedBlockIds = new Set();+ this.fire<LinkedBlockChangedEvent>("linkedBlockChanged", changed);+ }, LINKED_BLOCK_DELAY);+ }}/** Gives ids to the first and the last block of the selection, and returns the reference. */@@ -208,6 +248,53 @@ function getEdgeChild(element: ModelElement, edge: Edge) {return element.getChild(edge === "first" ? 0 : element.childCount - 1);}+/**+ * The ids of the blocks whose content the last change of `model` changed, or `null` when it+ * inserted or removed a block that holds others, whose ids the differ does not list.+ */+function getChangedBlockIds(model: Model) {+ const ids = new Set<string>();+ for (const change of model.document.differ.getChanges()) {+ if (change.type === "attribute") {+ if (change.attributeKey === BLOCK_ID) {+ addBlockIds(ids, change.attributeOldValue, change.attributeNewValue);+ }+ continue;+ }++ // `reconvertItem()` redraws an element without changing it.+ if (change.action === "refresh") {+ continue;+ }++ if (canHoldBlocks(model, change.name)) {+ return null;+ }++ addBlockIds(ids, change.attributes.get(BLOCK_ID));+ let parent = change.position.parent as ModelElement | null;+ for (; parent; parent = parent.parent as ModelElement | null) {+ addBlockIds(ids, parent.getAttribute(BLOCK_ID));+ }+ }++ return ids;+}++/** Whether an element named `name` holds blocks rather than text. */+function canHoldBlocks(model: Model, name: string) {+ const schema = model.schema;+ return !schema.isInline(name) && !schema.isObject(name) && !schema.checkChild(name, "$text");+}++function addBlockIds(ids: Set<string>, ...values: unknown[]) {+ for (const value of values) {+ if (typeof value === "string") {+ ids.add(value);+ }+ }+}+function getInsertedBlocksWithId(model: Model) {const blocks: ModelElement[] = [];for (const change of model.document.differ.getChanges()) {diff --git a/packages/ckeditor5/src/plugins/referencelink.spec.ts b/packages/ckeditor5/src/plugins/referencelink.spec.tsindex 31f1e05493..d13c5bdf43 100644--- a/packages/ckeditor5/src/plugins/referencelink.spec.ts+++ b/packages/ckeditor5/src/plugins/referencelink.spec.ts@@ -1,7 +1,11 @@-import { _getModelData as getModelData, _getViewData as getViewData, _setModelData as setModelData, ClassicEditor, Essentials, LinkEditing, Paragraph } from "ckeditor5";-import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ _getModelData as getModelData, _getViewData as getViewData, _setModelData as setModelData,+ BlockQuote, ClassicEditor, Essentials, Heading, LinkEditing, type ModelElement, Paragraph+} from "ckeditor5";+import { beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";import { createTestEditor } from "../../test/editor-kit.js";+import BlockReference from "./block_reference/block_reference.js";import ReferenceLink, { getAttachmentId, getNoteId } from "./referencelink.js";describe("ReferenceLink", () => {@@ -225,7 +229,8 @@ describe("ReferenceLink", () => {const anchor = editor.editing.view.getDomRoot()?.querySelector("a.reference-link");expect(anchor?.textContent).toBe("Synced title");- expect(getReferenceLinkTitleSync).toHaveBeenCalledWith("#root/noteAbc", "Stored");+ expect(getReferenceLinkTitleSync)+ .toHaveBeenCalledWith("#root/noteAbc", "Stored", undefined);expect(loadReferenceLinkTitle).not.toHaveBeenCalled();});@@ -254,7 +259,8 @@ describe("ReferenceLink", () => {expect(findAnchor()?.getAttribute("href")).toBe("#root/abc");expect(findAnchor()?.querySelector(".bx-spin")).toBeNull();- expect(loadReferenceLinkTitle).toHaveBeenCalledWith(expect.anything(), "#root/abc", undefined);+ expect(loadReferenceLinkTitle)+ .toHaveBeenCalledWith(expect.anything(), "#root/abc", undefined, undefined);});it("redraws the links to a changed attachment and removes those to a deleted one", () => {@@ -297,7 +303,8 @@ describe("ReferenceLink", () => {{ attachmentId: "renamed", isDeleted: false }]);- expect(loadReferenceLinkTitle).toHaveBeenCalledWith(expect.anything(), href, "a");+ expect(loadReferenceLinkTitle)+ .toHaveBeenCalledWith(expect.anything(), href, "a", undefined);expect(getModelData(editor.model)).toBe(before);});@@ -342,6 +349,102 @@ describe("ReferenceLink", () => {expect(redrawnHrefs()).toEqual([]);});+ describe("links to blocks of the note in the editor", () => {+ const LINKS = "<p><a class=\"reference-link\" href=\"#root/abc?block=h\">a</a>"+ + "<a class=\"reference-link\" href=\"#root/parent/abc?block=p:h\">b</a>"+ + "<a class=\"reference-link\" href=\"#root/def?block=h\">c</a>"+ + "<a class=\"reference-link\" href=\"#root/abc\">d</a></p>";+ const OWN_LINKS = [ "#root/abc?block=h", "#root/parent/abc?block=p:h" ];++ /** An editor on the note `abc`, with or without the block ids of `BlockReference`. */+ function createNoteEditor(plugins = [ BlockQuote, Heading, BlockReference ]) {+ const allPlugins = [ Essentials, Paragraph, LinkEditing, ReferenceLink, ...plugins ];+ return createTestEditor(allPlugins, {+ getNoteId: () => "abc",+ referenceLink: {+ getTitle: getReferenceLinkTitle,+ getTitleSync: getReferenceLinkTitleSync,+ renderTitle: loadReferenceLinkTitle+ }+ });+ }++ it("gives the host the content of the editor to read their text from", async () => {+ const noteEditor = await createNoteEditor([]);+ const domRoot = noteEditor.editing.view.getDomRoot();+ const expected = [ [ OWN_LINKS[0], true ], [ OWN_LINKS[1], true ],+ [ "#root/def?block=h", false ], [ "#root/abc", false ] ];++ noteEditor.setData(LINKS);+ expect(loadReferenceLinkTitle.mock.calls.map(([ , href, , content ]) =>+ [ href, content === domRoot ])).toStrictEqual(expected);+ getReferenceLinkTitleSync.mockClear();+ noteEditor.getData();+ expect(getReferenceLinkTitleSync.mock.calls.map(([ href, , content ]) =>+ [ href, content === domRoot ])).toStrictEqual(expected);++ // An editor that does not name its note has no links to blocks of its own.+ loadReferenceLinkTitle.mockClear();+ editor.setData(LINKS);+ expect(loadReferenceLinkTitle.mock.calls.map((args) => args[3]))+ .toStrictEqual([ undefined, undefined, undefined, undefined ]);+ });++ it("redraws the links to blocks whose text changed, but not the document", async () => {+ const noteEditor = await createNoteEditor();+ vi.useFakeTimers();+ onTestFinished(() => {+ vi.useRealTimers();+ });+ noteEditor.setData("<h2 data-trilium-block-id=\"h\">Intro</h2>"+ + "<p data-trilium-block-id=\"p\">Text</p>" + LINKS+ + "<blockquote><p>Quote</p></blockquote>");+ const domRoot = noteEditor.editing.view.getDomRoot();+ // An anchor that only looks like a reference.+ domRoot?.appendChild(document.createElement("a")).classList.add("reference-link");+ vi.runAllTimers();+ const dataChanges = vi.fn();+ noteEditor.model.document.on("change:data", dataChanges);+ const getBlock = (index: number) =>+ noteEditor.model.document.getRoot()?.getChild(index) as ModelElement;+ const type = (index: number) => {+ noteEditor.model.change((writer) => writer.setSelection(getBlock(index), "end"));+ noteEditor.execute("insertText", { text: "!" });+ };+ // The href of each title drawn again, and whether it is the title of that link,+ // drawn from the content of the editor.+ const redrawn = () => {+ const calls = loadReferenceLinkTitle.mock.calls.map(([ title, href, , dom ]) => {+ const linkTitle = domRoot?.querySelector(`a[href="${href}"] > span`);+ return [ href, title === linkTitle && dom === domRoot ];+ });+ loadReferenceLinkTitle.mockClear();+ return calls;+ };++ loadReferenceLinkTitle.mockClear();+ type(0);+ expect(redrawn()).toStrictEqual([]);+ vi.advanceTimersByTime(300);+ expect(redrawn()).toStrictEqual([ [ OWN_LINKS[0], true ], [ OWN_LINKS[1], true ] ]);++ type(1);+ vi.runAllTimers();+ expect(redrawn()).toStrictEqual([ [ OWN_LINKS[1], true ] ]);++ noteEditor.model.change((writer) => writer.remove(getBlock(3)));+ vi.runAllTimers();+ expect(redrawn()).toStrictEqual([ [ OWN_LINKS[0], true ], [ OWN_LINKS[1], true ] ]);+ expect(dataChanges).toHaveBeenCalledTimes(3);++ // A change of the note redraws the other links only.+ getReferenceLinkTitleSync.mockReturnValue("Renamed");+ noteEditor.plugins.get("ReferenceLinkEditing").refreshNoteLinks([ "abc", "def" ]);+ expect(new Set(loadReferenceLinkTitle.mock.calls.map(([ , href ]) => href)))+ .toStrictEqual(new Set([ "#root/def?block=h", "#root/abc" ]));+ });+ });+it("reads the attachment a link points to, and none from a note link or a missing href", () => {expect(getAttachmentId("#root/owner?viewMode=attachments&attachmentId=att1")).toBe("att1");expect(getAttachmentId("#root/noteAbc")).toBeNull();@@ -361,7 +464,8 @@ describe("ReferenceLink", () => {const data = editor.getData();- expect(getReferenceLinkTitleSync).toHaveBeenCalledWith("#root/noteAbc", "old");+ expect(getReferenceLinkTitleSync)+ .toHaveBeenCalledWith("#root/noteAbc", "old", undefined);expect(data).toContain('class="reference-link"');expect(data).toContain('href="#root/noteAbc"');expect(data).toContain("Some title");diff --git a/packages/ckeditor5/src/plugins/referencelink.ts b/packages/ckeditor5/src/plugins/referencelink.tsindex b10a0346a2..c88aebfd97 100644--- a/packages/ckeditor5/src/plugins/referencelink.ts+++ b/packages/ckeditor5/src/plugins/referencelink.ts@@ -4,6 +4,8 @@ import {viewToModelPositionOutsideModelElement, Widget} from "ckeditor5";+import type { LinkedBlockChangedEvent } from "./block_reference/block_reference_editing.js";+export default class ReferenceLink extends Plugin {static get requires() {return [ ReferenceLinkEditing ];@@ -95,6 +97,12 @@ export interface AttachmentLinkChange {isDeleted: boolean;}+/** The title of a link to blocks of the note in the editor, as `renderTitle()` drew it. */+interface BlockLinkTitle {+ blockIds: string[];+ redraw(): void;+}+export class ReferenceLinkEditing extends Plugin {static get requires() {return [ Widget, LinkEditing ];@@ -110,6 +118,9 @@ export class ReferenceLinkEditing extends Plugin {/** The title `getReferenceTitleSync()` read when the editing downcast drew each reference. */private readonly _drawnTitles = new WeakMap<ModelElement, string>();+ /** The title of each reference to blocks of the note in the editor. */+ private readonly _blockLinkTitles = new WeakMap<ModelElement, BlockLinkTitle>();+/*** Redraws the reference links to the notes in `noteIds` whose title changed since they were* drawn. Finds the links in the editing DOM rather than walking the model.@@ -129,7 +140,8 @@ export class ReferenceLinkEditing extends Plugin {}const reference = this._getReference( anchor );- if ( !reference ) {+ // `_redrawBlockLinks()` draws a link to blocks of this note.+ if ( !reference || this._blockLinkTitles.has( reference ) ) {continue;}@@ -217,6 +229,31 @@ export class ReferenceLinkEditing extends Plugin {} );}+ afterInit() {+ const plugins = this.editor.plugins;+ if ( plugins.has( 'BlockReferenceEditing' ) ) {+ this.listenTo<LinkedBlockChangedEvent>(+ plugins.get( 'BlockReferenceEditing' ), 'linkedBlockChanged',+ ( _evt, blockIds ) => this._redrawBlockLinks( blockIds )+ );+ }+ }++ /**+ * Draws the title of the links to `blockIds` of this note again, or of all the links to its+ * blocks for `null`. Changes the DOM of the titles only, so the note is not saved again.+ */+ private _redrawBlockLinks( blockIds: ReadonlySet<string> | null ) {+ const domRoot = this.editor.editing.view.getDomRoot() as HTMLElement;+ for ( const anchor of domRoot.querySelectorAll<HTMLAnchorElement>( 'a.reference-link' ) ) {+ const reference = this._getReference( anchor );+ const title = reference && this._blockLinkTitles.get( reference );+ if ( title && ( !blockIds || title.blockIds.some( id => blockIds.has( id ) ) ) ) {+ title.redraw();+ }+ }+ }+/*** Asks the editor component to fix the reference link around `domTarget` when* `loadReferenceLinkTitle()` rendered it as one to a missing note.@@ -293,6 +330,7 @@ export class ReferenceLinkEditing extends Plugin {const uploadFileName = String(modelItem.getAttribute('uploadFileName') ?? '');const drawnTitle = getReferenceTitleSync( editor, href, storedTitle );this._drawnTitles.set( modelItem, drawnTitle );+ const blockLinkTitles = this._blockLinkTitles;const referenceLinkView = viewWriter.createContainerElement( 'a', {href,@@ -314,7 +352,13 @@ export class ReferenceLinkEditing extends Plugin {const renderTitle = editor.config.get( 'referenceLink' )?.renderTitle;if ( renderTitle ) {- renderTitle( domElement, href, storedTitle );+ const blockIds = getOwnBlockIds( editor, href );+ const content = blockIds ? editor.editing.view.getDomRoot() : undefined;+ const draw = () => renderTitle( domElement, href, storedTitle, content );+ draw();+ if ( blockIds ) {+ blockLinkTitles.set( modelItem, { blockIds, redraw: draw } );+ }} else {domElement.textContent = getReferenceTitleSync( editor, href, storedTitle );}@@ -369,7 +413,20 @@ export function getReferenceTitle( editor: Editor, href: string ): Promise<strin*/export function getReferenceTitleSync( editor: Editor, href: string, storedTitle?: string ): string {const getTitleSync = editor.config.get( 'referenceLink' )?.getTitleSync;- return getTitleSync ? getTitleSync( href, storedTitle ) : storedTitle ?? href;+ if ( !getTitleSync ) {+ return storedTitle ?? href;+ }++ const content = getOwnBlockIds( editor, href ) ? editor.editing.view.getDomRoot() : undefined;+ return getTitleSync( href, storedTitle, content );+}++/** The ids of the blocks of the note in `editor` that `href` links to, or else `null`. */+function getOwnBlockIds( editor: Editor, href: string ) {+ const block = new URLSearchParams( href.split( '?' )[ 1 ] ).get( 'block' );+ return block && getNoteId( href ) === editor.config.get( 'getNoteId' )?.()+ ? block.split( ':' )+ : null;}/** The selected reference link, or `null` when the selection holds none. */@@ -419,13 +476,21 @@ declare module "ckeditor5" {/*** The title of the note or attachment `href` points to, from what is already loaded.* `storedTitle` is the title the saved content holds, for a note that is not loaded.+ * For a link to blocks of the note in the editor, `content` is the editing view's+ * content, which holds their current text.*/- getTitleSync?( href: string, storedTitle?: string ): string;+ getTitleSync?(+ href: string, storedTitle?: string, content?: HTMLElement | null+ ): string;/**- * Fills `element` with the label of the link to `href`, which the host can load.- * Without it, the link shows what `getTitleSync()` reads.+ * Fills `element` with the label of the link to `href`, which the host can load, and+ * with `content` as `getTitleSync()` takes it. Without it, the link shows what+ * `getTitleSync()` reads.*/- renderTitle?( element: HTMLElement, href: string, storedTitle?: string ): void;+ renderTitle?(+ element: HTMLElement, href: string, storedTitle?: string,+ content?: HTMLElement | null+ ): void;/*** Lets the user pick the note a reference link to a missing note should point at* instead, starting from `storedTitle`, and calls `fix()` with the new href.diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex 16eb1e62a6..e412040512 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -855,6 +855,25 @@ describe("content_renderer", () => {expect(content).toStrictEqual("<p>Foo</p>");});+ it("shows a link to a heading of the note it is in as the text of the heading", () => {+ const note = buildShareNote({+ id: "headingLink1",+ content: `<h2 data-trilium-block-id="h">Lists &\n <em>more</em>`+ + `<a class="reference-link" href="#root/headingLink1?block=h">Intro</a></h2>`+ + `<p><a class="reference-link" href="#root/headingLink1?block=h">a</a>`+ + `<a class="reference-link" href="#root/headingLink1?block=p">b</a>`+ + `<a class="reference-link" href="#root/headingLink1?block=gone">c</a></p>`+ + `<p data-trilium-block-id="p">Text</p>`+ });++ const content = getContent(note).content as string;++ expect(content).toContain(`<a class="reference-link type-text"`+ + ` href="./headingLink1?block=h"><span>Lists & more</span></a>`);+ // A link to another block, or to one that is gone, shows the note.+ expect(content.match(/<span class="tn-icon bx bx-note"><\/span>/g)).toHaveLength(2);+ });+it("does not treat an external URL's query string as a note ID", () => {const target = buildShareNote({ id: "extIdTarget1", title: "Target" });const href = `https://example.com/${target.noteId}?x=1`;diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex cc93e0d957..07fdb08fbe 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -5,7 +5,8 @@ import {getNestedEmbedOptions, getNoteEmbedHref, isHttpUrl, isImageAttachmentRole, MIME_TYPE_AUTO,type MimeType, normalizeMimeTypeForCKEditor, readLinkPreviewData, renderLinkEmbedHtml,renderLinkMentionHtml, resolveContentEmbed, resolveEnabledMimeTypes, SHARE_CODE_PREVIEW_THEMES,- SHARE_HOSTED_NOTE_TYPES, SHARE_HOSTED_VIEW_TYPES, shouldSyntaxHighlight, sliceToBlockReference+ resolveBlockReference, SHARE_HOSTED_NOTE_TYPES, SHARE_HOSTED_VIEW_TYPES, shouldSyntaxHighlight,+ sliceToBlockReference} from "@triliumnext/commons";import { renderToHtml as renderMarkdownToHtml } from "@triliumnext/commons/src/lib/markdown_renderer.js";import { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";@@ -726,7 +727,9 @@ function renderText(result: Result, note: SNote | BNote, options: ShareRenderOpt}if (linkEl.classList.contains("reference-link")) {- cleanUpReferenceLinks(linkEl, href ?? "", getNote);+ cleanUpReferenceLinks(linkEl, href ?? "", getNote, {+ noteId: note.noteId, content: document+ });}}@@ -846,7 +849,15 @@ function handleAttachmentLink(linkEl: HTMLElement, href: string, getNote: GetNot* @param linkEl the <a> element to process.* @param href the `href` stored in the note; `handleAttachmentLink()` rewrites the attribute.*/-function cleanUpReferenceLinks(linkEl: HTMLElement, href: string, getNote: GetNoteFunction) {+/** The note whose `content` holds a reference link. */+interface ReferenceLinkHost {+ noteId: string;+ content: HTMLElement;+}++function cleanUpReferenceLinks(+ linkEl: HTMLElement, href: string, getNote: GetNoteFunction, host?: ReferenceLinkHost+) {// Note: this method is basically a reimplementation of getReferenceLinkTitleSync from the link service of the client.// Handle attachment reference links@@ -875,8 +886,37 @@ function cleanUpReferenceLinks(linkEl: HTMLElement, href: string, getNote: GetNo} else if (note.isProtected) {linkEl.innerHTML = "[protected]";} else {- linkEl.innerHTML = `<span><span class="${utils.escapeHtml(note.getIcon())}"></span>${utils.escapeHtml(note.title)}</span>`;+ // A link to a heading of the note it is in shows the text of the heading, as in the app.+ const heading = host && note.noteId === host.noteId+ ? getLinkedHeadingText(host.content, href)+ : null;+ const icon = `<span class="${utils.escapeHtml(note.getIcon())}"></span>`;+ linkEl.innerHTML = heading !== null+ ? `<span>${utils.escapeHtml(heading)}</span>`+ : `<span>${icon}${utils.escapeHtml(note.title)}</span>`;+ }+}++/**+ * The text of the heading in `content` whose block `href` links to, or `null`. The labels of the+ * block references in the heading are left out, as in the app.+ */+function getLinkedHeadingText(content: HTMLElement, href: string) {+ const block = new URLSearchParams(href.split("?")[1]).get("block");+ if (!block) {+ return null;+ }++ const { start, end } = resolveBlockReference<HTMLElement>(content, block);+ if (!start || start !== end || !/^H[1-6]$/.test(start.tagName)) {+ return null;+ }++ const heading = start.clone() as HTMLElement;+ for (const link of heading.querySelectorAll(`a.reference-link[href*="block="]`)) {+ link.remove();}+ return heading.textContent.replace(/\s+/g, " ").trim();}/** Returns the ID of the note a link such as `#root/abc/def?viewMode=source` points to. */