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 editor: add support for headings within the same note
Adorian Doran889b62f267e9
diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.tsindex 05c3356cdb..4183280539 100644--- a/apps/client/src/services/link.spec.ts+++ b/apps/client/src/services/link.spec.ts@@ -25,15 +25,24 @@ vi.mock("./ws.js", () => {// (via note_context) and let us assert on the navigation commands link.ts dispatches.const triggerCommand = vi.fn();const openTabWithNoteWithHoisting = vi.fn();+const getNoteContextById = vi.fn((_ntxId: string) => ({ noteId: "abcdefghijkl" }));vi.mock("../components/app_context.js", () => ({default: {triggerCommand: (...args: unknown[]) => triggerCommand(...args),tabManager: {- openTabWithNoteWithHoisting: (...args: unknown[]) => openTabWithNoteWithHoisting(...args)+ openTabWithNoteWithHoisting: (...args: unknown[]) => openTabWithNoteWithHoisting(...args),+ getNoteContextById: (ntxId: string) => getNoteContextById(ntxId)}}}));+const showAnchor = vi.fn();+const showBlockReference = vi.fn();+vi.mock("@triliumnext/ckeditor5/src/plugins/block_reference/block_reference_read_only.js", () => ({+ showAnchor: (...args: unknown[]) => showAnchor(...args),+ showBlockReference: (...args: unknown[]) => showBlockReference(...args)+}));+const openInCurrentNoteContext = vi.fn();vi.mock("../components/note_context.js", () => ({openInCurrentNoteContext: (...args: unknown[]) => openInCurrentNoteContext(...args)@@ -743,24 +752,66 @@ describe("goToLinkExt", () => {openSpy.mockRestore();});- it("scrolls to an in-page anchor for non-root hash links", () => {- const target = document.createElement("p");- target.id = "fn1";+ it("scrolls to an in-page anchor for non-root hash links, and flashes its block", async () => {const content = document.createElement("div");content.className = "ck-content";- content.appendChild(target);+ content.innerHTML = "<p id=\"fn1\">note</p><p><a id=\"a"b\"></a>held</p>";document.body.appendChild(content);- target.scrollIntoView = vi.fn();- const $link = $("<a id='ref'>").attr("href", "#fn1");- content.appendChild($link[0]);-- const handled = goToLinkExt(leftClick(), "#fn1", $link);- expect(handled).toBe(true);- expect(target.scrollIntoView).toHaveBeenCalled();+ // One at a time: concurrent imports of a mocked module can each resolve differently.+ for (const name of [ "fn1", "a\"b" ]) {+ const $link = $("<a>").attr("href", `#${name}`);+ content.appendChild($link[0]);+ expect(goToLinkExt(leftClick(), `#${name}`, $link)).toBe(true);+ await vi.waitFor(() => expect(showAnchor).toHaveBeenLastCalledWith(content, name));+ }+ expect(showAnchor).toHaveBeenCalledTimes(2);+ expect(openInCurrentNoteContext).not.toHaveBeenCalled();document.body.removeChild(content);});+ it("follows a link to blocks of the note it is in within the page", async () => {+ const split = $("<div data-ntx-id='ntx1'><div class='ck-content'>"+ + "<h2 data-trilium-block-id='h'>Intro</h2></div></div>").appendTo(document.body);+ const content = split.find(".ck-content")[0];+ const click = (href: string, $link = $("<a>").appendTo(content), extra = {}) => {+ goToLinkExt(leftClick(extra), href, $link);+ };++ click("#root/abcdefghijkl?block=h");+ await vi.waitFor(() => expect(showBlockReference).toHaveBeenCalledExactlyOnceWith(+ content, "h"));+ expect(getNoteContextById).toHaveBeenCalledWith("ntx1");+ expect(openInCurrentNoteContext).not.toHaveBeenCalled();++ // Another note, a broken range, content outside a note context, or a modifier navigates.+ click("#root/bcdefghijklm?block=h");+ click("#root/abcdefghijkl?block=h:gone");+ click("#root/abcdefghijkl?block=h", $("<a>"));+ click("#root/abcdefghijkl?block=h", $("<a>").appendTo($("<div class='ck-content'>")));+ click("#root/abcdefghijkl?block=h", undefined, { shiftKey: true });+ expect(openInCurrentNoteContext).toHaveBeenCalledTimes(4);+ expect(triggerCommand).toHaveBeenCalledOnce();+ expect(showBlockReference).toHaveBeenCalledOnce();+ split.remove();+ });++ it("leaves a jump of the link toolbar's preview button to the editor", () => {+ const $preview = $("<a class='ck-link-toolbar__preview' target='_blank'>");+ const handled = leftClick({ isDefaultPrevented: () => true });+ expect(goToLinkExt(handled, "#root/aaaaaaaaaaaa?block=h", $preview)).toBe(true);+ expect(handled.preventDefault).not.toHaveBeenCalled();+ // A double click is two clicks of the button.+ goToLinkExt(leftClick({ type: "dblclick" }), "#root/aaaaaaaaaaaa", $preview);+ expect(openInCurrentNoteContext).not.toHaveBeenCalled();+ expect(openTabWithNoteWithHoisting).not.toHaveBeenCalled();+ // A native event, as the canvas hands over, is read the same way.+ const native = new MouseEvent("click", { cancelable: true });+ native.preventDefault();+ expect(goToLinkExt(native, "#intro", $preview)).toBe(true);+ expect(openInCurrentNoteContext).not.toHaveBeenCalled();+ });+it("does nothing for an unhandled external link without a protocol match", () => {const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);// not http, not api/, not an allowed protocol -> no navigationdiff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.tsindex b7f93dad23..972079015d 100644--- a/apps/client/src/services/link.ts+++ b/apps/client/src/services/link.ts@@ -1,4 +1,6 @@-import { ALLOWED_PROTOCOLS, encodeBlockParameter } from "@triliumnext/commons";+import {+ ALLOWED_PROTOCOLS, encodeBlockParameter, resolveBlockReference+} from "@triliumnext/commons";import appContext, { type NoteCommandData } from "../components/app_context.js";import { openInCurrentNoteContext } from "../components/note_context.js";@@ -546,6 +548,13 @@ export function goToLinkExt(evt: MouseEvent | JQuery.ClickEvent | JQuery.MouseDoreturn true;}+ // The preview button of the text editor's link toolbar acts on its clicks alone, and the+ // editor has handled a click that jumped into the note itself.+ if (evt && $link?.hasClass("ck-link-toolbar__preview")+ && (evt.type === "dblclick" || isDefaultPrevented(evt))) {+ return true;+ }+evt?.preventDefault();evt?.stopPropagation();@@ -555,7 +564,7 @@ export function goToLinkExt(evt: MouseEvent | JQuery.ClickEvent | JQuery.MouseDo}}- const { notePath, viewScope, openInPopup } = parseNavigationStateFromUrl(hrefLink);+ const { notePath, noteId, viewScope, openInPopup } = parseNavigationStateFromUrl(hrefLink);const ctrlKey = evt && utils.isCtrlKey(evt);const shiftKey = evt?.shiftKey;@@ -577,6 +586,12 @@ export function goToLinkExt(evt: MouseEvent | JQuery.ClickEvent | JQuery.MouseDoreturn true;}+ // A link to blocks of the note it is in acts as a link within a page.+ if (isPlainLeftClick && $link && viewScope?.block+ && showBlocksInPlace($link, noteId, viewScope.block)) {+ return true;+ }+if (isLeftClick && openInPopup) {appContext.triggerCommand("openInPopup", { noteIdOrPath: notePath, viewScope });} else if (openInNewWindow) {@@ -639,11 +654,46 @@ function isInEditableText($link: JQuery<HTMLElement>) {* @returns `true` if the link was handled (i.e., the element was found and scrolled to), `false` otherwise.*/function handleAnchor(hrefLink: string, $link: JQuery<HTMLElement>) {- const el = $link.closest(".ck-content").find(hrefLink)[0];- if (el) {- el.scrollIntoView({ behavior: "smooth", block: "center" });+ const content = $link.closest(".ck-content")[0];+ const name = hrefLink.slice(1);+ // Exact comparison: an anchor name can hold characters that a CSS selector does not allow.+ const isFound = !!content+ && Array.from(content.querySelectorAll("[id]")).some((element) => element.id === name);+ if (isFound) {+ void loadBlockJump().then(({ showAnchor }) => showAnchor(content, name));+ }+ return isFound;+}++/**+ * Scrolls to the blocks `block` of the note `noteId` and flashes them, when `$link` is in the+ * content of that note that holds them. Returns whether it does.+ */+function showBlocksInPlace($link: JQuery<HTMLElement>, noteId: string | null, block: string) {+ const content = $link.closest(".ck-content")[0];+ const ntxId = $link.closest("[data-ntx-id]").attr("data-ntx-id");+ if (!content || !ntxId || appContext.tabManager.getNoteContextById(ntxId).noteId !== noteId) {+ return false;}- return !!el;++ // A broken range is left to the note context, which also shows the error.+ const { start, end } = resolveBlockReference(content, block);+ if (!start || !end) {+ return false;+ }++ void loadBlockJump().then(({ showBlockReference }) => showBlockReference(content, block));+ return true;+}++/** Whether something before `goToLinkExt()` already took the default action of `evt`. */+function isDefaultPrevented(evt: NonNullable<Parameters<typeof goToLinkExt>[0]>) {+ return "isDefaultPrevented" in evt ? evt.isDefaultPrevented() : evt.defaultPrevented;+}++/** The module that scrolls to blocks and anchors and flashes them, loaded on first use. */+function loadBlockJump() {+ return import("@triliumnext/ckeditor5/src/plugins/block_reference/block_reference_read_only.js");}function linkContextMenu(e: PointerEvent) {diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 5723594069..de77f6171e 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -79,9 +79,10 @@"title_from_url": "Same as the URL","description": "Description","page_description": "Description of the web page",- "anchors": "Anchors",- "target_anchor": "Target anchor",- "no_anchors": "No anchors available."+ "anchors": "Headings & anchors",+ "target_anchor": "Anchors",+ "headings": "Headings",+ "no_headings_or_anchors": "This note doesn't contain any headings or anchors."},"branch_prefix": {"edit_branch_prefix": "Edit branch prefix",@@ -4718,7 +4719,9 @@"create-a-new-child-note": "Create a new child note","create-a-new-child-note-and-insert-a-link-to-it": "Create a new child note and insert a link to it","open-note": "Open note",- "open-attachment": "Open attachment"+ "open-attachment": "Open attachment",+ "jump-to-heading": "Jump to heading",+ "jump-to-anchor": "Jump to anchor"},"task-state-dropped-title": "Invalid task states","task-state-dropped-message_one": "A custom task state definition is invalid and was ignored.",diff --git a/apps/client/src/widgets/dialogs/edit_link.css b/apps/client/src/widgets/dialogs/edit_link.cssindex 715ca3ed51..eae0365fc7 100644--- a/apps/client/src/widgets/dialogs/edit_link.css+++ b/apps/client/src/widgets/dialogs/edit_link.css@@ -55,21 +55,22 @@margin: 0 auto 1rem;}- .edit-link-anchors .tn-card-body {- border-radius: var(--card-border-radius);- height: 150px;+ .edit-link-targets {+ height: 240px;overflow-y: auto;- > .tn-card-section {- flex-shrink: 0;- }-- > .tn-card-choice:focus-visible {+ .tn-card-choice:focus-visible {outline-offset: -2px;}+ }++ .edit-link-headings {+ --card-nested-section-indent: 24px;- > .edit-link-no-anchors {- flex-grow: 1;+ .tn-card-choice-label {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;}}}diff --git a/apps/client/src/widgets/dialogs/edit_link.spec.tsx b/apps/client/src/widgets/dialogs/edit_link.spec.tsxindex 0d490a092e..6058112dc7 100644--- a/apps/client/src/widgets/dialogs/edit_link.spec.tsx+++ b/apps/client/src/widgets/dialogs/edit_link.spec.tsx@@ -1,6 +1,6 @@import type { RefObject } from "preact";import { act } from "preact/test-utils";-import { beforeEach, describe, expect, it, vi } from "vitest";+import { beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";import Component from "../../components/component";import type { Suggestion } from "../../services/note_autocomplete";@@ -9,7 +9,7 @@ import { renderInto } from "../../test/render";import Modal from "../react/Modal";import { ParentComponent } from "../react/react_utils";import EditLinkDialog, {- EditLinkBalloon, type EditLinkOpts, getShownDisplay, normalizeWebLink+ EditLinkBalloon, type EditLinkOpts, getShownDisplay, type LinkHeading, normalizeWebLink} from "./edit_link";const autocomplete = vi.hoisted(() => ({@@ -124,6 +124,20 @@ describe("EditLinkDialog", () => {return anchorRows().find((row) => row.getAttribute("aria-checked") === "true")?.textContent;}+ function headingRows() {+ return [ ...container.querySelectorAll<HTMLElement>(".edit-link-headings .tn-card-choice") ];+ }++ function checkedHeading() {+ return headingRows().find((row) => row.getAttribute("aria-checked") === "true")?.textContent;+ }++ async function toggleHeading(index: number) {+ const expander = headingRows()[index]?.querySelector<HTMLElement>(".tn-card-choice-expander");+ if (!expander) throw new Error(`The heading ${index} has no expander.`);+ await act(async () => expander.click());+ }+function displays() {return [ ...displaySelect()?.options ?? [] ].map((option) => option.textContent);}@@ -470,7 +484,9 @@ describe("EditLinkDialog", () => {expect(container.querySelector(".note-autocomplete")).toBeNull();expect(headings()).toStrictEqual([ "add_link.target_anchor" ]);const titleCard = field("text")?.closest(".tn-card");- expect(titleCard?.nextElementSibling?.classList.contains("edit-link-anchors")).toBe(true);+ expect(titleCard?.nextElementSibling?.matches(".edit-link-targets")).toBe(true);+ expect(titleCard?.nextElementSibling?.firstElementChild?.matches(".edit-link-anchors"))+ .toBe(true);expect(anchorRows().map((row) => row.textContent)).toStrictEqual([ "intro", "outro" ]);expect(anchorRows().every((row) => row.querySelector(".tn-card-choice-icon.bx-bookmark"))).toBe(true);@@ -514,11 +530,94 @@ describe("EditLinkDialog", () => {await submit();expect(addLink).toHaveBeenLastCalledWith("#intro", "intro", true);- await open({ anchors: [] });+ // With neither headings nor anchors, a placeholder takes the place of the page.+ await open({ anchors: [], headings: [] });+ await act(async () => choice()[2]?.click());+ expect(headings()).toStrictEqual([]);+ expect(field("text")).toBeNull();+ expect(container.querySelector(".no-items")?.textContent)+ .toBe("add_link.no_headings_or_anchors");+ });++ it("lists the headings as a tree above the anchors, and links one by its title", async () => {+ const intro = createHeading("Intro", 2);+ const linux = createHeading("Linux", 4);+ await open({+ anchors: [ "top" ],+ headings: [ intro, createHeading("Setup", 3), linux, createHeading("Usage", 2) ]+ });+ await act(async () => choice()[2]?.click());+ expect(headings()).toStrictEqual([ "add_link.headings", "add_link.target_anchor" ]);+ expect(container.querySelector(".edit-link-targets")?.firstElementChild+ ?.matches(".edit-link-headings")).toBe(true);+ expect(headingRows().map((row) => [+ row.textContent,+ row.getAttribute("style") ?? "",+ !!row.querySelector(".tn-card-choice-icon.bx-heading"),+ row.querySelector(".tn-card-choice-expander-empty") !== null+ ])).toStrictEqual([+ [ "Intro", "", true, false ],+ [ "Setup", "--tn-card-section-nesting-level: 1;", true, false ],+ [ "Linux", "--tn-card-section-nesting-level: 2;", true, true ],+ [ "Usage", "", true, true ]+ ]);++ await toggleHeading(0);+ expect(headingRows().map((row) => row.textContent)).toStrictEqual([ "Intro", "Usage" ]);+ expect(checkedHeading()).toBeUndefined();+ await toggleHeading(0);+ expect(headingRows()).toHaveLength(4);++ await act(async () => headingRows()[2]?.click());+ expect(checkedHeading()).toBe("Linux");+ expect(field("text")?.placeholder).toBe("Linux");+ // A heading and an anchor are one choice.+ await act(async () => anchorRows()[0]?.click());+ expect([ checkedHeading(), checkedAnchor() ]).toStrictEqual([ undefined, "top" ]);+ await act(async () => headingRows()[2]?.click());+ expect([ checkedHeading(), checkedAnchor() ]).toStrictEqual([ "Linux", undefined ]);+ expect(linux.createLinkPath).not.toHaveBeenCalled();+ await submit();+ expect(linux.createLinkPath).toHaveBeenCalledOnce();+ expect(addLink).toHaveBeenLastCalledWith("root/note?block=Linux", "Linux");++ await open({ headings: [ intro ] });await act(async () => choice()[2]?.click());- expect(anchorRows()).toStrictEqual([]);- expect(container.querySelector(".edit-link-anchors .no-items")?.textContent)- .toBe("add_link.no_anchors");+ await act(async () => headingRows()[0]?.click());+ await type(field("text"), "Read the intro");+ await submit();+ expect(addLink).toHaveBeenLastCalledWith("root/note?block=Intro", "Read the intro");+ });++ it("opens an edited heading link on its heading, scrolled to the middle of the list", async () => {+ // The checked row is 400px below the top of the list until the list scrolls.+ vi.spyOn(Element.prototype, "getBoundingClientRect").mockImplementation(function (+ this: Element+ ) {+ const list = this.closest(".edit-link-targets");+ const isChecked = this.getAttribute("aria-checked") === "true";+ return { top: isChecked ? 400 - (list?.scrollTop ?? 0) : 0 } as DOMRect;+ });+ vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(240);+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(40);+ onTestFinished(() => {+ vi.restoreAllMocks();+ });++ const usage = createHeading("Usage", 2);+ await open({+ anchors: [], headings: [ createHeading("Intro", 2), usage ], currentHeading: usage,+ currentTitle: "See usage"+ });+ expect(container.querySelector(".modal-title")?.textContent).toBe("add_link.edit_link");+ expect(current()).toBe("add_link.anchors");+ // A list without items has no card.+ expect(headings()).toStrictEqual([ "add_link.headings" ]);+ expect(checkedHeading()).toBe("Usage");+ expect(field("text")?.value).toBe("See usage");+ expect(container.querySelector(".edit-link-targets")?.scrollTop).toBe(300);+ await submit();+ expect(addLink).toHaveBeenLastCalledWith("root/note?block=Usage", "See usage");});});@@ -643,6 +742,14 @@ describe("EditLinkBalloon", () => {});});+function createHeading(title: string, level: number) {+ return {+ title,+ level,+ createLinkPath: vi.fn(() => `root/note?block=${title}`)+ } satisfies LinkHeading;+}+async function type(input: HTMLInputElement | HTMLTextAreaElement | null, value: string) {if (!input) throw new Error("The field is not shown.");await act(async () => {diff --git a/apps/client/src/widgets/dialogs/edit_link.tsx b/apps/client/src/widgets/dialogs/edit_link.tsxindex 4b469d4c38..4ce96c0570 100644--- a/apps/client/src/widgets/dialogs/edit_link.tsx+++ b/apps/client/src/widgets/dialogs/edit_link.tsx@@ -3,7 +3,7 @@ import "./edit_link.css";import type { LinkDisplayMode } from "@triliumnext/ckeditor5";import internalLinkIcon from "@triliumnext/ckeditor5/src/icons/trilium.svg?raw";import { ALLOWED_PROTOCOLS, isHttpUrl } from "@triliumnext/commons";-import { useEffect, useRef, useState } from "preact/hooks";+import { useEffect, useMemo, useRef, useState } from "preact/hooks";import froca from "../../services/froca";import { t } from "../../services/i18n";@@ -13,7 +13,7 @@ import tree from "../../services/tree";import { isMobile } from "../../services/utils";import { logError } from "../../services/ws";import Button from "../react/Button";-import { Card, CardSection, ChoiceCardSection, OptionCardSection } from "../react/Card";+import { Card, ChoiceCardSection, OptionCardSection } from "../react/Card";import FormSelect from "../react/FormSelect";import FormTextArea from "../react/FormTextArea";import FormTextBox from "../react/FormTextBox";@@ -28,9 +28,23 @@ import SegmentedChoice, { type SegmentedChoiceOption } from "../react/SegmentedCtype LinkType = "reference-link" | "external-link" | "hyper-link";-/** What the link points at: a note, an address outside Trilium, or an anchor in the document. */+/**+ * What the link points at: a note, an address outside Trilium, or a heading or an anchor in the+ * document.+ */export type LinkTarget = "note" | "url" | "anchor";+/** A heading of the document that the link goes into. */+export interface LinkHeading {+ title: string;+ /** 1 for `<h1>`, up to 6 for `<h6>`. */+ level: number;+ /** The block id of the heading, if it has one. */+ blockId?: string;+ /** Gives the heading a block id if it has none, and returns the note path of a link to it. */+ createLinkPath(): string;+}+export interface EditLinkOpts {text: string;hasSelection: boolean;@@ -62,12 +76,19 @@ export interface EditLinkOpts {/** The anchor within the note that the link being edited points at. */currentBookmark?: string;/**- * The anchors in the document that the link goes into. When given, the dialog has an Anchors- * page that links to one of them.+ * The anchors in the document that the link goes into. When given, the dialog has a Headings+ * & anchors page that links to one of them.*/anchors?: string[];/** The anchor in `anchors` that the link being edited points at. */currentAnchor?: string;+ /**+ * The headings of the document that the link goes into, in document order. When given, the+ * Headings & anchors page lists them.+ */+ headings?: LinkHeading[];+ /** The heading in `headings` that the link being edited points at. */+ currentHeading?: LinkHeading;/*** The side a new link opens on, the note side by default. A selected URL opens on the web link* side.@@ -186,9 +207,16 @@ function useEditLinkForm(opts: EditLinkOpts | undefined) {const [ webLink, setWebLink ] = useState("");const [ display, setDisplay ] = useState<LinkDisplayMode>("plain");const [ anchor, setAnchor ] = useState("");+ const [ heading, setHeading ] = useState<LinkHeading | null>(null);+ const [ collapsedHeadings, setCollapsedHeadings ] = useState<ReadonlySet<LinkHeading>>(+ new Set()+ );const [ isShowPending, setIsShowPending ] = useState(false);const webLinkRef = useRef<HTMLInputElement>(null);const titleRef = useRef<HTMLInputElement>(null);+ // The scrolling box around the Headings and Anchors cards.+ const linkTargetsRef = useRef<HTMLDivElement>(null);+ const headingTree = useMemo(() => nestHeadings(opts?.headings ?? []), [ opts ]);// The text of the link being edited, while it stands in for the picked note's title.const keptTitleRef = useRef<string | null>(null);const initialBookmarkRef = useRef("");@@ -211,6 +239,8 @@ function useEditLinkForm(opts: EditLinkOpts | undefined) {setWebLink(initialWebLink ?? "");setDisplay(opts?.display ?? "plain");setAnchor(opts?.currentAnchor ?? "");+ setHeading(opts?.currentHeading ?? null);+ setCollapsedHeadings(new Set());keptTitleRef.current = opts?.currentTitle ?? null;previewTitleRef.current = opts?.currentLink && opts.display && opts.display !== "plain"? opts.currentTitle ?? null : null;@@ -250,6 +280,7 @@ function useEditLinkForm(opts: EditLinkOpts | undefined) {setLinkDescription("");setLinkType(opts?.hasSelection ? "hyper-link" : "reference-link");setAnchor("");+ setHeading(null);if (next === "url") {changeWebLink(text);} else {@@ -259,6 +290,10 @@ function useEditLinkForm(opts: EditLinkOpts | undefined) {}useEffect(() => {+ if (target === "anchor") {+ scrollToCheckedChoice(linkTargetsRef.current);+ }+if (!autoFocus) return;if (target === "url") {webLinkRef.current?.focus();@@ -358,6 +393,10 @@ function useEditLinkForm(opts: EditLinkOpts | undefined) {}, [ isShowPending ]);async function fillAndFocus() {+ if (target === "anchor") {+ scrollToCheckedChoice(linkTargetsRef.current);+ }+if (target === "url" || target === "anchor") {const field = target === "url" ? webLinkRef.current : titleRef.current;if (autoFocus) {@@ -408,9 +447,13 @@ function useEditLinkForm(opts: EditLinkOpts | undefined) {if (!opts) return;if (target === "anchor") {- // An anchor link without a text of its own reads as the anchor's name. `true` keeps- // the href as it is.- if (anchor) opts.addLink(`#${anchor}`, linkTitle.trim() || anchor, true);+ // 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);+ } else if (anchor) {+ opts.addLink(`#${anchor}`, linkTitle.trim() || anchor, true);+ }return;}@@ -446,7 +489,7 @@ function useEditLinkForm(opts: EditLinkOpts | undefined) {const autocompleteRef = useRef<HTMLInputElement>(null);const handleRef = useRef<NoteAutocompleteHandle>(null);- const isEditing = !!opts?.currentLink || !!opts?.currentAnchor;+ const isEditing = !!opts?.currentLink || !!opts?.currentAnchor || !!opts?.currentHeading;const title = opts?.fixLink ? t("add_link.fix_link"): isEditing ? t("add_link.edit_link") : t("add_link.add_link");const buttonText = opts?.fixLink ? t("add_link.button_fix_link")@@ -454,7 +497,7 @@ function useEditLinkForm(opts: EditLinkOpts | undefined) {/** The text the link reads as while the title field is empty. */function getTitlePlaceholder() {- if (target === "anchor") return anchor || undefined;+ if (target === "anchor") return heading?.title || anchor || undefined;if (target !== "url") return undefined;return isPreview ? t("add_link.page_title"): suggestion?.externalLink ?? t("add_link.title_from_url");@@ -477,7 +520,7 @@ function useEditLinkForm(opts: EditLinkOpts | undefined) {{ value: "url", label: t("add_link.web_link"), icon: "bx-globe" },{ value: "note", label: t("add_link.note"), iconSvg: internalLinkIcon }];- if (opts?.anchors) {+ if (opts?.anchors || opts?.headings) {targets.push({ value: "anchor", label: t("add_link.anchors"), icon: "bx-bookmark" });}const switcher = !opts?.fixLink && (@@ -489,27 +532,68 @@ function useEditLinkForm(opts: EditLinkOpts | undefined) {/>);+ /** The choice of `item` on the Headings & anchors page, with the headings under it. */+ function renderHeadingChoice(item: LinkHeading, index: number) {+ const children = headingTree.get(item) ?? [];+ return (+ <ChoiceCardSection+ key={index}+ icon="bx bx-heading"+ isChecked={item === heading}+ onCheck={() => {+ setHeading(item);+ setAnchor("");+ }}+ subSections={children.map(renderHeadingChoice)}+ isExpanded={!collapsedHeadings.has(item)}+ onExpandedChange={(isExpanded) => setCollapsedHeadings((collapsed) => {+ const next = new Set(collapsed);+ if (isExpanded) {+ next.delete(item);+ } else {+ next.add(item);+ }+ return next;+ })}+ >+ {item.title}+ </ChoiceCardSection>+ );+ }+const anchors = opts?.anchors ?? [];- const anchorPage = (<>+ const topHeadings = headingTree.get(null) ?? [];+ const anchorPage = topHeadings.length > 0 || anchors.length > 0 ? (<>{showsTitle && <Card>{titleSection}</Card>}- <Card className="edit-link-anchors" heading={t("add_link.target_anchor")}>- {anchors.length > 0 ? anchors.map((name) => (- <ChoiceCardSection- key={name}- icon="bx bx-bookmark"- isChecked={name === anchor}- onCheck={() => setAnchor(name)}- >- {name}- </ChoiceCardSection>- )) : (- <CardSection className="edit-link-no-anchors">- <NoItems icon="bx bx-bookmark" text={t("add_link.no_anchors")} size="small" />- </CardSection>+ <div ref={linkTargetsRef} className="edit-link-targets">+ {topHeadings.length > 0 && (+ <Card className="edit-link-headings" heading={t("add_link.headings")}>+ {topHeadings.map(renderHeadingChoice)}+ </Card>+ )}++ {anchors.length > 0 && (+ <Card className="edit-link-anchors" heading={t("add_link.target_anchor")}>+ {anchors.map((name) => (+ <ChoiceCardSection+ key={name}+ icon="bx bx-bookmark"+ isChecked={name === anchor}+ onCheck={() => {+ setAnchor(name);+ setHeading(null);+ }}+ >+ {name}+ </ChoiceCardSection>+ ))}+ </Card>)}- </Card>- </>);+ </div>+ </>) : (+ <NoItems icon="bx bx-heading" text={t("add_link.no_headings_or_anchors")} />+ );const displays = [{ value: "plain", title: t("add_link.display_plain") },{ value: "inline", title: t("add_link.display_inline") },@@ -522,7 +606,7 @@ function useEditLinkForm(opts: EditLinkOpts | undefined) {return {title,buttonText,- hasLink: target === "anchor" ? !!anchor : !!suggestion,+ hasLink: target === "anchor" ? !!heading || !!anchor : !!suggestion,/** Fills and focuses the fields, once the form is on screen. */onShown: () => setIsShowPending(true),applyLink,@@ -663,16 +747,45 @@ function useEditLinkForm(opts: EditLinkOpts | undefined) {}/**- * The page the dialog opens on: Anchors for an edited anchor link, Web link when there is an- * `initialWebLink`, and Note otherwise.+ * The page the dialog opens on: Headings & anchors for an edited link to a heading or an anchor,+ * Web link when there is an `initialWebLink`, and Note otherwise.*/function getInitialTarget(opts: EditLinkOpts | undefined, initialWebLink: string | null): LinkTarget {- if (opts?.currentAnchor) return "anchor";+ if (opts?.currentAnchor || opts?.currentHeading) return "anchor";return initialWebLink !== null ? "url" : "note";}+/**+ * The headings nested under each heading of `headings`, with the top level under `null`. A heading+ * nests under the closest heading before it with a lower level.+ */+function nestHeadings(headings: LinkHeading[]) {+ const tree = new Map<LinkHeading | null, LinkHeading[]>();+ const ancestors: LinkHeading[] = [];+ for (const heading of headings) {+ while ((ancestors.at(-1)?.level ?? 0) >= heading.level) {+ ancestors.pop();+ }++ const parent = ancestors.at(-1) ?? null;+ tree.set(parent, [ ...(tree.get(parent) ?? []), heading ]);+ ancestors.push(heading);+ }++ return tree;+}++/** Scrolls the checked choice in `container` to the middle of it, if there is one. */+function scrollToCheckedChoice(container: HTMLElement | null) {+ const choice = container?.querySelector<HTMLElement>("[aria-checked=\"true\"]");+ if (!container || !choice) return;++ const offset = choice.getBoundingClientRect().top - container.getBoundingClientRect().top;+ container.scrollTop += offset - (container.clientHeight - choice.offsetHeight) / 2;+}+/*** The address the dialog opens on, on the web link side: the external link being edited, a* selected text that is a URL, or an empty one for `target: "url"`. `null` opens it on the notediff --git a/apps/client/src/widgets/react/Card.css b/apps/client/src/widgets/react/Card.cssindex 9a850e310a..a006cebf7b 100644--- a/apps/client/src/widgets/react/Card.css+++ b/apps/client/src/widgets/react/Card.css@@ -123,6 +123,19 @@flex-shrink: 0;margin-inline-start: auto;}++ .tn-card-choice-expander {+ flex-shrink: 0;+ font-size: 1.25em;+ }++ .tn-card-choice-expander-empty {+ visibility: hidden;+ }+}++body[dir=rtl] .tn-card-choice-expander {+ transform: scaleX(-1);}.tn-card-section-link {diff --git a/apps/client/src/widgets/react/Card.spec.tsx b/apps/client/src/widgets/react/Card.spec.tsxindex fb00770a4e..3749c9689c 100644--- a/apps/client/src/widgets/react/Card.spec.tsx+++ b/apps/client/src/widgets/react/Card.spec.tsx@@ -186,6 +186,59 @@ describe("ChoiceCardSection", () => {));expect(prevented).toStrictEqual([ true, true, false ]);expect(onCheck).toHaveBeenCalledTimes(3);+ expect(container.querySelector(".tn-card-choice-expander")).toBeNull();+ });++ it("nests choices under an expander, which toggles them without checking the choice", () => {+ const onCheck = vi.fn();+ const onExpandedChange = vi.fn();+ const tree = (isExpanded: boolean) => renderInto(+ <Card>+ <ChoiceCardSection+ isChecked={false} onCheck={onCheck}+ isExpanded={isExpanded} onExpandedChange={onExpandedChange}+ subSections={[+ <ChoiceCardSection+ key="leaf" isChecked={false} onCheck={onCheck}+ onExpandedChange={onExpandedChange} subSections={[]}+ >+ leaf+ </ChoiceCardSection>+ ]}+ >+ parent+ </ChoiceCardSection>+ </Card>+ );++ const expanded = tree(true);+ const [ parent, leaf ] = [ ...expanded.querySelectorAll<HTMLElement>(".tn-card-choice") ];+ expect([ parent, leaf ].map((section) => [+ section?.className.includes("tn-card-section-nested"),+ section?.getAttribute("style") ?? "",+ section?.querySelector(".tn-card-choice-expander")?.className+ ])).toStrictEqual([+ [ false, "", "bx bx-chevron-down tn-card-choice-expander tn-icon" ],+ [+ true, "--tn-card-section-nesting-level: 1;",+ "bx bx-chevron-down tn-card-choice-expander tn-card-choice-expander-empty tn-icon"+ ]+ ]);++ parent?.querySelector<HTMLElement>(".tn-card-choice-expander")?.click();+ expect(onExpandedChange).toHaveBeenCalledExactlyOnceWith(false);+ expect(onCheck).not.toHaveBeenCalled();+ // The hidden expander of a leaf is part of its choice.+ leaf?.querySelector<HTMLElement>(".tn-card-choice-expander")?.click();+ expect(onExpandedChange).toHaveBeenCalledOnce();+ expect(onCheck).toHaveBeenCalledOnce();++ const collapsed = tree(false);+ expect([ ...collapsed.querySelectorAll(".tn-card-choice") ].map((row) => row.textContent))+ .toStrictEqual([ "parent" ]);+ expect(collapsed.querySelector(".tn-card-choice-expander.bx-chevron-right")).not.toBeNull();+ collapsed.querySelector<HTMLElement>(".tn-card-choice-expander")?.click();+ expect(onExpandedChange).toHaveBeenLastCalledWith(true);});});diff --git a/apps/client/src/widgets/react/Card.tsx b/apps/client/src/widgets/react/Card.tsxindex 196fb50453..5b88ea4d02 100644--- a/apps/client/src/widgets/react/Card.tsx+++ b/apps/client/src/widgets/react/Card.tsx@@ -285,18 +285,38 @@ export interface ChoiceCardSectionProps {icon?: string;className?: string;children: ComponentChildren;+ /** The choices nested under this one, as more `ChoiceCardSection`s. */+ subSections?: JSX.Element[];+ /** Whether `subSections` are shown. Defaults to `true`. */+ isExpanded?: boolean;+ /**+ * Adds an expander before the icon, which calls this with the new `isExpanded`. Pass it to+ * every choice of a tree: a choice without `subSections` keeps the space of its hidden+ * expander, so the labels line up.+ */+ onExpandedChange?: (isExpanded: boolean) => void;}/*** One segment of a card that lists exclusive choices. A click, Enter or Space checks it, and the* checked segment shows a check mark.*/-export function ChoiceCardSection(- { isChecked, onCheck, icon, className, children }: ChoiceCardSectionProps-) {- return (+export function ChoiceCardSection({+ isChecked, onCheck, icon, className, children, subSections, isExpanded = true,+ onExpandedChange+}: ChoiceCardSectionProps) {+ const parentContext = useContext(CardSectionContext);+ const nestingLevel = parentContext ? parentContext.nestingLevel + 1 : 0;+ const style = { "--tn-card-section-nesting-level": nestingLevel || null };+ const isExpandable = !!subSections?.length;++ return <><section- className={clsx("tn-card-section tn-card-highlight-on-hover tn-card-choice", className)}+ className={clsx(+ "tn-card-section tn-card-highlight-on-hover tn-card-choice", className,+ { "tn-card-section-nested": nestingLevel > 0 }+ )}+ style={style}role="radio"aria-checked={isChecked}tabIndex={0}@@ -308,11 +328,30 @@ export function ChoiceCardSection(}}}>+ {onExpandedChange && (+ <Icon+ icon={isExpanded ? "bx bx-chevron-down" : "bx bx-chevron-right"}+ className={clsx("tn-card-choice-expander", {+ "tn-card-choice-expander-empty": !isExpandable+ })}+ onClick={isExpandable ? (event) => {+ // Expanding does not check the choice.+ event.stopPropagation();+ onExpandedChange(!isExpanded);+ } : undefined}+ />+ )}{icon && <Icon icon={icon} className="tn-card-choice-icon" />}<span className="tn-card-choice-label">{children}</span>{isChecked && <Icon icon="bx bx-check" className="tn-card-choice-check" />}</section>- );++ {isExpandable && isExpanded && (+ <CardSectionContext.Provider value={{ nestingLevel }}>+ {subSections}+ </CardSectionContext.Provider>+ )}+ </>;}// #endregiondiff --git a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx b/apps/client/src/widgets/type_widgets/text/CKEditor.tsxindex bc6d29e13c..0134efbb00 100644--- a/apps/client/src/widgets/type_widgets/text/CKEditor.tsx+++ b/apps/client/src/widgets/type_widgets/text/CKEditor.tsx@@ -1,7 +1,8 @@import {- type CKEditorError, CKTextEditor, ClassicEditor, getAnchorNames, getLinkAtSelection,- type IconPickerRequest, type LinkAtSelection, type LinkDialogRequest, type LinkDisplayMode,- onTextEditorError, PopupEditor, replaceLinkAtSelection, SnippetDefinition+ assignBlockId, type CKEditorError, CKTextEditor, ClassicEditor, type DocumentHeading,+ getAnchorNames, getHeadings, getLinkAtSelection, type IconPickerRequest, type LinkAtSelection,+ type LinkDialogRequest, type LinkDisplayMode, onTextEditorError, PopupEditor,+ replaceLinkAtSelection, SnippetDefinition} from "@triliumnext/ckeditor5";import { DISPLAYABLE_LOCALE_IDS } from "@triliumnext/commons";import { createPortal, HTMLAttributes, RefObject } from "preact";@@ -25,6 +26,13 @@ export interface CKEditorApi {getCurrentLink(): LinkAtSelection | null;/** The names of the anchors in the document. */getAnchors(): string[];+ /** The headings of the document that have text, in document order. */+ getHeadings(): DocumentHeading[];+ /**+ * The block id of `heading`, which gets a new id first if it has none. `undefined` once the+ * editor is gone.+ */+ assignBlockId(heading: DocumentHeading): string | undefined;addLink(notePath: string, linkTitle: string | null, externalLink?: boolean): void;/*** Rewrites the link around the caret or the selected link preview, as {@link addLink} would@@ -209,6 +217,14 @@ export default function CKEditor({const editor = editorRef.current;return editor ? getAnchorNames(editor) : [];},+ getHeadings() {+ const editor = editorRef.current;+ return editor ? getHeadings(editor) : [];+ },+ assignBlockId(heading) {+ const model = editorRef.current?.model;+ return model && assignBlockId(model, heading.element);+ },async updateLink(notePath, linkTitle, externalLink) {const editor = editorRef.current;if (!editor) return;diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts b/apps/client/src/widgets/type_widgets/text/EditableText.spec.tsindex d53d07513b..286499cc1e 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/EditableText.spec.ts@@ -7,7 +7,7 @@* being uploaded flickered and vanished instead of a "cannot upload" toast appearing.*/import type {- CKEditorError, CKTextEditor, FileUploadData, LinkAtSelection+ CKEditorError, CKTextEditor, DocumentHeading, FileUploadData, LinkAtSelection, ModelElement} from "@triliumnext/ckeditor5";import { beforeEach, describe, expect, it, vi } from "vitest";@@ -456,12 +456,17 @@ describe("parseLinkHref", () => {});describe("getEditLinkOpts", () => {- function createApi(currentLink: LinkAtSelection | null, anchors: string[] = []) {+ function createApi(+ currentLink: LinkAtSelection | null, anchors: string[] = [],+ headings: DocumentHeading[] = []+ ) {return {hasSelection: vi.fn(() => true),getSelectedText: vi.fn(() => "chosen words"),getCurrentLink: vi.fn(() => currentLink),getAnchors: vi.fn(() => anchors),+ getHeadings: vi.fn(() => headings),+ assignBlockId: vi.fn<(heading: DocumentHeading) => string | undefined>(() => "new"),addLink: vi.fn(),updateLink: vi.fn(),addLinkPreview: vi.fn(),@@ -539,6 +544,48 @@ describe("getEditLinkOpts", () => {expect(opts.currentLink).toBeUndefined();});+ it("offers the headings of the note, which link to their blocks", () => {+ const heading = { element: {} as ModelElement, level: 2, text: "Intro" };+ const api = createApi(null, [], [ heading ]);+ expect(getEditLinkOpts(api, ready).headings).toBeUndefined();++ const headings = getEditLinkOpts(api, ready, { notePath: "root/abc" }).headings;+ expect(headings).toMatchObject([ { title: "Intro", level: 2, blockId: undefined } ]);+ expect(api.assignBlockId).not.toHaveBeenCalled();+ expect(headings?.[0]?.createLinkPath()).toBe("root/abc?block=new");+ expect(api.assignBlockId).toHaveBeenCalledExactlyOnceWith(heading);+ api.assignBlockId.mockReturnValueOnce("a b");+ expect(headings?.[0]?.createLinkPath()).toBe("root/abc?block=a%20b");+ // Without an editor, the link goes to the note.+ api.assignBlockId.mockReturnValueOnce(undefined);+ expect(headings?.[0]?.createLinkPath()).toBe("root/abc");+ });++ it("edits a link to a heading of the note as that heading", () => {+ const intro = { element: {} as ModelElement, level: 2, text: "Intro", blockId: "a" };+ const edit = (href: string, isReference?: boolean) => getEditLinkOpts(+ createApi({ href, text: "See intro", display: "plain", isReference }, [], [ intro ]),+ ready, { notePath: "root/abc" }+ );++ const opts = edit("#root/other/abc?block=a");+ expect(opts).toMatchObject({ currentTitle: "See intro", currentHeading: { title: "Intro" } });+ 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);+ expect(other.currentHeading).toBeUndefined();+ expect(other.currentLink?.notePath).toMatch(/^root\/(abc|def)/);+ }+ expect(edit("https://example.com/abc?block=a").currentHeading).toBeUndefined();+ });+it("opens a new link on the side and with the display it is asked for", () => {const opts = getEditLinkOpts(createApi(null), ready, { target: "url", display: "embed" });expect(opts).toMatchObject({ target: "url", display: "embed" });diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex d9c197bbbe..e99eee39de 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -10,7 +10,9 @@ import {type LinkDialogRequest,SnippetDefinition} from "@triliumnext/ckeditor5";-import { deferred, formatBlockRange, parseBlockRange } from "@triliumnext/commons";+import {+ deferred, encodeBlockParameter, formatBlockRange, parseBlockRange+} from "@triliumnext/commons";import { createPortal } from "preact";import { useEffect, useRef, useState } from "preact/hooks";@@ -26,7 +28,7 @@ import note_create from "../../../services/note_create";import { consumeSearchTerms } from "../../../services/search_jump";import toast from "../../../services/toast";import utils, { isMobile } from "../../../services/utils";-import { EditLinkBalloon, type EditLinkOpts } from "../../dialogs/edit_link";+import { EditLinkBalloon, type EditLinkOpts, type LinkHeading } from "../../dialogs/edit_link";import {useEditorSpacedUpdate, useLegacyImperativeHandlers, useNoteLabel, useSameNoteSwitch,useSearchTermsConsumer, useTriliumEvent, useTriliumOption, useTriliumOptionBool@@ -259,7 +261,11 @@ export default function EditableText({function showLinkDialog(request: LinkDialogRequest) {if (!editorApiRef.current) return null;- const opts = getEditLinkOpts(editorApiRef.current, waitForEditor, request);+ const opts = getEditLinkOpts(editorApiRef.current, waitForEditor, {+ target: request.target,+ display: request.display,+ notePath: noteContext?.notePath+ });if (isMobile()) {parentComponent?.triggerCommand("showEditLinkDialog", opts);return null;@@ -585,13 +591,19 @@ export default function EditableText({* The content of an editor of the blocks of a note that `block` points at, and the blocks it holds* now. An empty editor still holds a block, whose id keeps the place of the blocks in the note.*/+/** What the edit link dialog opens on, besides the editor. */+interface EditLinkRequest extends Pick<EditLinkOpts, "target" | "display"> {+ /** The path of the note in the editor. Without it, the dialog lists no headings. */+ notePath?: string | null;+}+/*** What the edit link dialog opens on: the link around the caret or the selected link preview, which* saving rewrites, or a new link at the selection, on the `target` side and shown as `display`.*/export function getEditLinkOpts(api: CKEditorApi, ready: () => Promise<unknown>,- { target, display }: Pick<EditLinkOpts, "target" | "display"> = {}+ { target, display, notePath }: EditLinkRequest = {}): EditLinkOpts {async function addLinkPreview(...args: Parameters<CKEditorApi["addLinkPreview"]>) {await ready();@@ -599,8 +611,13 @@ export function getEditLinkOpts(}const anchors = api.getAnchors();+ 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+ ? findLinkedHeading(currentLink.href, headings, notePath)+ : undefined;return {text: currentLink.text,hasSelection: false,@@ -608,7 +625,8 @@ export function getEditLinkOpts(currentDescription: currentLink.description,display: currentLink.display,anchors,- ...parseLinkHref(currentLink.href, anchors),+ headings,+ ...(currentHeading ? { currentHeading } : parseLinkHref(currentLink.href, anchors)),async addLink(notePath, linkTitle, externalLink) {await ready();await api.updateLink(notePath, linkTitle, externalLink);@@ -623,6 +641,7 @@ export function getEditLinkOpts(target,display,anchors,+ headings,async addLink(notePath, linkTitle, externalLink) {await ready();api.addLink(notePath, linkTitle, externalLink);@@ -631,6 +650,31 @@ export function getEditLinkOpts(};}+/** The headings of the editor, which link to their blocks in the note at `notePath`. */+function getLinkHeadings(api: CKEditorApi, notePath: string): LinkHeading[] {+ return api.getHeadings().map((heading) => ({+ title: heading.text,+ level: heading.level,+ blockId: heading.blockId,+ createLinkPath() {+ const blockId = api.assignBlockId(heading);+ return blockId ? `${notePath}?block=${encodeBlockParameter(blockId)}` : notePath;+ }+ }));+}++/** The heading of `headings` whose block `href` links to, in the note at `notePath`. */+function findLinkedHeading(href: string, headings: LinkHeading[], notePath: string) {+ if (!href.startsWith("#")) return undefined;++ const [ path, query = "" ] = href.slice(1).split("?", 2);+ const blockId = new URLSearchParams(query).get("block");+ const isSameNote = path.split("/").at(-1) === notePath.split("/").at(-1);+ return blockId && isSameNote+ ? headings.find((heading) => heading.blockId === blockId)+ : undefined;+}+/*** What a link's `href` opens the edit link dialog on: one of the document's `anchors`, the note* with the anchor it points at, or the address.diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.jsonindex d5c5bbe20b..4c3fedcb10 100644--- a/apps/server/src/assets/help/help_content.json+++ b/apps/server/src/assets/help/help_content.json@@ -115,10 +115,10 @@"_help_i6dbnitykE5D": "<h2>Inspiration for the name “Trilium”</h2><blockquote><p>Naming software is hard. I lived in Ontario when I first started the project and Trillium (the flower) is sort of a provincial logo, many institutions in Ontario are named \"Trillium [something]\". So I kept hearing/reading it almost everyday, I liked the sound of it and its nature motif, so I just reused it.</p><p><em>– Zadam (original Trilium maintainer)</em></p></blockquote><aside class=\"admonition note\"><p>Despite the fact that the Trillium flower has two “l\"s, the Trilium application only has one.</p></aside><h2>How do I create a folder?</h2><p>Trilium has no separate folder type: any note can have child notes, so any note can act as a folder. A note can hold its own content and have children at the same time, unlike a file system, which separates files from directories.</p><p>To organize notes into a folder:</p><ol><li>Create a note that acts as the folder, for example \"Projects\".</li><li>Right-click it in the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a> and select <em>Insert child note</em>, or hover over it and press the <span class=\"tn-icon bx bx-plus\"></span> button.</li><li>To move existing notes into it, drag them onto it in the tree.</li></ol><p>The children of a note are listed at the end of its content (see <a class=\"reference-link\" href=\"#root/_help_0ESUbbAxVnoK\">Note List</a>).</p><p>If you want the note to look like a folder, with no content of its own and only its children shown, make it a collection instead: right-click in the tree, select <em>Insert child note</em> → <em>Collection</em>, then choose <a class=\"reference-link\" href=\"#root/_help_8QqnMzx393bx\">Grid View</a> or <a class=\"reference-link\" href=\"#root/_help_mULW0Q3VojwY\">List View</a>. See <a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a> for the other views, such as tables, boards and calendars.</p><h2>macOS support</h2><p>Originally, Trilium Notes considered the macOS build unsupported. TriliumNext commits to make the experience on macOS as good as possible.</p><p>if you find any platform-specific issues, feel free to <a href=\"#root/_help_wy8So3yZZlH9\">report them</a>.</p><h2>Translation / localisation support</h2><p>The original Trilium Notes application did not support multiple languages. Since we believe that internationalisation is a core part of an application, we have added support for it.</p><p>Contributions to translations are welcome.</p><h2>Multi-user support</h2><p>Common request is to allow multiple users collaborate, share notes etc. So far I'm resisting this because of these reasons:</p><ul><li>it's a huge feature, or rather a Pandora's box of collaboration features like user management, permissions, conflict resolution, real-time editing of a note by multiple people etc. This would be a huge amount of work. Trilium Notes is project made mostly by one person in free time and that's unlikely to change in the future.</li><li>given its size it would probably pivot the attention away from my main focus which is a personal note-taking</li><li>the assumption that only single person has access to the app simplifies many things, or just outright makes them possible. In multi-user app, our <a href=\"#root/_help_CdNpE2pqjmI6\">scripting</a>support would be a XSS security hole, while with the single user assumption it's an endless customizable tool.</li></ul><h2>How to open multiple documents in one Trilium instance</h2><p>This is normally not supported - one Trilium process can open only a single instance of a <a href=\"#root/_help_wX4HbRucYSDD\">database</a>. However, you can run two Trilium processes (from one installation), each connected to a separate document. To achieve this, you need to set a location for the <a href=\"#root/_help_tAassRL4RSQL\">data directory</a> in the <code>TRILIUM_DATA_DIR</code> environment variable and separate port on <code>TRILIUM_PORT</code> environment variable. How to do that depends on the platform, in Unix-based systems you can achieve that by running command such as this:</p><pre><code class=\"language-text-x-sh\">TRILIUM_DATA_DIR=/home/me/path/to/data/dir TRILIUM_PORT=12345 trilium </code></pre><p>You can save this command into a <code>.sh</code> script file or make an alias. Do this similarly for a second instance with different data directory and port.</p><h2>Can I use Dropbox / Google Drive / OneDrive to sync data across multiple computers.</h2><p>No.</p><p>These general purpose sync apps are not suitable to sync database files which are open and being worked on by another application. The result is that they will corrupt the database file, resulting in data loss and this message in the Trilium logs:</p><pre><code class=\"language-text-x-trilium-auto\">SqliteError: database disk image is malformed</code></pre><p>The only supported way to sync Trilium's data across the network is to use a <a href=\"#root/_help_cbkrhQjrkKrh\">sync/web server</a>.</p><h2>Why database instead of flat files?</h2><p>Trilium stores notes in a <a href=\"#root/_help_wX4HbRucYSDD\">database</a> which is an SQLite database. People often ask why doesn't Trilium rather use flat files for note storage - it's fair question since flat files are easily interoperable, work with SCM/git etc.</p><p>Short answer is that file systems are simply not powerful enough for what we want to achieve with Trilium. Using filesystem would mean fewer features with probably more problems.</p><p>More detailed answer:</p><ul><li><a href=\"#root/_help_IakOLONlIfGI\">clones</a> are what you might call \"hard directory link\" in filesystem lingo, but this concept is not implemented in any filesystem</li><li>filesystems make a distinction between directory and file while there's intentionally no such difference in Trilium</li><li>files are stored in no particular order and user can't change this</li><li>Trilium allows storing note <a href=\"#root/_help_zEY4DaJG4YT5\">attributes</a> which could be represented in extended user attributes but their support differs greatly among different filesystems / operating systems</li><li>Trilium makes links / relations between different notes which can be quickly retrieved / navigated (e.g. for <a href=\"#root/_help_BCkXAVs63Ttv\">note map</a>). There's no such support in file systems which means these would have to be stored in some kind of side-car files (mini-databases).</li><li>Filesystems are generally not transactional. While this is not completely required for a note-taking application, having transactions make it way easier to keep notes and their metadata in predictable and consistent state.</li></ul><h2>Search-related Questions</h2><h3>Why does search sometimes find results with typos?</h3><p>Trilium uses a progressive search strategy that includes fuzzy matching when exact matches return fewer than 5 results. This finds notes despite minor typos in your search query. You can use fuzzy search operators (<code>~=</code> for fuzzy exact match and <code>~*</code> for fuzzy contains). See the <a class=\"reference-link\" href=\"#root/_help_eIg8jdvaoNNd\">Search</a> documentation for details.</p><h3>How can I search for notes when I'm not sure of the exact spelling?</h3><p>Use the fuzzy search operators:</p><ul><li><code>#title ~= \"projct\"</code> - finds notes with titles like \"project\" despite the typo</li><li><code>note.content ~* \"algoritm\"</code> - finds content containing \"algorithm\" or similar words</li></ul><h3>Why do some search results appear before others with lower scores?</h3><p>Trilium places exact matches before fuzzy matches. When you search for \"project\", notes containing exactly \"project\" appear before notes with variations like \"projects\" or \"projection\", regardless of other scoring factors.</p><h3>How can I make my searches faster?</h3><ol><li>Use the \"Fast search\" option to search only titles and attributes (not content)</li><li>Limit search scope using the \"Ancestor\" field</li><li>Set a result limit to prevent loading too many results</li><li>For large databases, consider archiving old notes to reduce search scope</li></ol>","_help_KSZ04uQ2D1St": "<p>One of the core features of Trilium is that it supports multiple types of notes, depending on the need.</p><h2>Creating a new note with a different type via the note tree</h2><p>The default note type in Trilium (e.g. when creating a new note) is <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>, since it's for general use.</p><p>To create a new note of a different type, head to the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a> and right click an existing note where to place the new one and select:</p><ul><li><em>Insert note after</em>, to put the new note underneath the one selected.</li><li><em>Insert child note</em>, to insert the note as a child of the selected note.</li></ul><p>The note types created less often, <a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a>, <a class=\"reference-link\" href=\"#root/_help_HcABDtFCkbFN\">Render Note</a>, <a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a> and <a class=\"reference-link\" href=\"#root/_help_bdUJEHsAPYQR\">Note Map</a>, are in the <em>More</em> submenu.</p><p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types_image.png\"></p><h2>Creating a new note of a different type via add link or new tab</h2><ul><li>When adding a <a href=\"#root/_help_QEAPj01N5f7w\">link</a> in a <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a> note, type the desired title of the new note and press Enter. Afterwards the type of the note will be asked.</li><li>Similarly, when creating a new tab, type the desired title and press Enter.</li></ul><p>The note type is chosen from the same menu as in the note tree, with its submenus (code languages, snippets, collections and the note types created less often) and its search box: type to narrow the list, then press <kbd>Enter</kbd> to create the first match. <kbd>Enter</kbd> right away creates a Text note.</p><h2>Changing the type of a note</h2><p>It is possible to change the type of a note after it has been created via <a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a> → <em>Note type</em>. This feature can also be used to edit the <a href=\"#root/_help_4FahAwuGTAwC\">source of a note</a>.</p><aside class=\"admonition note\"><p>Note that it's generally a good idea to change the note type only if the note is empty</p></aside><h2>Supported note types</h2><p>The following note types are supported by Trilium:</p><figure class=\"table\"><table><thead><tr><th>Note Type</th><th>Description</th></tr></thead><tbody><tr><td><a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a></td><td>The default note type, which allows for rich text formatting, images, admonitions and right-to-left support.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a></td><td>Uses a mono-space font and can be used to store larger chunks of code or plain text than a text note, and has better syntax highlighting.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a></td><td>Stores the information about a search (the search text, criteria, etc.) for later use. Can be used for quick filtering of a large amount of notes, for example. The search can easily be triggered.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_iRwzGnHPzonm\">Relation Map</a></td><td>Allows easy creation of notes and relations between them. Can be used for mainly relational data such as a family tree.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_bdUJEHsAPYQR\">Note Map</a></td><td>Displays the relationships between the notes, whether via relations or their hierarchical structure.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_HcABDtFCkbFN\">Render Note</a></td><td>Used in <a class=\"reference-link\" href=\"#root/_help_CdNpE2pqjmI6\">Scripting</a>, it displays the HTML content of another note. This allows displaying any kind of content, provided there is a script behind it to generate it.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a></td><td>Displays the children of the note either as a grid, a list, or for a more specialized case: a calendar. <br> <br>Generally useful for easy reading of short notes.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_s1aBHPd79XYj\">Mermaid Diagrams</a></td><td>Displays diagrams such as bar charts, flow charts, state diagrams, etc. Requires a bit of technical knowledge since the diagrams are written in a specialized format.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_grjYqerjn243\">Canvas</a></td><td>Allows easy drawing of sketches, diagrams, handwritten content. Uses the same technology behind <a href=\"https://excalidraw.com\">excalidraw.com</a>.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_1vHRoWCEjj0L\">Web View</a></td><td>Displays the content of an external web page, similar to a browser.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_gBbsAeiuUxI5\">Mind Map</a></td><td>Easy for brainstorming ideas, by placing them in a hierarchical layout.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_81SGnPGMk7Xc\">Geo Map</a></td><td>Displays the children of the note as a geographical map, one use-case would be to plan vacations. It even has basic support for tracks. Notes can also be created from it.</td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_W8vYD3Q1zjCR\">File</a></td><td>Represents an uploaded file such as PDFs, images, video or audio files.</td></tr></tbody></table></figure>","_help_iPIMuisry3hd": "<p>The default note type in Trilium, text notes allow for rich formatting, tables, images, admonitions and a handful of other features.</p><h2>Formatting bars</h2><p>Most of the interaction with text notes is done via the built-in toolbars. Depending on preference, there are two different layouts:</p><ul><li>The <em>Floating toolbar</em> is hidden by default and only appears when needed. In this mode there are actually two different toolbars:<br><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/1_Text_image.png\" width=\"496\" height=\"91\"><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/2_Text_image.png\" width=\"812\" height=\"114\"></li><li>A toolbar that appears when text is selected. This provides text-level formatting such as bold, italic, text colors, inline code, etc.<br><em><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text_image.png\" width=\"1109\" height=\"124\"></em></li></ul><p>Fore more information see <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>.</p><h2>Features and formatting</h2><p>Here's a list of various features supported by text notes:</p><figure class=\"table\"><table><thead><tr><th>Dedicated article</th><th>Feature</th></tr></thead><tbody><tr><td><a class=\"reference-link\" href=\"#root/_help_Gr6xFaF6ioJ5\">General formatting</a></td><td><ul><li>Headings (section titles, paragraph)</li><li>Font size</li><li>Bold, italic, underline, strike-through</li><li>Superscript, subscript</li><li>Font color & background color</li><li>Remove formatting</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_S6Xx8QIWTV66\">Lists</a></td><td><ul><li>Bulleted lists</li><li>Numbered lists</li><li>To-do lists</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_NwBbFdNZ9h7O\">Block quotes & admonitions</a></td><td><ul><li>Block quotes</li><li>Admonitions</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_NdowYOC1GFKS\">Tables</a></td><td><ul><li>Basic tables</li><li>Merging cells</li><li>Styling tables and cells.</li><li>Table captions</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_UYuUB1ZekNQU\">Developer-specific formatting</a></td><td><ul><li>Inline code</li><li>Code blocks</li><li>Keyboard shortcuts</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_AgjCISero73a\">Footnotes</a></td><td><ul><li>Footnotes</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_mT0HEkOsz6i1\">Images</a></td><td><ul><li>Images</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_QEAPj01N5f7w\">Links</a></td><td><ul><li>External links</li><li>Internal Trilium links</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a></td><td><ul><li>Include note</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_klC3ilXa9kUE\">Block references</a></td><td><ul><li>Links to blocks of a note</li><li>Including blocks of a note</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_CohkqWQC1iBv\">Insert buttons</a></td><td><ul><li>Symbols</li><li><a class=\"reference-link\" href=\"#root/_help_YfYAtQBcfo5V\">Math Equations</a></li><li>Mermaid diagrams</li><li>Horizontal ruler</li><li>Page break</li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_dEHYtoWWi8ct\">Other features</a></td><td><ul><li>Indentation<ul><li>Markdown import</li></ul></li><li><a class=\"reference-link\" href=\"#root/_help_2x0ZAX9ePtzV\">Cut to subnote</a></li><li><a class=\"reference-link\" href=\"#root/_help_0vgWgxQAWj4a\">Sorting</a></li></ul></td></tr><tr><td><a class=\"reference-link\" href=\"#root/_help_gLt3vA97tMcp\">Premium features</a></td><td><ul><li><a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a></li><li><a class=\"reference-link\" href=\"#root/_help_KC1HB96bqqHX\">Templates</a></li><li><a class=\"reference-link\" href=\"#root/_help_5wZallV2Qo1t\">Format Painter</a></li></ul></td></tr></tbody></table></figure><h2>Read-Only vs. Editing Mode</h2><p>Text notes are usually opened in edit mode. However, they may open in read-only mode if the note is too big or the note is explicitly marked as read-only. For more information, see <a class=\"reference-link\" href=\"#root/_help_CoFPLs3dRlXc\">Read-Only Notes</a>.</p><h2>Keyboard shortcuts</h2><p>There are numerous keyboard shortcuts to format the text without having to use the mouse. For a reference of all the key combinations, see <a class=\"reference-link\" href=\"#root/_help_A9Oc6YKKc65v\">Keyboard Shortcuts</a>. In addition, see <a class=\"reference-link\" href=\"#root/_help_QrtTYPmdd1qq\">Markdown-like formatting</a> as an alternative to the keyboard shortcuts.</p><h2>Content width</h2><p>For readability purposes on wider screens, the width of text notes is limited via a configurable option. See <a class=\"reference-link\" href=\"#root/_help_t596jLvPrqkS\">Content width</a> for more information.</p><h2>Converting to a Markdown note</h2><p>Text notes can be converted to <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> notes. See <a class=\"reference-link\" href=\"#root/_help_jludwdW7N4hg\">Converting between note types</a>.</p><h2>Technical details</h2><p>For the text editing functionality, Trilium uses a commercial product (with an open-source base) called <a class=\"reference-link\" href=\"#root/_help_MI26XDLSAlCD\">CKEditor</a>. This brings the benefit of having a powerful WYSIWYG (What You See Is What You Get) editor.</p>",- "_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>Anchors</em> at the top of the <a href=\"#root/_help_QEAPj01N5f7w\"><em>Add link</em> dialog</a>.</li><li>Under <em>Target anchor</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>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>Anchors</em>, with the linked anchor checked.</li></ul><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>Anchors</em> at its top instead.</p></aside>",+ "_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.</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>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><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.</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_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>",@@ -141,7 +141,7 @@"_help_UmgZAfcltxkS": "<p>Link previews turn a pasted URL into a rich, metadata-aware widget that can be displayed in three visual modes:</p><h2>Display modes</h2><p>A link preview can be displayed in one of three modes:</p><ul><li><strong>Inline</strong> — a link showing the site's favicon and page title (quite similar to <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a>). Use this when you want the link to flow with the surrounding paragraph.</li><li><strong>Card</strong> — a block-level preview with thumbnail, title, description, and site name. Use this when the link is the focus of a paragraph.</li><li><strong>Embed</strong> — a block-level interactive embed.<ul><li>Currently supported for YouTube videos, which render interactively (via an <code>iframe</code>).</li><li>To prevent unwanted remote requests, the video is shown only after clicking on it first. Until then, the video's thumbnail is shown with a play button.</li></ul></li></ul><div class=\"trilium-multicolumn-layout\" data-trilium-column-ratios=\"1-1-1\"><div class=\"trilium-multicolumn-column\"><figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:251/42;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Link%20Previews_image.png\" width=\"251\" height=\"42\"><figcaption><em>Inline</em> link preview</figcaption></figure></div><div class=\"trilium-multicolumn-column\"><figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:1217/196;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Link%20Previews_image.png\" width=\"1217\" height=\"196\"><figcaption><em>Card</em> link preview</figcaption></figure></div><div class=\"trilium-multicolumn-column\"><figure class=\"image image_resized\" style=\"width:100%;\"><img style=\"aspect-ratio:994/563;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Link%20Previews_image.png\" width=\"994\" height=\"563\"><figcaption><em>Embed</em> link preview</figcaption></figure></div></div><h2>Inserting a link preview</h2><p>There are three ways to create one:</p><h3>1. By pasting a URL</h3><p>A link preview is automatically created:</p><ul><li>By pasting the URL and pressing <kbd>Space</kbd>. This will create an <em>inline</em> link preview.</li><li>When at the start of a new paragraph, pressing <kbd>Enter</kbd> will create a <em>card</em> or an <em>embed</em> for YouTube URLs.</li></ul><p>To undo an automatic link preview, press <kbd>Ctrl</kbd>+<kbd>Z</kbd> immediately afterwards which keeps it as a plain link instead. Alternatively, once a link preview was created, click on the link and select <em>Plain link</em> from the link preview toolbar.</p><p>This automatic conversion can be disabled by going to <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text Notes</em> and unchecking <em>Autogenerate link previews</em> from the <em>Features</em> section.</p><p>If the link is not accessible to the Trilium server (or the network request fails for any other reason), it will not be converted to a link preview.</p><aside class=\"admonition note\"><p>A URL is only auto-converted when the pasted text <em>is</em> the URL. Links with a display name (e.g. <a href=\"https://triliumnotes.org\">Trilium Notes website</a>) are left as plain links.</p></aside><h3>2. From the link dialog</h3><p>Since v0.107.0, a link preview is created from the same <em>Add link</em> dialog as any other link (see <a class=\"reference-link\" href=\"#root/_help_3IDVtesTQ8ds\">External links</a>):</p><ul><li>Press <span class=\"tn-icon cke cke-link\"></span> in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, or press <kbd>Ctrl</kbd>+<kbd>K</kbd>, to open the dialog on <em>Web link</em>.</li><li>Type or paste the address, then pick the preview in <em>Display as</em>: <em>Inline</em>, <em>Card</em> or, for a YouTube video, <em>YouTube embed</em>. <em>Plain link</em> inserts an ordinary link. <em>Display as</em> is not shown when text is selected, since the link then keeps the selected text.</li><li>Optionally, type a <em>Link title</em> to show instead of the page's own title. A <em>Card</em> also offers a <em>Description</em> to show instead of the page's own description.</li><li>Press <kbd>Enter</kbd> or <em>Add link</em> to confirm. The link appears right away and turns into the preview once Trilium has read the page.</li></ul><p>Alternatively, use <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a> and look for <em>link preview</em> (it is also found by <em>embed</em>, <em>url</em> or <em>video</em>). It opens the same dialog with a preview already picked: a <em>YouTube embed</em> for a YouTube video, a <em>Card</em> for any other page.</p><p>To turn an existing link into a preview, open its <em>Edit link</em> dialog and change <em>Display as</em>. A link whose text differs from its address keeps that text as the title of the preview.</p><h3>3. By saving browser tabs from the Web Clipper</h3><p>When the <a class=\"reference-link\" href=\"#root/_help_MtPxeAWVAzMg\">Web Clipper</a> saves the tabs of a window, each tab becomes an <em>inline</em> link preview showing the title and favicon the browser displays for it. Because this data comes from the browser, pages behind a login keep their real title, and the Trilium server does not contact the saved pages.</p><p>When <em>Autogenerate link previews</em> is turned off, the tabs are saved as a list of plain links instead.</p><h2>Altering an existing link preview</h2><p>Click on an inserted link preview to select it, and a small toolbar will appear with the following options:</p><ul><li>The normal link operations (opening in a new tab, copying the link, unlinking).</li><li>The <span class=\"tn-icon cke cke-pencil\"></span> <em>Edit link</em> button, which opens the <em>Edit link</em> dialog on the link preview, as does pressing <kbd>Ctrl</kbd>+<kbd>K</kbd> while it is selected. The dialog changes its address, its <em>Link title</em> (especially useful if the title is hidden behind a login screen), the <em>Description</em> of a card and how it is displayed. A new address shows the title and description of the new page, unless you type your own.</li><li>A way to switch between the link preview modes (Inline, Card or Embed) as well as to convert it to a normal link instead.<ul><li>The Embed option is only enabled when the URL points to a supported service (YouTube today).</li></ul></li></ul><h2>Where the preview data comes from</h2><p>When you insert a link preview, Trilium fetches metadata once and stores it with the note:</p><ul><li><strong>YouTube URLs</strong>: the title and channel name are fetched via YouTube's public oEmbed endpoint, and the video's thumbnail is downloaded at up to 1280×720.</li><li><strong>All other URLs</strong>: Trilium fetches the page and reads OpenGraph tags (<code>og:title</code>, <code>og:description</code>, <code>og:image</code>, <code>og:site_name</code>), falling back to the page's <code><title></code> and <code><meta name=\"description\"></code>. The site's favicon and the page's image are downloaded as well.</li></ul><p>The text is kept in the note's HTML. The images are kept as system <a class=\"reference-link\" href=\"#root/_help_0vhv7lsOLy82\">Attachments</a> of the note, listed under <em>Generated by Trilium</em>.</p><p>Because the data is stored in the note itself, link previews continue to render correctly when you reopen the note, share/publish it, or export to HTML — without any further network requests.</p><p>The metadata is captured <strong>at insertion time</strong> and is not automatically refreshed. If the linked page later changes its title or thumbnail, you'll need to re-insert the link to pick up the new values. To refresh a link, simply create it again.</p><p>A YouTube embed inserted before v0.107.0 keeps its smaller thumbnail, shown blurred, until the link is inserted again.</p><p>When accessing a <a class=\"reference-link\" href=\"#root/_help_WOcw2SLH6tbX\">Server Installation</a>, the data is fetched from the remote URL by the server and not the client.</p><h2>Known limitations</h2><ul><li>The Embed display mode currently only supports YouTube. Other video and media platforms fall back to a Card preview.</li><li>Pages that block automated fetches may produce a minimal preview (hostname only).</li><li>Link previews require the Trilium server to reach the target URL, so they won't generate previews for pages on networks the server can't see.</li></ul>","_help_QEAPj01N5f7w": "<p>There are two types of links:</p><ul><li><a class=\"reference-link\" href=\"#root/_help_3IDVtesTQ8ds\">External links</a>, for standard hyperlinks to websites or other resources.</li><li><a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> for links to other notes within Trilium.<ul><li>The list of notes that refer to a particular note is called <a class=\"reference-link\" href=\"#root/_help_wfGXLmm7x27z\">Backlinks</a>.</li></ul></li></ul><h2>Note map</h2><p>Trilium provides a visualization of incoming and outgoing links for a particular note. See <a href=\"#root/_help_BCkXAVs63Ttv\">note map</a> for details.</p>","_help_3IDVtesTQ8ds": "<p>An external link is a standard web link targeting for example a website. For example, <a href=\"https://en.wikipedia.org/wiki/South_China_Sea\">https://en.wikipedia.org/wiki/South_China_Sea</a> is an external link to a Wikipedia page.</p><p>To create a link without a custom text:</p><ul><li>Press <span class=\"tn-icon cke cke-link\"></span> in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, or press <kbd>Ctrl</kbd>+<kbd>K</kbd>:<ul><li>Since v0.107.0, the <em>Add link</em> dialog opens on <em>Web link</em>, in a popup next to the cursor on desktop. Type or paste the address, and optionally a <em>Link title</em>; without one, the link shows its address.</li><li><em>Display as</em> inserts the address as a <em>Plain link</em>, or as one of the <a class=\"reference-link\" href=\"#root/_help_UmgZAfcltxkS\">Link Previews</a>: <em>Inline</em>, <em>Card</em> or, for a YouTube video, <em>YouTube embed</em>.</li><li>Press <kbd>Enter</kbd> or <em>Add link</em> to confirm.</li></ul></li><li>A simpler way is to paste the raw link and press space to turn it automatically into a link.</li><li>The <span class=\"tn-icon cke cke-trilium\"></span> button and <kbd>Ctrl</kbd>+<kbd>L</kbd> of <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> open the same dialog on <em>Note</em>. Select <em>Web link</em> at the top of the dialog to create an external link from there.</li></ul><p>An address without a scheme, such as <code>example.com</code>, gets <code>https://</code>. A URL pasted into the <em>Note</em> field, or picked from its search, switches the dialog to <em>Web link</em>. The dialog also opens on <em>Web link</em> when the selected text is a URL.</p><p>To create a link with a custom text:</p><ul><li>First, type and select the text which will be turned into a link.</li><li>Open the <em>Add link</em> dialog as above (via the formatting toolbar, or <kbd>Ctrl</kbd>+<kbd>K</kbd>). The selected text becomes the text of the link, so the dialog does not offer <em>Display as</em>.</li><li>Alternatively, simply paste (<kbd>Ctrl</kbd>+<kbd>V</kbd>) over the selected text to turn it into a link.</li></ul><p>Once a link is inserted:</p><ul><li>The text inside the link can be changed if needed but the link itself will remain.</li><li>To modify the link, click on the link to display the popup and press the <span class=\"tn-icon cke cke-pencil\"></span> <em>Edit link</em> button. It opens the <em>Edit link</em> dialog, filled with the link's address and text, as do placing the cursor inside the link and pressing <kbd>Ctrl</kbd>+<kbd>K</kbd>, <kbd>Ctrl</kbd>+<kbd>L</kbd> or one of the link buttons. <em>Save link</em> changes the whole link, its text included, and the dialog can also turn it into a link to a note.</li><li>To remove a link, click on it and press the <span class=\"tn-icon cke cke-unlink\"></span> <em>Unlink</em> button.</li></ul><p>You can follow external link by either double clicking (will open new tab/window) it or right clicking on them and choosing \"Open in new tab\".</p>",- "_help_hrZ1D00cLbal": "<p>Internal links are links to other notes within Trilium.</p><p>You can open an internal link by clicking it. You can also see a read-only preview of an internal link's contents by hovering over it.</p><p>Since v0.107.0, clicking an internal link while editing a text note shows its popup instead, as clicking an external link does:</p><ul><li><em>Open note</em> opens the linked note, or <em>Open attachment</em> for a link to an attachment.</li><li><span class=\"tn-icon cke cke-trilium-copy\"></span> <em>Copy URL</em> copies the address of the link.</li><li><span class=\"tn-icon cke cke-pencil\"></span> <em>Edit link</em> changes the link, as described below.</li><li><span class=\"tn-icon cke cke-unlink\"></span> <em>Unlink</em> turns the link into plain text.</li></ul><p>To open the note in a new tab without the popup, <kbd>Ctrl</kbd>+click or double-click the link. The preview does not show while the popup is open.</p><h2>Inserting internal links</h2><p>Internal links can be created at the current position in a text note by:</p><ol><li>Pressing <kbd>Ctrl</kbd> + <kbd>L</kbd> or the <span class=\"tn-icon cke cke-trilium\"></span> button underneath the <span class=\"tn-icon cke cke-plus\"></span> menu in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>. On desktop, the <em>Add link</em> dialog opens in a popup next to the cursor.</li><li>Searching for the title of the desired note to link. It's also possible to create new notes from this dialog by typing a non-existing note title and selecting either <em>Create note</em>, which places it in the <a class=\"reference-link\" href=\"#root/_help_S0Fos78ZfcY7\">Note Inbox</a> (today's day note, or the top level, when no inbox is set), or <em>Create child note</em>, which places it under the note being edited.</li></ol><p>There are two link types, chosen with the <em>Mirror the note's title</em> switch of the dialog, which is on by default:</p><ol><li>With the switch on, the link mirrors the note's title.<ol><li>This is sometimes also called \"reference link\".</li><li>The title of this link cannot be changed. Instead, it will always show the current title of the linked note.</li><li>The icon of the linked note will also be displayed.</li><li>If the linked note is deleted, the link keeps the last title it showed, in red and with a <span class=\"tn-icon bx bx-x\"></span> icon instead of the note icon. Clicking it while editing opens the <em>Fix link</em> dialog, which searches for that title; picking a note, or creating a new one, replaces the link with one to that note.</li></ol></li><li>With the switch off, the link has a title of its own, typed in the <em>Link title</em> field.<ol><li>This will create a traditional hyperlink, where the text of the link can be different from the note title.</li></ol></li></ol><p>Since v0.107.0, to change a 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 whose title does not mirror the note's, placing the cursor inside it and pressing <kbd>Ctrl</kbd> + <kbd>L</kbd> or the <span class=\"tn-icon cke cke-trilium\"></span> button works too. The <em>Edit link</em> dialog opens on the linked note, with its anchor and, for a link with a title of its own, the link's text; <em>Save link</em> changes the whole link. Turning <em>Mirror the note's title</em> on or off there switches between the two link types.</p><h2>In-place linking</h2><p>You can also insert internal links “inline” by using the <code>@</code> symbol:</p><ol><li>Type <code>@</code> in a text note, which will open the note search menu.</li><li>Search for the desired note's title by typing a few characters. Use <kbd>Up</kbd> and <kbd>Down</kbd> to select the correct note, and press <kbd>Enter</kbd> or <kbd>Tab</kbd> to create the link. It's also possible to create new notes with this method by typing a non-existing note title and selecting <em>Create note</em>, as described above, or <em>Create child note</em>. <em>Create child note</em> creates the note under the note being edited without asking for its type, inserts the link and opens the new note in <a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, which offers the note types to turn it into while it is still empty.</li></ol><p>To create an empty child note and link to it before naming it, use <em>New child note</em>, described in <a class=\"reference-link\" href=\"#root/_help_CohkqWQC1iBv\">Insert buttons</a>.</p><h2>Pasting internal links</h2><p>You can also insert internal links by copying a note from the note tree.</p><ol><li>In the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>, select a note and press <kbd>Ctrl</kbd> + <kbd>C</kbd>.</li><li>In a text note, paste the link by pressing <kbd>Ctrl</kbd> + <kbd>V</kbd>.</li></ol>",+ "_help_hrZ1D00cLbal": "<p>Internal links are links to other notes within Trilium.</p><p>You can open an internal link by clicking it. You can also see a read-only preview of an internal link's contents by hovering over it.</p><p>Since v0.107.0, clicking an internal link while editing a text note shows its popup instead, as clicking an external link does:</p><ul><li><em>Open note</em> opens the linked note, or <em>Open attachment</em> for a link to an attachment. A link to a heading of the same note reads <em>Jump to heading</em> instead.</li><li><span class=\"tn-icon cke cke-trilium-copy\"></span> <em>Copy URL</em> copies the address of the link.</li><li><span class=\"tn-icon cke cke-pencil\"></span> <em>Edit link</em> changes the link, as described below.</li><li><span class=\"tn-icon cke cke-unlink\"></span> <em>Unlink</em> turns the link into plain text.</li></ul><p>To open the note in a new tab without the popup, <kbd>Ctrl</kbd>+click or double-click the link. The preview does not show while the popup is open.</p><h2>Inserting internal links</h2><p>Internal links can be created at the current position in a text note by:</p><ol><li>Pressing <kbd>Ctrl</kbd> + <kbd>L</kbd> or the <span class=\"tn-icon cke cke-trilium\"></span> button underneath the <span class=\"tn-icon cke cke-plus\"></span> menu in the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>. On desktop, the <em>Add link</em> dialog opens in a popup next to the cursor.</li><li>Searching for the title of the desired note to link. It's also possible to create new notes from this dialog by typing a non-existing note title and selecting either <em>Create note</em>, which places it in the <a class=\"reference-link\" href=\"#root/_help_S0Fos78ZfcY7\">Note Inbox</a> (today's day note, or the top level, when no inbox is set), or <em>Create child note</em>, which places it under the note being edited.</li></ol><p>There are two link types, chosen with the <em>Mirror the note's title</em> switch of the dialog, which is on by default:</p><ol><li>With the switch on, the link mirrors the note's title.<ol><li>This is sometimes also called \"reference link\".</li><li>The title of this link cannot be changed. Instead, it will always show the current title of the linked note.</li><li>The icon of the linked note will also be displayed.</li><li>If the linked note is deleted, the link keeps the last title it showed, in red and with a <span class=\"tn-icon bx bx-x\"></span> icon instead of the note icon. Clicking it while editing opens the <em>Fix link</em> dialog, which searches for that title; picking a note, or creating a new one, replaces the link with one to that note.</li></ol></li><li>With the switch off, the link has a title of its own, typed in the <em>Link title</em> field.<ol><li>This will create a traditional hyperlink, where the text of the link can be different from the note title.</li></ol></li></ol><p>Since v0.107.0, to change a 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 whose title does not mirror the note's, placing the cursor inside it and pressing <kbd>Ctrl</kbd> + <kbd>L</kbd> or the <span class=\"tn-icon cke cke-trilium\"></span> button works too. The <em>Edit link</em> dialog opens on the linked note, with its anchor and, for a link with a title of its own, the link's text; <em>Save link</em> changes the whole link. Turning <em>Mirror the note's title</em> on or off there switches between the two link types.</p><h2>In-place linking</h2><p>You can also insert internal links “inline” by using the <code>@</code> symbol:</p><ol><li>Type <code>@</code> in a text note, which will open the note search menu.</li><li>Search for the desired note's title by typing a few characters. Use <kbd>Up</kbd> and <kbd>Down</kbd> to select the correct note, and press <kbd>Enter</kbd> or <kbd>Tab</kbd> to create the link. It's also possible to create new notes with this method by typing a non-existing note title and selecting <em>Create note</em>, as described above, or <em>Create child note</em>. <em>Create child note</em> creates the note under the note being edited without asking for its type, inserts the link and opens the new note in <a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, which offers the note types to turn it into while it is still empty.</li></ol><p>To create an empty child note and link to it before naming it, use <em>New child note</em>, described in <a class=\"reference-link\" href=\"#root/_help_CohkqWQC1iBv\">Insert buttons</a>.</p><h2>Pasting internal links</h2><p>You can also insert internal links by copying a note from the note tree.</p><ol><li>In the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>, select a note and press <kbd>Ctrl</kbd> + <kbd>C</kbd>.</li><li>In a text note, paste the link by pressing <kbd>Ctrl</kbd> + <kbd>V</kbd>.</li></ol>","_help_wfGXLmm7x27z": "<p>A link points from one note to another; a <em>backlink</em> is that same connection seen from the other end: the list of notes that refer to the current one.</p><p>Backlinks are maintained automatically and are read-only from this side. A backlink disappears when the note that created it removes the link; it cannot be deleted from the note being pointed at.</p><h2>What counts as a backlink</h2><p>Any <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> pointing at the current note, which covers two rather different cases:</p><ul><li>Relations that Trilium maintains on your behalf.<ul><li>The most common is <code>internalLink</code>, created whenever a note refers to another one through <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> in its text.</li><li>Embedded images (<code>imageLink</code>), relation map connections (<code>relationMapLink</code>) and note inclusions (<code>includeNoteLink</code>) work the same way.</li></ul></li><li>Relations you define yourself.<ul><li>If another note has <code>~author</code> pointing at the current note, that note is listed here as well.</li></ul></li></ul><p>Relations coming from a <a class=\"reference-link\" href=\"#root/_help_m523cpzocqaD\">Saved Search</a> are excluded, since a search stores an <code>ancestor</code> relation that would otherwise list every one of its results as a backlink.</p><aside class=\"admonition note\"><p>Only some note types have their content scanned for links: <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a>, <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a>, <a class=\"reference-link\" href=\"#root/_help_iRwzGnHPzonm\">Relation Map</a> and <a class=\"reference-link\" href=\"#root/_help_GBBMSlVSOIGP\">AI</a> chats. A link written inside a <a class=\"reference-link\" href=\"#root/_help_6f9hih2hXXZk\">Code</a> note is not registered and will not appear as a backlink on the target note. A relation set manually on a code note does still count.</p></aside><h2>How entries are displayed</h2><p>Each entry names the note the reference comes from, followed by one of:</p><ul><li><strong>An excerpt</strong> of the surrounding content, with the link itself highlighted. This is available for <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a> notes and for <a class=\"reference-link\" href=\"#root/_help_GBBMSlVSOIGP\">AI</a> chat notes. Roughly 200 characters of context are quoted around the link, trimmed with an ellipsis where the surrounding text is longer, and images are left out.</li><li><strong>The name of the relation</strong>, for every other note type where the source cannot be quoted. This is the case for <a class=\"reference-link\" href=\"#root/_help_iRwzGnHPzonm\">Relation Map</a> notes and for any note carrying a relation you defined yourself.</li></ul><p>A note is listed once per reference it makes, so a note that links to the current one three times occupies three rows.</p><p>Of note:</p><ul><li>For AI chat notes, only the assistant's own prose is quoted. A chat that reached the note purely through tool calls has nothing to quote and is listed by relation name instead.</li><li>Excerpts are only generated for roughly the first 50 sources. On a heavily referenced note, the remaining entries fall back to showing the relation name.</li></ul><h2>Where backlinks are shown</h2><ul><li>In the <a class=\"reference-link\" href=\"#root/_help_KRlZFoIH0j6p\">Connections tab</a> of the <a class=\"reference-link\" href=\"#root/_help_RnaPdbciOfeq\">Right Sidebar</a>, as a dedicated section.</li><li>As a badge in the <a class=\"reference-link\" href=\"#root/_help_AlJ73vBCjWDw\">Status bar</a> showing the number of backlinks. The badge only appears when the note is being read normally (not in a revision or attachment view) and when there is at least one backlink; pressing it opens the section above.</li><li>In <a class=\"reference-link\" href=\"#root/_help_ZjLYv08Rp3qC\">Quick edit</a>, as a button with a link icon in the header of the popup, under the same conditions; its tooltip gives the number of backlinks. Pressing a backlink opens that note in the popup.</li><li>Incoming links are also drawn on the link map, see <a class=\"reference-link\" href=\"#root/_help_BCkXAVs63Ttv\">Note Map (Link map, Tree map)</a>.</li></ul>","_help_S6Xx8QIWTV66": "<p>There are three types of lists supported by text notes:</p><ul><li><span class=\"tn-icon cke cke-bulleted-list\"></span> Bulleted lists (also known as unordered lists).</li><li><span class=\"tn-icon cke cke-numbered-list\"></span> Numbered lists (or ordered lists).</li><li><span class=\"tn-icon cke cke-todo-list\"></span> To-do lists</li></ul><p>For bulleted and numbered lists, it's possible to configure an alternative marker such as squares or Roman numbering by pressing the <span class=\"tn-icon cke cke-dropdown-arrow\"></span> icon. For numbered lists, it's also possible to specify the number to start at or whether to count in reverse order. On the <a class=\"reference-link\" href=\"#root/_help_RDslemsQ6gCp\">Mobile Frontend</a>, these are in the row of the <em>List ›</em> button, which shows while the cursor is in a list; its <em>List type</em> button also turns the list into another kind, to-do lists included.</p><h2>Keyboard interaction</h2><ul><li>To create a new list:<ul><li>Bulleted list: Start a line with <code>*</code> or <code>-</code> followed by a space;</li><li>Numbered list: Start a line with <code>1.</code> or <code>1)</code> followed by a space;</li><li>To-do list: Start a line with <code>- [ ]</code> for an unchecked item or <code>[x]</code> for a checked item.</li></ul></li><li>To create a new item in the list, press <kbd>Enter</kbd>.</li><li>To create a blank line within a list item, press <kbd>Shift</kbd>+<kbd>Enter</kbd>.</li><li>To exit out of the list, press <kbd>Enter</kbd> twice.</li><li>To merge two lists, simply delete the gap between them.</li><li>To create nested lists, simply use the <span class=\"tn-icon cke cke-indent\"></span> button (see <em>Indentation</em> in <a class=\"reference-link\" href=\"#root/_help_dEHYtoWWi8ct\">Other features</a>) or the <kbd>Tab</kbd> key. To decrease the nesting level for the current element, press <kbd>Shift</kbd>+<kbd>Tab</kbd>.</li></ul><h2>Headings, code blocks within lists</h2><p>It possible to add content-level blocks such as headings, code blocks, tables within lists, as follows:</p><figure class=\"table\"><table><tbody><tr><td>1</td><td><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Lists_image.jpg\"></td><td>First, create a list.</td></tr><tr><td>2</td><td><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/4_Lists_image.jpg\"></td><td>Press Enter to create a new list item.</td></tr><tr><td>3</td><td><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Lists_image.jpg\"></td><td>Press Backspace to get rid of the bullet point. Notice the cursor position.</td></tr><tr><td>4</td><td><img class=\"image_resized\" style=\"aspect-ratio:676/112;width:98.29%;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/5_Lists_image.jpg\" width=\"676\" height=\"112\"></td><td>At this point, insert any desired block-level item such as a code block.</td></tr><tr><td>5</td><td><img class=\"image_resized\" style=\"aspect-ratio:675/129;width:94.22%;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/3_Lists_image.jpg\" width=\"675\" height=\"129\"></td><td>To continue with a new bullet point, press Enter until the cursor moves to a new blank position.</td></tr><tr><td>6</td><td><img class=\"image_resized\" style=\"aspect-ratio:675/129;width:100%;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Lists_image.jpg\" width=\"675\" height=\"129\"></td><td>Press Enter once more to create the new bullet.</td></tr></tbody></table></figure><p>The same principle applies to all three list types (bullet, numbered and to-do).</p><h2>Sorting</h2><p>The items of a list can be sorted, nested items moving with the item they belong to. This is experimental, see <a class=\"reference-link\" href=\"#root/_help_0vgWgxQAWj4a\">Sorting</a>.</p><h2>Alignment</h2><p>A list item can be centered or aligned to the right, either with the text alignment button in the formatting toolbar or by aligning the <a class=\"reference-link\" href=\"#root/_help_NdowYOC1GFKS\">Tables</a> cell that contains the list. The bullet, number or checkbox then moves together with the text of the item.</p><h2>To-do lists</h2><p>See <a class=\"reference-link\" href=\"#root/_help_fASfBrYnquKU\">To-do Lists</a>.</p><h2>Collapsible lists</h2><p>Starting with Trilium v0.104.0, it is possible to collapse nested list items. This applies to bullet lists, numbered lists as well as to-do lists.</p><p>To collapse or expand a list item that has nested sub-items:</p><ul><li>Using the mouse, move the cursor over the list item and an arrow will appear to its left. Clicking it will toggle between collapsed and expanded.</li><li>For bullet lists and numbered lists, it's also possible to click directly on the marker (e.g. the bullet or the number) instead of on the arrow to collapse or expand it. This won't work for to-do lists since this would toggle the to-do instead.</li><li>Press <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Enter</kbd> which will toggle the collapse/expand state for the item at the cursor position.</li></ul><p>Of note:</p><ul><li>Collapsed items always show the arrow to indicate its state.</li><li>The collapsed state is saved at note level and synced across instances, which means that it will restore after a refresh or reopening of the application.</li><li>The collapsed state is also persisted in <a class=\"reference-link\" href=\"#root/_help_mHbBMPDPkVV5\">Import & Export</a>, but only for the HTML format. Markdown exports will not preserve the collapse state.</li><li>Collapsible bullets only exist in the context of editable text notes. Read-only lists will always be fully expanded.</li><li>The list items will auto-expand on edit to avoid typing in a hidden area.</li></ul>","_help_QrtTYPmdd1qq": "<p>Markdown-like formatting allows inserting some basic formatting by typing the Markdown equivalent. Note that this does not mean that <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a> notes supports Markdown, these are just some convenience shortcuts.</p><p>To import more complex formatting into text notes, consider using the <a href=\"#root/_help_dEHYtoWWi8ct\"><em>Import from Markdown</em></a> function. For fully-fleged Markdown notes imports, consider using the dedicated <a href=\"#root/_help_Oau6X9rCuegd\">import</a> function.</p><ul><li>For <a href=\"#root/_help_Gr6xFaF6ioJ5\">headings:</a><ul><li><code>##</code> for Heading 2 (the first-level heading is reserved for the note title).</li><li><code>###</code> for Heading 3</li><li><code>####</code> for Heading 4</li><li><code>#####</code> for Heading 5</li><li><code>######</code> for Heading 6</li></ul></li><li>For <a class=\"reference-link\" href=\"#root/_help_Gr6xFaF6ioJ5\">General formatting</a>:<ul><li><strong>Bold</strong>: Type <code>**text**</code> or <code>__text__</code></li><li><em>Italic</em>: Type <code>*text*</code> or <code>_text_</code></li><li><del>Strikethrough</del>: Type <code>~~text~~</code></li></ul></li><li>For <a class=\"reference-link\" href=\"#root/_help_S6Xx8QIWTV66\">Lists</a>:<ul><li>Bulleted list: Start a line with <code>*</code> or <code>-</code> followed by a space;</li><li>Numbered list: Start a line with <code>1.</code> or <code>1)</code> followed by a space;</li><li>To-do list: Start a line with <code>[ ]</code> for an unchecked item or <code>[x]</code> for a checked item.</li></ul></li><li>For <a href=\"#root/_help_NwBbFdNZ9h7O\">block quotes</a>, press <code>></code>, followed by a space.</li><li>For <a class=\"reference-link\" href=\"#root/_help_QxEyIjRBizuC\">Code blocks</a>, type <code>```</code>.</li><li>For a <a href=\"#root/_help_dEHYtoWWi8ct\">horizontal line</a>, type <code>---</code>.</li><li>For <a href=\"#root/_help_NwBbFdNZ9h7O\">admonitions</a>:<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><li>Starting any other text with <code>!!!</code> will insert a note admonition with the text inside of it.</li></ul></li><li>For <a href=\"#root/_help_CohkqWQC1iBv\">emojis</a>, type <code>:</code> followed by an emoji name to trigger an auto-completion.</li></ul><p>If auto-formatting is not desirable, press <kbd>Ctrl</kbd> + <kbd>Z</kbd> to revert the text to its original form.</p>",diff --git a/docs/User Guide/User Guide/Note Types/Text/Anchors.md b/docs/User Guide/User Guide/Note Types/Text/Anchors.mdindex 2b35522573..bfca711a30 100644--- a/docs/User Guide/User Guide/Note Types/Text/Anchors.md+++ b/docs/User Guide/User Guide/Note Types/Text/Anchors.md@@ -14,10 +14,14 @@ This feature was introduced in TriliumNext v0.94.0 and augmented in v0.103.0 to* Alternatively, use <a class="reference-link" href="Slash%20Commands.md">Slash Commands</a> and look for _anchor_.* To place a link to an anchor in the same note:* 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 _Anchors_ at the top of the [_Add link_ dialog](Links.md).- * Under _Target anchor_, click the desired anchor to check it. Optionally, type a _Link title_; without one, the link shows the anchor's name.+ * 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 [_Add link_ dialog](Links.md).+ * Under _Anchors_, click the desired anchor to check it. Optionally, type a _Link title_; without one, the link shows the anchor's name.* Press <kbd>Enter</kbd> or _Add link_ to confirm.-* 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 _Edit link_ dialog opens on _Anchors_, with the linked anchor checked.+* 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.+* 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 _Edit link_ dialog opens on _Headings & anchors_, with the linked anchor checked.++> [!TIP]+> To link to a heading of the same note, no anchor is needed: pick the heading under _Headings_ in the same dialog. See [Linking to a heading](Block%20references.md) for details.## Linking across notes@@ -46,4 +50,4 @@ Clicking on a reference link pointing to an anchor will automatically scroll to4. Go to the note where to insert the link and press <kbd>Ctrl</kbd>+<kbd>V</kbd>.> [!NOTE]-> Use this method only to insert <a class="reference-link" href="Links/Internal%20(reference)%20links.md">Internal (reference) links</a> between two documents. To link to an anchor on the same note, use the _Add link_ dialog (<kbd>Ctrl</kbd>+<kbd>K</kbd>) and select _Anchors_ at its top instead.\ No newline at end of file+> Use this method only to insert <a class="reference-link" href="Links/Internal%20(reference)%20links.md">Internal (reference) links</a> between two documents. To link to an anchor on the same note, use the _Add link_ dialog (<kbd>Ctrl</kbd>+<kbd>K</kbd>) and select _Headings & anchors_ at its top instead.\ No newline at end of filediff --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 bef82dfc54..7427df768c 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@@ -12,7 +12,7 @@ Inside a <a class="reference-link" href="Content%20tabs.md">Content tabs</a> bloThe 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.-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.+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.The _Paste_ submenu of the context menu offers two more ways to insert a copied reference:@@ -21,10 +21,23 @@ The _Paste_ submenu of the context menu offers two more ways to insert a copiedIn a browser, the context menu of the text editor opens only when right-clicking selected text. Elsewhere the browser shows its own menu.+## Linking to a heading++Since v0.107.0, a link to a heading of the same note can be created from the _Add link_ dialog:++* 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.+* 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.+## Following a referenceClicking 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.+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 _Jump to heading_ there, or _Open note_ for other blocks.+## Including the referenced blocksTo show the referenced blocks inside another note, right-click the link in a note being edited and select _Convert link to note excerpt_, or paste the copied reference with _Paste_ → _Paste reference as an excerpt_. The include shows only the referenced blocks, not the rest of the note, and marks them with an _Excerpt_ badge in its title. It starts at the _Full_ 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.diff --git a/docs/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.md b/docs/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.mdindex 7f49dd7886..983e518d7e 100644--- a/docs/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.md+++ b/docs/User Guide/User Guide/Note Types/Text/Links/Internal (reference) links.md@@ -5,7 +5,7 @@ You can open an internal link by clicking it. You can also see a read-only previSince v0.107.0, clicking an internal link while editing a text note shows its popup instead, as clicking an external link does:-* _Open note_ opens the linked note, or _Open attachment_ for a link to an attachment.+* _Open note_ opens the linked note, or _Open attachment_ for a link to an attachment. A link to a heading of the same note reads _Jump to heading_ instead.* <span class="tn-icon cke cke-trilium-copy"></span> _Copy URL_ copies the address of the link.* <span class="tn-icon cke cke-pencil"></span> _Edit link_ changes the link, as described below.* <span class="tn-icon cke cke-unlink"></span> _Unlink_ turns the link into plain text.diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 970d58fb2b..241ec5fb34 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -30,9 +30,12 @@ export type { ContentEmbedHost } from "./plugins/content_embed/content_embed.js"export type { AttachmentLinkChange } from "./plugins/referencelink.js";export type { ChildNoteHost } from "./plugins/child_note.js";export {- getAnchorNames, getLinkAtSelection, replaceLinkAtSelection+ getAnchorNames, getHeadings, getLinkAtSelection, replaceLinkAtSelection} from "./plugins/internallink.js";-export type { LinkAtSelection, LinkDialogRequest } from "./plugins/internallink.js";+export type {+ DocumentHeading, LinkAtSelection, LinkDialogRequest+} from "./plugins/internallink.js";+export { assignBlockId } from "./plugins/block_reference/block_reference_editing.js";export type { default as TriliumEmojiMention, EmojiSuggestion } from "./plugins/mention/emoji_mention.js";export type { default as TriliumSlashCommands, SlashCommandConfig, SlashCommandDefinition, SlashCommandItem } from "./plugins/mention/slash_commands.js";export type { MentionHostedFeed, MentionHostedList, MentionHostedListState } from "./plugins/mention/types.js";diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.tsindex d5d9a00e77..58754c54ed 100644--- a/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference.spec.ts@@ -9,6 +9,7 @@ import { createTestEditor, createTestEditorOf } from "../../../test/editor-kit.jimport 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";const PLUGINS = [Essentials, Paragraph, Heading, BlockQuote, CodeBlock, List, Table, BlockReference@@ -171,6 +172,26 @@ describe("BlockReference", () => {});});+ describe("assignBlockId", () => {+ it("gives a block a new id outside the undo history, and returns an id it has", async () => {+ const editor = await createTestEditor(PLUGINS);+ setModelData(editor.model,+ "<paragraph>one[]</paragraph><heading1 blockId=\"a\">two</heading1>");+ editor.execute("insertText", { text: "!" });++ const id = assignBlockId(editor.model, getBlock(editor, 0));+ expect(id).toMatch(/^[A-Za-z0-9]{12}$/);+ expect(getBlock(editor, 0).getAttribute("blockId")).toBe(id);+ expect(assignBlockId(editor.model, getBlock(editor, 0))).toBe(id);+ expect(assignBlockId(editor.model, getBlock(editor, 1))).toBe("a");++ // The first undo takes back the typing, not the id.+ editor.execute("undo");+ expect(editor.getData()).toBe(+ `<p data-trilium-block-id="${id}">one</p><h2 data-trilium-block-id="a">two</h2>`);+ });+ });+describe("duplicate ids", () => {it("removes the id from a pasted copy", async () => {const editor = await createTestEditor(PLUGINS);diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.tsindex 046e368cae..a88747789e 100644--- a/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference_editing.ts@@ -240,6 +240,21 @@ function getBlocksById(model: Model, excluded: Set<ModelElement>) {return blocks;}+/** The id of `block`, which gets a new id first if it has none. */+export function assignBlockId(model: Model, block: ModelElement): string {+ const id = block.getAttribute(BLOCK_ID);+ if (typeof id === "string") {+ return id;+ }++ const newId = generateBlockId();+ // Not an undo step: the id is invisible, so undoing it would seem to do nothing.+ model.enqueueChange({ isUndoable: false }, (writer) => {+ writer.setAttribute(BLOCK_ID, newId, block);+ });+ return newId;+}+/** A new random block id. */export function generateBlockId() {const bytes = crypto.getRandomValues(new Uint8Array(BLOCK_ID_LENGTH));diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.tsindex e0edf33ec4..4c4ca9af57 100644--- a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.ts+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.spec.ts@@ -1,7 +1,9 @@import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest";import { applyTabs, getTabTitle } from "../tabs/tabs_read_only.js";-import { getBlockRangeElements, showBlockReference } from "./block_reference_read_only.js";+import {+ getBlockRangeElements, showAnchor, showBlockReference+} from "./block_reference_read_only.js";const SPACER = "<div style=\"height: 1000px\"></div>";@@ -156,6 +158,28 @@ describe("showBlockReference", () => {});});+describe("showAnchor", () => {+ it("centers and flashes the block that holds an anchor, or the anchor itself", () => {+ const scroller = mountScroller(SPACER+ + "<details><summary>s</summary><p style=\"height: 100px\">"+ + "<strong><a id=\"a"b\"></a>held</strong></p></details>"+ + SPACER + "<span id=\"loose\">loose</span>" + SPACER);++ expect(showAnchor(scroller, "a\"b")).toBe(true);+ expect(scroller.querySelector("details")?.open).toBe(true);+ const paragraph = scroller.querySelector("p");+ expect(paragraph?.getBoundingClientRect().top)+ .toBeCloseTo(scroller.getBoundingClientRect().top + 150);+ expect(getFlashed(scroller)).toEqual([ "held" ]);++ expect(showAnchor(scroller, "loose")).toBe(true);+ expect(getFlashed(scroller)).toEqual([ "held", "loose" ]);++ expect(showAnchor(scroller, "missing")).toBe(false);+ expect(scrollBy).toHaveBeenCalledTimes(2);+ });+});+describe("getBlockRangeElements", () => {it("returns a single block, or the blocks between two in a list", () => {const container = buildContainer(diff --git a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.ts b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.tsindex b6ffee9140..c8a9287082 100644--- a/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.ts+++ b/packages/ckeditor5/src/plugins/block_reference/block_reference_read_only.ts@@ -9,6 +9,8 @@ const FLASH_CLASS = "block-reference-flash";const FLASH_DURATION_MS = 1500;/** The smallest gap above the shown blocks, as a share of the height of their scroll container. */const MIN_TOP_GAP = 0.15;+/** The elements that `showAnchor()` flashes when they hold the anchor. */+const ANCHOR_BLOCKS = "p, h1, h2, h3, h4, h5, h6, li, dt, dd, pre, blockquote, figure, td, th";/*** Scrolls to the blocks that `value`, a `block` link parameter, points at in `container` and@@ -32,6 +34,25 @@ export function showBlockReference(container: Element, value: string) {return !!start && !!end;}+/**+ * Scrolls to the element whose `id` is `name` in `container`, such as an anchor, and flashes the+ * block that holds it, as {@link showBlockReference} does. Returns `false` when it is missing.+ */+export function showAnchor(container: Element, name: string) {+ // Exact comparison: an anchor name can hold characters that a CSS selector does not allow.+ const anchor = Array.from(container.querySelectorAll("[id]"))+ .find((element) => element.id === name);+ if (!anchor) {+ return false;+ }++ const block = anchor.closest(ANCHOR_BLOCKS) ?? anchor;+ reveal(block);+ scrollToBlocks(block, block);+ flashBlocks([ block ]);+ return true;+}+/** Flashes `elements` for a moment. */export function flashBlocks(elements: Element[]) {for (const element of elements) {diff --git a/packages/ckeditor5/src/plugins/internallink.spec.ts b/packages/ckeditor5/src/plugins/internallink.spec.tsindex 37fe0a17e3..82240b4253 100644--- a/packages/ckeditor5/src/plugins/internallink.spec.ts+++ b/packages/ckeditor5/src/plugins/internallink.spec.ts@@ -1,14 +1,15 @@import {- _getModelData as getModelData, _setModelData as setModelData, Bold, Bookmark, ButtonView,- ClassicEditor, CodeBlock, ContextualBalloon, Essentials, keyCodes, type KeystrokeHandler,- Link, LinkEditing, LinkUI, Paragraph+ _getModelData as getModelData, _setModelData as setModelData, BlockQuote, Bold, Bookmark,+ ButtonView, ClassicEditor, CodeBlock, ContextualBalloon, Essentials, Heading, keyCodes,+ type KeystrokeHandler, Link, LinkEditing, LinkUI, Paragraph} from "ckeditor5";import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../test/editor-kit.js";import { createLinkEmbedHost } from "../../test/link-embed-kit.js";+import BlockReferenceEditing from "./block_reference/block_reference_editing.js";import InternalLinkPlugin, {- COMMAND_NAME, getAnchorNames, getLinkAtSelection, type LinkDialogRequest,+ COMMAND_NAME, getAnchorNames, getHeadings, getLinkAtSelection, type LinkDialogRequest,replaceLinkAtSelection} from "./internallink.js";import LinkEmbedEditing from "./link_embed/link_embed_editing.js";@@ -198,6 +199,30 @@ describe("the anchors of the document", () => {});});+describe("the headings of the document", () => {+ it("lists the headings with text in order, with their level, text and block id", async () => {+ const editor = await createTestEditor([+ Essentials, Paragraph, Bold, Heading, BlockQuote, BlockReferenceEditing,+ InternalLinkPlugin+ ]);+ setModelData(editor.model, "<heading1>Intro[]</heading1><paragraph>text</paragraph>"+ + "<blockQuote><heading2 blockId=\"a\"> Nested <$text bold=\"true\">part</$text>"+ + "</heading2></blockQuote><heading3> </heading3>"+ + "<heading3>Deep<softBreak></softBreak>down</heading3>");+ const root = editor.model.document.getRoot();+ const quote = root?.getChild(2);++ expect(getHeadings(editor)).toStrictEqual([+ { element: root?.getChild(0), level: 1, text: "Intro", blockId: undefined },+ {+ element: quote?.is("element") && quote.getChild(0),+ level: 2, text: "Nested part", blockId: "a"+ },+ { element: root?.getChild(4), level: 3, text: "Deep down", blockId: undefined }+ ]);+ });+});+describe("the link at the selection", () => {let editor: ClassicEditor;let getTitle: ReturnType<typeof vi.fn>;diff --git a/packages/ckeditor5/src/plugins/internallink.ts b/packages/ckeditor5/src/plugins/internallink.tsindex 17c376f35d..b4b18f3ae2 100644--- a/packages/ckeditor5/src/plugins/internallink.ts+++ b/packages/ckeditor5/src/plugins/internallink.ts@@ -2,9 +2,10 @@ import {BookmarkEditing, ButtonView, Command, ContextualBalloon, findAttributeRange, IconLink,IconPencil, LinkUI, ModelLiveRange, Plugin} from 'ckeditor5';-import type { Editor, LinkCommand, ModelRange, View } from 'ckeditor5';+import type { Editor, LinkCommand, ModelElement, ModelRange, View } from 'ckeditor5';import HostedBalloon from '../hosted_balloon.js';import internalLinkIcon from '../icons/trilium.svg?raw';+import { BLOCK_ID } from './block_reference/block_reference_editing.js';import {getLinkWidgetMode, getSelectedLinkWidget, type LinkDisplayMode} from './link_embed/link_embed_commands.js';@@ -27,6 +28,16 @@ export interface InternalLinkDialogOptions {display?: LinkDisplayMode;}+/** A heading of the document. */+export interface DocumentHeading {+ element: ModelElement;+ /** 1 for `heading1`, up to 6 for `heading6`. */+ level: number;+ text: string;+ /** The block id of the heading, if it has one. */+ blockId?: string;+}+/** The request that the editor passes to the host's link dialog. */export interface LinkDialogRequest extends InternalLinkDialogOptions {/** The element to render the dialog into, which the editor owns and places at the caret. */@@ -294,6 +305,42 @@ export function getAnchorNames(editor: Editor): string[] {return [ ...names ].sort((a, b) => a.localeCompare(b));}+/** The headings of the document that have text, in document order. */+export function getHeadings(editor: Editor): DocumentHeading[] {+ const model = editor.model;+ const root = model.document.getRoot() as ModelElement;+ const headings: DocumentHeading[] = [];++ for (const item of model.createRangeIn(root).getItems()) {+ if (!item.is('element')) {+ continue;+ }++ const level = /^heading([1-6])$/.exec(item.name)?.[1];+ if (!level) {+ continue;+ }++ // An inline element, such as a soft break, separates words.+ let text = '';+ for (const child of model.createRangeIn(item).getItems()) {+ text += child.is('$textProxy') ? child.data : ' ';+ }++ text = text.replace(/\s+/g, ' ').trim();+ if (text) {+ headings.push({+ element: item,+ level: Number(level),+ text,+ blockId: item.getAttribute(BLOCK_ID) as string | undefined+ });+ }+ }++ return headings;+}+function findLinkAtSelection(editor: Editor): { href: string; range: ModelRange } | null {const model = editor.model;const reference = getSelectedReference(editor);diff --git a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.tsindex 9c210f216b..82b1017e4f 100644--- a/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts+++ b/packages/ckeditor5/src/plugins/link_embed/link_embed_toolbar.ts@@ -275,7 +275,8 @@ class LinkEmbedEditLinkButton extends Plugin {/*** A {@link ButtonView} rendered as an `<a target="_blank">` so a click opens the* URL in a new tab. Reuses CKEditor's `ck-link-toolbar__preview` styling for- * visual parity with the built-in link toolbar.+ * visual parity with the built-in link toolbar. Like CKEditor's preview button, it fires+ * `navigate` on a click, whose listener can cancel opening the URL.*/export class LinkEmbedPreviewButtonView extends ButtonView {declare href: string | undefined;@@ -293,6 +294,14 @@ export class LinkEmbedPreviewButtonView extends ButtonView {href: bind.to("href"),target: "_blank",rel: "noopener noreferrer"+ },+ on: {+ click: bind.to((event) => {+ if (this.href) {+ this.fire<LinkEmbedPreviewNavigateEvent>("navigate", this.href,+ () => event.preventDefault());+ }+ })}});@@ -302,3 +311,12 @@ export class LinkEmbedPreviewButtonView extends ButtonView {}}}++/**+ * Fired by a click on a `LinkEmbedPreviewButtonView`, with its `href` and a function that cancels+ * opening it.+ */+export type LinkEmbedPreviewNavigateEvent = {+ name: "navigate";+ args: [ href: string, cancel: () => void ];+};diff --git a/packages/ckeditor5/src/plugins/note_link_toolbar.spec.ts b/packages/ckeditor5/src/plugins/note_link_toolbar.spec.tsindex e1248afb15..854517fa32 100644--- a/packages/ckeditor5/src/plugins/note_link_toolbar.spec.ts+++ b/packages/ckeditor5/src/plugins/note_link_toolbar.spec.ts@@ -1,11 +1,12 @@import {- _getModelData as getModelData, _setModelData as setModelData, ButtonView, type ClassicEditor,- ContextualBalloon, Essentials, Link, LinkUI, Paragraph, type ToolbarView,- WidgetToolbarRepository+ _getModelData as getModelData, _setModelData as setModelData, Bookmark, ButtonView,+ type ClassicEditor, ContextualBalloon, Essentials, Heading, Link, LinkUI, Paragraph,+ type ToolbarView, WidgetToolbarRepository} from "ckeditor5";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../test/editor-kit.js";+import BlockReferenceEditing from "./block_reference/block_reference_editing.js";import { LinkEmbedPreviewButtonView } from "./link_embed/link_embed_toolbar.js";import NoteLinkToolbar, { UNLINK_REFERENCE_COMMAND } from "./note_link_toolbar.js";@@ -44,6 +45,9 @@ describe("NoteLinkToolbar", () => {expect(preview.tooltip).toBe(false);linkTo(ATTACHMENT);expect(preview.label).toBe("Open attachment");+ // An editor that names no note has no heading of its own to jump to.+ linkTo(`${NOTE}?block=x`);+ expect(preview.label).toBe("Open note");for (const href of [ "https://a.example", "#rootless", "#anchor" ]) {linkTo(href);@@ -128,6 +132,79 @@ describe("NoteLinkToolbar", () => {});});+describe("links within the note", () => {+ it("jumps to an anchor, and reads Jump to heading for a heading of the same note", async () => {+ const editor = await createTestEditor([+ Essentials, Paragraph, Heading, Bookmark, Link, BlockReferenceEditing, NoteLinkToolbar+ ], {+ getNoteId: () => "abc",+ referenceLink: { getTitle: async () => "Target", getTitleSync: () => "Target" }+ });+ const preview = editor.ui.componentFactory.create("linkPreview") as ButtonView;+ const content = "<heading1 blockId=\"h\">[]Intro</heading1>"+ + "<paragraph blockId=\"p\"><bookmark bookmarkId=\"top\"></bookmark>text</paragraph>";+ // The caret enters the link after the content is loaded, so the anchors are known.+ const linkTo = (href: string) => {+ setModelData(editor.model,+ `${content}<paragraph><$text linkHref="${href}">foo</$text></paragraph>`);+ editor.model.change((writer) => {+ const link = editor.model.document.getRoot()?.getChild(2);+ if (link) writer.setSelection(link, 1);+ });+ return preview.label;+ };++ expect([+ "#root/x/abc?block=h", "#root/def?block=h", "#root/abc?block=p",+ "#root/abc?block=gone", "#top", "#gone", "https://a.example/#top"+ ].map(linkTo)).toStrictEqual([+ "Jump to heading", "Open note", "Open note", "Open note", "Jump to anchor", "#gone",+ "https://a.example/#top"+ ]);++ // The editor follows a link into the note in place, flashing what it links to.+ const navigate = (href: string) => {+ const cancel = vi.fn();+ preview.fire("navigate", href, cancel);+ return [ cancel.mock.calls.length, takeFlashed(editor) ];+ };+ linkTo("#top");+ expect(navigate("#top")).toEqual([ 1, [ "text" ] ]);+ linkTo("#root/x/abc?block=h");+ expect(navigate("#root/x/abc?block=h")).toEqual([ 1, [ "Intro" ] ]);+ linkTo("#root/def?block=h");+ expect(navigate("#root/def?block=h")).toEqual([ 0, [] ]);++ const referencePreview =+ editor.ui.componentFactory.create("referenceLinkPreview") as ButtonView;+ referencePreview.render();+ const click = () => {+ const event = new MouseEvent("click", { cancelable: true });+ referencePreview.element?.dispatchEvent(event);+ return [ event.defaultPrevented, takeFlashed(editor) ];+ };+ // Without a reference, the button has no address to follow.+ expect(click()).toEqual([ false, [] ]);+ setModelData(editor.model, content.replace("[]", "")+ + "<paragraph>[<reference href=\"#root/abc?block=h\"></reference>]</paragraph>");+ expect(referencePreview.label).toBe("Jump to heading");+ expect(click()).toEqual([ true, [ "Intro" ] ]);+ const cancel = vi.fn();+ referencePreview.fire("navigate", "#root/def", cancel);+ expect(cancel).not.toHaveBeenCalled();+ });+});++/** The text of the blocks that flash in `editor`, which stop flashing. */+function takeFlashed(editor: ClassicEditor) {+ const flashed = [ ...editor.editing.view.getDomRoot()?.querySelectorAll(+ ".block-reference-flash") ?? [] ];+ for (const element of flashed) {+ element.classList.remove("block-reference-flash");+ }+ return flashed.map((element) => element.textContent);+}+describe("the provider of note links", () => {afterEach(() => {vi.restoreAllMocks();diff --git a/packages/ckeditor5/src/plugins/note_link_toolbar.ts b/packages/ckeditor5/src/plugins/note_link_toolbar.tsindex e018a5ff9a..7623f9d52f 100644--- a/packages/ckeditor5/src/plugins/note_link_toolbar.ts+++ b/packages/ckeditor5/src/plugins/note_link_toolbar.ts@@ -1,19 +1,26 @@import {- ButtonView, Command, type Editor, IconUnlink, LinkUI, type ModelElement, Plugin,- WidgetToolbarRepository+ BookmarkEditing, ButtonView, Command, type Editor, IconUnlink, LinkUI, type ModelElement,+ Plugin, WidgetToolbarRepository} from 'ckeditor5';+import { BLOCK_ID } from './block_reference/block_reference_editing.js';+import { showAnchor, showBlockReference } from './block_reference/block_reference_read_only.js';import { createCopyUrlButton } from './copy_link_url.js';import InternalLinkPlugin from './internallink.js';-import { LinkEmbedPreviewButtonView } from './link_embed/link_embed_toolbar.js';-import { getAttachmentId, getReferenceTitleSync, getSelectedReference } from './referencelink.js';+import {+ LinkEmbedPreviewButtonView, type LinkEmbedPreviewNavigateEvent+} from './link_embed/link_embed_toolbar.js';+import {+ getAttachmentId, getNoteId, getReferenceTitleSync, getSelectedReference+} from './referencelink.js';export const UNLINK_REFERENCE_COMMAND = 'unlinkReference';/*** The toolbar of a link to a note. A link in the text shows the link toolbar of `LinkUI`, and a* reference link shows a widget toolbar with the same buttons. In both, the first button reads- * "Open note" instead of the address.+ * "Open note" instead of the address, or "Jump to heading" for a heading of the same note. An+ * anchor link reads "Jump to anchor".*/export default class NoteLinkToolbar extends Plugin {@@ -45,6 +52,11 @@ export default class NoteLinkToolbar extends Plugin {button.bind('href').to(this, 'referenceHref', href => href ?? undefined);button.bind('label').to(this, 'referenceHref',href => href ? getOpenLinkLabel(editor, href) : undefined);+ button.on<LinkEmbedPreviewNavigateEvent>('navigate', (_evt, href, cancel) => {+ if (jumpInNote(editor, href)) {+ cancel();+ }+ });return button;});@@ -74,10 +86,19 @@ export default class NoteLinkToolbar extends Plugin {if (editor.plugins.has(LinkUI)) {editor.plugins.get(LinkUI).registerLinksListProvider({label: editor.t('Internal link'),+ // Ahead of the provider of `BookmarkUI`, which reads an anchor link as its name.+ order: -1,getListItems: () => [],- getItem: href => NOTE_LINK.test(href)- ? { href, label: getOpenLinkLabel(editor, href) }- : null+ getItem: href => {+ if (getLinkedAnchor(editor, href)) {+ return { href, label: editor.t('Jump to anchor') };+ }++ return NOTE_LINK.test(href)+ ? { href, label: getOpenLinkLabel(editor, href) }+ : null;+ },+ navigate: ({ href }) => jumpInNote(editor, href)});}@@ -120,11 +141,56 @@ class UnlinkReferenceCommand extends Command {/** A link to a note or to an attachment of one, as opposed to a web address or an anchor. */const NOTE_LINK = /^#root(?:[/?]|$)/;-/** The text of the button that opens the note or attachment `href` points to. */+/** The text of the button that follows the link `href` to a note, an attachment or a heading. */function getOpenLinkLabel(editor: Editor, href: string) {+ const block = getLinkedBlock(editor, href);+ if (block && /^heading[1-6]$/.test(block.name)) {+ return editor.t('Jump to heading');+ }+return getAttachmentId(href) ? editor.t('Open attachment') : editor.t('Open note');}+/** The block of the note in the editor that `href` links to by its block id, or `null`. */+function getLinkedBlock(editor: Editor, href: string) {+ const blockId = new URLSearchParams(href.split('?')[1]).get('block');+ if (!blockId || getNoteId(href) !== editor.config.get('getNoteId')?.()) {+ return null;+ }++ const root = editor.model.document.getRoot() as ModelElement;+ for (const item of editor.model.createRangeIn(root).getItems()) {+ if (item.is('element') && item.getAttribute(BLOCK_ID) === blockId) {+ return item;+ }+ }++ return null;+}++/** The anchor of the document that `href` links to, or `null`. */+function getLinkedAnchor(editor: Editor, href: string) {+ if (!href.startsWith('#') || !editor.plugins.has(BookmarkEditing)) {+ return null;+ }++ return editor.plugins.get(BookmarkEditing).getElementForBookmarkId(href.slice(1));+}++/**+ * Scrolls to the block or the anchor of the note that `href` links to and flashes it, as a link+ * within a page does. Returns whether `href` links into the note.+ */+function jumpInNote(editor: Editor, href: string) {+ const root = editor.editing.view.getDomRoot() as HTMLElement;+ const block = getLinkedBlock(editor, href);+ if (block) {+ return showBlockReference(root, block.getAttribute(BLOCK_ID) as string);+ }++ return !!getLinkedAnchor(editor, href) && showAnchor(root, href.slice(1));+}+declare module 'ckeditor5' {interface PluginsMap {[NoteLinkToolbar.pluginName]: NoteLinkToolbar;diff --git a/packages/share-theme/src/content/in_page_links.spec.ts b/packages/share-theme/src/content/in_page_links.spec.tsnew file mode 100644index 0000000000..3ba86a09d4--- /dev/null+++ b/packages/share-theme/src/content/in_page_links.spec.ts@@ -0,0 +1,94 @@+// @vitest-environment happy-dom+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import setupInPageLinks from "./in_page_links.js";++const mocks = vi.hoisted(() => ({+ showAnchor: vi.fn(),+ showBlockReference: vi.fn()+}));+vi.mock("@triliumnext/ckeditor5/src/plugins/block_reference/block_reference_read_only.js", () => mocks);++describe("setupInPageLinks", () => {+ beforeEach(() => {+ history.replaceState(null, "", "/share/page");+ document.body.innerHTML = "<div id=\"content\">"+ + "<h2 data-trilium-block-id=\"h\">Intro</h2>"+ + "<p><a id=\"top\"></a><a id=\"café\"></a><a id=\"%E0%A4%A\"></a>text</p>"+ + "</div>";+ setupInPageLinks();+ });++ afterEach(() => {+ vi.clearAllMocks();+ document.body.innerHTML = "";+ });++ /** Clicks a link to `href` in the content, and returns whether the click was taken. */+ function click(href: string, init: MouseEventInit = {}) {+ const link = document.createElement("a");+ link.setAttribute("href", href);+ document.getElementById("content")?.append(link);+ // Read once the content has seen the click, then kept from happy-dom, which follows a+ // link that no listener took.+ let isTaken = false;+ document.addEventListener("click", (event) => {+ isTaken = event.defaultPrevented;+ event.preventDefault();+ }, { once: true });+ link.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, ...init }));+ return isTaken;+ }++ it("scrolls to blocks of the page and flashes them, with the address of the link", async () => {+ expect(click("./page?block=h")).toBe(true);+ await vi.waitFor(() => expect(mocks.showBlockReference)+ .toHaveBeenCalledExactlyOnceWith(document.body, "h"));+ expect(location.search).toBe("?block=h");++ // A fragment link keeps `block` from the address, and goes to its anchor all the same.+ expect(click("#top")).toBe(true);+ await vi.waitFor(() => expect(mocks.showAnchor)+ .toHaveBeenLastCalledWith(document.body, "top"));+ expect(location.href).toBe("http://localhost:3000/share/page?block=h#top");+ const entries = history.length;+ mocks.showAnchor.mockClear();+ expect(click("#top")).toBe(true);+ await vi.waitFor(() => expect(mocks.showAnchor).toHaveBeenCalledOnce());+ expect(history.length).toBe(entries);++ expect(click("#caf%C3%A9")).toBe(true);+ await vi.waitFor(() => expect(mocks.showAnchor)+ .toHaveBeenLastCalledWith(document.body, "café"));+ expect(click("#%E0%A4%A")).toBe(true);+ await vi.waitFor(() => expect(mocks.showAnchor)+ .toHaveBeenLastCalledWith(document.body, "%E0%A4%A"));+ });++ it("leaves other links, modified clicks and missing targets to the browser", () => {+ expect([+ click("./other?block=h"),+ click("https://example.com/share/page?block=h"),+ click("./page?block=h:gone"),+ click("./page?x=1"),+ click("#missing"),+ click("./page?block=h", { ctrlKey: true }),+ click("./page?block=h", { button: 1 })+ ]).toEqual([ false, false, false, false, false, false, false ]);++ // A click outside a link, and one that a script of the page took already.+ document.querySelector("h2")?.click();+ const link = document.createElement("a");+ link.href = "./page?block=h";+ document.getElementById("content")?.append(link);+ link.addEventListener("click", (event) => event.preventDefault(), { once: true });+ link.click();+ expect(location.search).toBe("");+ expect(mocks.showBlockReference).not.toHaveBeenCalled();+ });++ it("does nothing on a page without content", () => {+ document.body.innerHTML = "";+ expect(() => setupInPageLinks()).not.toThrow();+ });+});diff --git a/packages/share-theme/src/content/in_page_links.ts b/packages/share-theme/src/content/in_page_links.tsnew file mode 100644index 0000000000..7969bb4f8b--- /dev/null+++ b/packages/share-theme/src/content/in_page_links.ts@@ -0,0 +1,62 @@+import { resolveBlockReference } from "@triliumnext/commons/src/lib/block_reference.js";++/** Loads the module, shared with the app, that scrolls to blocks and anchors and flashes them. */+const loadBlockJump = () =>+ import("@triliumnext/ckeditor5/src/plugins/block_reference/block_reference_read_only.js");++type BlockJump = Awaited<ReturnType<typeof loadBlockJump>>;++/**+ * Makes a link to blocks of the page, or to an element of it by `id` such as an anchor, scroll to+ * its target and flash it, as the app does. The address changes as for a link within the page.+ */+export default function setupInPageLinks() {+ document.getElementById("content")?.addEventListener("click", (event) => {+ const link = (event.target as Element).closest<HTMLAnchorElement>("a[href]");+ if (!link || event.defaultPrevented || event.button !== 0+ || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) {+ return;+ }++ const show = getInPageTarget(link);+ if (show) {+ event.preventDefault();+ if (link.href !== location.href) {+ history.pushState(null, "", link.href);+ }+ void loadBlockJump().then(show);+ }+ });+}++/** What shows the target of `link` when it is on this page, or `null`. */+function getInPageTarget(link: HTMLAnchorElement): ((jump: BlockJump) => unknown) | null {+ const url = new URL(link.href);+ if (url.origin !== location.origin || url.pathname !== location.pathname) {+ return null;+ }++ // Checked first: a fragment link keeps the parameters of the page, `block` included.+ if (url.hash) {+ const name = decodeFragment(url.hash);+ return document.getElementById(name) ? (jump) => jump.showAnchor(document.body, name) : null;+ }++ const block = url.searchParams.get("block");+ if (!block) {+ return null;+ }++ // A broken range loads the page, which shows the block found.+ const { start, end } = resolveBlockReference(document.body, block);+ return start && end ? (jump) => jump.showBlockReference(document.body, block) : null;+}++/** The `id` that the fragment `hash` names, decoded as the browser does. */+function decodeFragment(hash: string) {+ try {+ return decodeURIComponent(hash.slice(1));+ } catch {+ return hash.slice(1);+ }+}diff --git a/packages/share-theme/src/index.spec.ts b/packages/share-theme/src/index.spec.tsindex 9321028931..508517fcde 100644--- a/packages/share-theme/src/index.spec.ts+++ b/packages/share-theme/src/index.spec.ts@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({whenActivated: vi.fn((callback: () => void) => callback()),setupMath: vi.fn(),setupMermaid: vi.fn(),+ setupInPageLinks: vi.fn(),applyTableScroll: vi.fn(),applyStickyTableHeaders: vi.fn(),applyListItemAlignment: vi.fn(),@@ -36,6 +37,7 @@ vi.mock("./page/speculation.js", () => ({}));vi.mock("./content/math.js", () => ({ default: mocks.setupMath }));vi.mock("./content/mermaid.js", () => ({ default: mocks.setupMermaid }));+vi.mock("./content/in_page_links.js", () => ({ default: mocks.setupInPageLinks }));vi.mock("./content/app_view.js", () => ({ default: mocks.setupAppView }));vi.mock("./content/note_view.js", () => ({ default: "mountNoteView" }));vi.mock("./content/collection_view.js", () => ({ default: "mountCollection" }));@@ -118,6 +120,7 @@ describe("share theme entry", () => {const content = document.getElementById("content");expect(mocks.setupMermaid).toHaveBeenCalledOnce();expect(mocks.setupMath).toHaveBeenCalledOnce();+ expect(mocks.setupInPageLinks).toHaveBeenCalledOnce();expect(mocks.enhanceLinkPreviews).toHaveBeenCalledWith(document.body);expect(mocks.applyTableScroll.mock.calls).toEqual([ [ content ], [ content?.querySelector(".include-note") ] ]);diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.tsindex 1513909e48..a2698d165e 100644--- a/packages/share-theme/src/index.ts+++ b/packages/share-theme/src/index.ts@@ -19,6 +19,7 @@ import "./content/link_embed.css";import "./content/full_height.css";import "./content/app_view.css";import setupCodeCopy from "./content/code_copy.js";+import setupInPageLinks from "./content/in_page_links.js";import setupMath from "./content/math.js";import setupAppView from "./content/app_view.js";import setupMermaid from "./content/mermaid.js";@@ -82,6 +83,7 @@ function setupTextNote() {const diagrams = $try(setupMermaid);$try(setupMath);$try(setupCodeCopy);+ $try(setupInPageLinks);$try(() => enhanceLinkPreviews(document.body));$try(setupTableScroll);$try(setupStickyTableHeaders);diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tsindex 70707831c4..16eb1e62a6 100644--- a/packages/trilium-core/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -228,7 +228,7 @@ describe("content_renderer", () => {const nested = getContent(note, { embedsAsReferenceLinks: true }).content as string;expect(content.match(/Top/g)).toHaveLength(2);- expect(nested).toContain(`href="./blkSelf"`);+ expect(nested).toContain(`href="./blkSelf?block=top"`);expect(nested).not.toContain("include-note");});@@ -925,6 +925,35 @@ describe("content_renderer", () => {expect(externalLink.text).toBe("Ext");});+ it("keeps the blocks that a link points at, inside an included note too", () => {+ buildShareNote({ id: "blockTarget1", title: "Target" });+ buildShareNote({+ id: "extBlocks001",+ title: "Ext",+ "#shareExternalLink": "https://example.com/page"+ });+ buildShareNote({+ id: "includedNote",+ content: "<p><a class=\"reference-link\" href=\"#root/blockTarget1?block=c\">"+ + "Old</a></p>"+ });+ const note = buildShareNote({+ id: "note",+ content: "<p><a href=\"#root/x/blockTarget1?block=a:b%20c\">range</a>"+ + "<a href=\"#root/extBlocks001?block=a\">ext</a>"+ + "<a href=\"#root/blockTarget1?viewMode=source\">plain</a></p>"+ + "<section class=\"include-note\" data-note-id=\"includedNote\"></section>"+ });++ const links = parse(String(getContent(note).content)).querySelectorAll("a");+ expect(links.map((link) => [ link.getAttribute("href"), link.text ])).toEqual([+ [ "./blockTarget1?block=a:b%20c", "range" ],+ [ "https://example.com/page", "ext" ],+ [ "./blockTarget1", "plain" ],+ [ "./blockTarget1?block=c", "Target" ]+ ]);+ });+it("links a note with either external link label out, as the navigation does", () => {buildShareNote({"id": "legacyExt0001",diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tsindex 9bf6a1eaaa..cc93e0d957 100644--- a/packages/trilium-core/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -1,6 +1,6 @@import type { PreviewThemeSlot } from "@triliumnext/codemirror/src/code_preview.js";import {- BLOCK_ID_ATTRIBUTE, CANVAS_ATTACHMENT_MIME, CONTENT_EMBED_KIND_ATTRIBUTE,+ BLOCK_ID_ATTRIBUTE, CANVAS_ATTACHMENT_MIME, CONTENT_EMBED_KIND_ATTRIBUTE, encodeBlockParameter,getAttachmentEmbedHref, getDrawingPictureTitle, getEmbedKey,getNestedEmbedOptions, getNoteEmbedHref, isHttpUrl, isImageAttachmentRole, MIME_TYPE_AUTO,type MimeType, normalizeMimeTypeForCKEditor, readLinkPreviewData, renderLinkEmbedHtml,@@ -823,7 +823,11 @@ function handleAttachmentLink(linkEl: HTMLElement, href: string, getNote: GetNotconst linkedNote = getNote(noteId);if (linkedNote) {const link = getShareLink(linkedNote, sanitize.sanitizeUrl);- linkEl.setAttribute("href", link.href);+ // A link to blocks keeps them, which the page of the note scrolls to and flashes.+ const block = new URLSearchParams(href.split("?")[1]).get("block");+ linkEl.setAttribute("href", block && !link.isExternal+ ? `${link.href}?block=${encodeBlockParameter(block)}`+ : link.href);if (link.isExternal) {linkEl.setAttribute("target", "_blank");linkEl.setAttribute("rel", "noopener noreferrer");@@ -854,8 +858,15 @@ function cleanUpReferenceLinks(linkEl: HTMLElement, href: string, getNote: GetNo// `handleAttachmentLink()` removes the `href` of a link whose target is missing.let noteId = "";+ // The link of an included note was rewritten already, to `./shareId` and its parameters.if (linkEl.hasAttribute("href")) {- noteId = href.startsWith("#") ? getNoteIdFromLink(href) : href.slice(href.lastIndexOf("/") + 1);+ if (href.startsWith("#")) {+ noteId = getNoteIdFromLink(href);+ } else if (href.startsWith("./")) {+ noteId = getNoteIdFromLink(href.slice(2));+ } else {+ noteId = href.slice(href.lastIndexOf("/") + 1);+ }}const note = noteId ? getNote(noteId) : undefined;if (!note) {