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/code notes: implement text tools
Adorian Dorance30ecd0969a
diff --git a/apps/client/src/menus/code_editor_context_menu.spec.ts b/apps/client/src/menus/code_editor_context_menu.spec.tsnew file mode 100644index 0000000000..3dcf46aad7--- /dev/null+++ b/apps/client/src/menus/code_editor_context_menu.spec.ts@@ -0,0 +1,167 @@+import { EditorSelection } from "@codemirror/state";+import VanillaCodeMirror from "@triliumnext/codemirror";+import { afterEach, describe, expect, it, vi } from "vitest";++const h = vi.hoisted(() => ({+ dateFormat: "DD.MM.YY",+ contentLanguage: "tr" as string | null+}));++vi.mock("../services/i18n.js", () => ({ t: (key: string) => key }));+vi.mock("../services/options.js", () => ({+ default: { get: (name: string) => (name === "customDateTimeFormat" ? h.dateFormat : "") }+}));+vi.mock("../utils/formatters.js", () => ({ resolveContentLanguage: () => h.contentLanguage }));++import type { CommandNames } from "../components/app_context.js";+import { buildCodeEditorContextMenuItems } from "./code_editor_context_menu.js";+import type { MenuCommandItem, MenuItem } from "./context_menu.js";++let editors: VanillaCodeMirror[] = [];++afterEach(() => {+ for (const editor of editors) {+ editor.destroy();+ }+ editors = [];+ h.dateFormat = "DD.MM.YY";+ h.contentLanguage = "tr";+});++describe("buildCodeEditorContextMenuItems", () => {+ it("offers nothing outside a code editor or in a read-only one", async () => {+ // An element that only looks like an editor.+ const foreign = document.createElement("div");+ foreign.className = "cm-editor";+ const plain = document.createElement("div");+ await expect(buildCodeEditorContextMenuItems(plain)).resolves.toBeNull();+ await expect(buildCodeEditorContextMenuItems(null)).resolves.toBeNull();+ await expect(buildCodeEditorContextMenuItems(foreign)).resolves.toBeNull();+ const readOnly = createEditor("text", { from: 0, to: 4 }, true);+ await expect(buildCodeEditorContextMenuItems(lineOf(readOnly))).resolves.toBeNull();+ });++ it("offers the line operations, the line removals and the text transforms", async () => {+ const items = await buildItems(createEditor("text", { from: 0, to: 4 }));++ expect(titles(items)).toEqual([+ "code_editor_context_menu.line_operations",+ "code_editor_context_menu.line_removal",+ "code_editor_context_menu.text_transform"+ ]);+ expect(titles(submenu(items, 0))).toEqual([+ "code_editor_context_menu.sort_ascending",+ "code_editor_context_menu.sort_descending",+ "---",+ "code_editor_context_menu.shuffle_lines",+ "code_editor_context_menu.reverse_lines",+ "code_editor_context_menu.deduplicate_lines"+ ]);+ expect(titles(submenu(items, 1))).toEqual([+ "code_editor_context_menu.trim_leading",+ "code_editor_context_menu.trim_trailing",+ "code_editor_context_menu.trim_both",+ "---",+ "code_editor_context_menu.remove_blank_lines"+ ]);+ expect(titles(submenu(items, 2))).toEqual([+ "code_editor_context_menu.to_uppercase",+ "code_editor_context_menu.to_lowercase",+ "code_editor_context_menu.to_sentence_case",+ "code_editor_context_menu.to_title_case",+ "---",+ "code_editor_context_menu.remove_diacritics"+ ]);+ expect(rows(submenu(items, 1)).map((row) => row.tooltip)).toEqual([+ "code_editor_context_menu.trim_leading_tooltip",+ "code_editor_context_menu.trim_trailing_tooltip",+ "code_editor_context_menu.trim_both_tooltip",+ undefined+ ]);+ expect(rows(items.flatMap((_, index) => submenu(items, index)))+ .every((row) => row.enabled && row.uiIcon)).toBe(true);+ });++ it("disables every row while nothing is selected", async () => {+ const items = await buildItems(createEditor("text", { from: 2, to: 2 }));++ expect(rows(items).map((row) => row.enabled)).toEqual([ false, false, false ]);+ expect(rows(items.flatMap((_, index) => submenu(items, index)))+ .some((row) => row.enabled)).toBe(false);+ });++ it("sorts the selected lines by the user's date format, and focuses the editor", async () => {+ const editor = createEditor("01.10.26\n30.09.26\nend", { from: 0, to: 17 });+ const focus = vi.spyOn(editor, "focus");++ run(submenu(await buildItems(editor), 0), "code_editor_context_menu.sort_ascending");++ expect(editor.getText()).toBe("30.09.26\n01.10.26\nend");+ expect(focus).toHaveBeenCalled();+ });++ it("sorts without a date format or a content language of the user's", async () => {+ h.dateFormat = "";+ h.contentLanguage = null;+ const editor = createEditor("01.10.26\n30.09.26\nend", { from: 0, to: 17 });++ run(submenu(await buildItems(editor), 0), "code_editor_context_menu.sort_descending");++ expect(editor.getText()).toBe("30.09.26\n01.10.26\nend");+ });++ it("removes lines and transforms the selected text by the content language", async () => {+ const editor = createEditor("a\n\nb istanbul", { from: 0, to: 12 });+ run(submenu(await buildItems(editor), 1), "code_editor_context_menu.remove_blank_lines");+ expect(editor.getText()).toBe("a\nb istanbul");++ editor.dispatch({ selection: EditorSelection.range(4, 12) });+ const focus = vi.spyOn(editor, "focus");+ run(submenu(await buildItems(editor), 2), "code_editor_context_menu.to_uppercase");+ expect(editor.getText()).toBe("a\nb İSTANBUL");+ expect(focus).toHaveBeenCalled();+ });+});++function createEditor(text: string, selection: { from: number; to: number }, readOnly = false) {+ const parent = document.createElement("div");+ document.body.append(parent);+ const editor = new VanillaCodeMirror({ parent, readOnly });+ editor.setText(text);+ editor.dispatch({ selection: EditorSelection.range(selection.from, selection.to) });+ editors.push(editor);+ return editor;+}++/** A line of `editor`, as the right-click target. */+function lineOf(editor: VanillaCodeMirror) {+ return editor.contentDOM.querySelector(".cm-line") ?? editor.contentDOM;+}++async function buildItems(editor: VanillaCodeMirror) {+ const items = await buildCodeEditorContextMenuItems(lineOf(editor));+ if (!items) {+ throw new Error("expected the text tools");+ }+ return items;+}++function rows(items: MenuItem<CommandNames>[]) {+ return items.filter((item): item is MenuCommandItem<CommandNames> => !("kind" in item));+}++function titles(items: MenuItem<CommandNames>[]) {+ return items.map((item) => ("kind" in item ? "---" : item.title));+}++function submenu(items: MenuItem<CommandNames>[], index: number) {+ return rows(items)[index]?.items ?? [];+}++function run(items: MenuItem<CommandNames>[], title: string) {+ const row = rows(items).find((item) => item.title === title);+ if (!row?.handler) {+ throw new Error(`expected a row titled ${title}`);+ }+ row.handler(row, new MouseEvent("click"));+}diff --git a/apps/client/src/menus/code_editor_context_menu.ts b/apps/client/src/menus/code_editor_context_menu.tsnew file mode 100644index 0000000000..0c027438fa--- /dev/null+++ b/apps/client/src/menus/code_editor_context_menu.ts@@ -0,0 +1,116 @@+import type { LineOperation, LineOperationOptions, TextTransform } from "@triliumnext/commons";++import type { CommandNames } from "../components/app_context.js";+import { t } from "../services/i18n.js";+import options from "../services/options.js";+import { resolveContentLanguage } from "../utils/formatters.js";+import type { MenuCommandItem, MenuItem } from "./context_menu.js";+import { submenuItem } from "./context_menu_utils.js";++/**+ * The text tools of a code editor's right-click menu, which change the selected lines or text:+ * the _Line operations_, _Line removal_ and _Text transform_ submenus. Their rows are disabled+ * while nothing is selected.+ *+ * Returns `null` when `element` is not in an editable code editor.+ */+export async function buildCodeEditorContextMenuItems(+ element: Element | null | undefined+): Promise<MenuItem<CommandNames>[] | null> {+ const root = element?.closest(".cm-editor");+ if (!(root instanceof HTMLElement)) {+ return null;+ }++ // Imported here: the menu is set up at startup, and a code editor loads CodeMirror later.+ const {+ default: CodeMirror, hasSelectedText, runLineOperation, runTextTransform+ } = await import("@triliumnext/codemirror");+ const editor = CodeMirror.findFromDOM(root);+ if (!(editor instanceof CodeMirror) || editor.state.readOnly) {+ return null;+ }++ const isEnabled = hasSelectedText(editor.state);+ const toolOptions = getTextToolOptions();+ const lineItem = (+ title: string, uiIcon: string, operation: LineOperation, tooltip?: string+ ): MenuCommandItem<CommandNames> => ({+ title,+ uiIcon,+ tooltip,+ enabled: isEnabled,+ handler: () => {+ runLineOperation(editor, operation, toolOptions);+ editor.focus();+ }+ });+ const transformItem = (+ title: string, uiIcon: string, transform: TextTransform+ ): MenuCommandItem<CommandNames> => ({+ title,+ uiIcon,+ enabled: isEnabled,+ handler: () => {+ runTextTransform(editor, transform, toolOptions);+ editor.focus();+ }+ });++ const lineOperations: MenuItem<CommandNames>[] = [+ lineItem(t("code_editor_context_menu.sort_ascending"), "bx bx-sort-a-z", "sortAscending"),+ lineItem(t("code_editor_context_menu.sort_descending"), "bx bx-sort-z-a", "sortDescending"),+ { kind: "separator" },+ lineItem(t("code_editor_context_menu.shuffle_lines"), "bx bx-shuffle", "shuffle"),+ lineItem(t("code_editor_context_menu.reverse_lines"), "bx bx-transfer-alt bx-rotate-90",+ "reverse"),+ lineItem(t("code_editor_context_menu.deduplicate_lines"), "bx bx-layer-minus",+ "deduplicate")+ ];+ const lineRemoval: MenuItem<CommandNames>[] = [+ lineItem(t("code_editor_context_menu.trim_leading"), "bx bx-align-left", "trimLeading",+ t("code_editor_context_menu.trim_leading_tooltip")),+ lineItem(t("code_editor_context_menu.trim_trailing"), "bx bx-align-right", "trimTrailing",+ t("code_editor_context_menu.trim_trailing_tooltip")),+ lineItem(t("code_editor_context_menu.trim_both"), "bx bx-align-middle", "trimBoth",+ t("code_editor_context_menu.trim_both_tooltip")),+ { kind: "separator" },+ lineItem(t("code_editor_context_menu.remove_blank_lines"), "bx bx-collapse-vertical",+ "removeBlankLines")+ ];+ const textTransforms: MenuItem<CommandNames>[] = [+ transformItem(t("code_editor_context_menu.to_uppercase"), "bx bx-chevrons-up", "upperCase"),+ transformItem(t("code_editor_context_menu.to_lowercase"), "bx bx-chevrons-down",+ "lowerCase"),+ transformItem(t("code_editor_context_menu.to_sentence_case"), "bx bx-text",+ "sentenceCase"),+ transformItem(t("code_editor_context_menu.to_title_case"), "bx bx-heading", "titleCase"),+ { kind: "separator" },+ transformItem(t("code_editor_context_menu.remove_diacritics"), "bx bx-eraser",+ "removeDiacritics")+ ];++ return [+ submenuItem({+ title: t("code_editor_context_menu.line_operations"),+ uiIcon: "bx bx-list-ul"+ }, lineOperations),+ submenuItem({+ title: t("code_editor_context_menu.line_removal"),+ uiIcon: "bx bx-list-minus"+ }, lineRemoval),+ submenuItem({+ title: t("code_editor_context_menu.text_transform"),+ uiIcon: "bx bx-font"+ }, textTransforms)+ ];+}++/** The locale of the note content, and the user's own date format for sorting by date. */+function getTextToolOptions(): LineOperationOptions {+ const customDateTimeFormat = options.get("customDateTimeFormat");+ return {+ locale: resolveContentLanguage(null) ?? undefined,+ dateFormats: customDateTimeFormat ? [ customDateTimeFormat ] : []+ };+}diff --git a/apps/client/src/menus/note_context_menu.spec.ts b/apps/client/src/menus/note_context_menu.spec.tsindex d70c7879b5..d9f24f0031 100644--- a/apps/client/src/menus/note_context_menu.spec.ts+++ b/apps/client/src/menus/note_context_menu.spec.ts@@ -23,6 +23,9 @@ vi.mock("../services/utils.js", () => ({reuseAcrossHotReloads: <T>(_hot: unknown, create: () => T) => create()}));vi.mock("./context_menu.js", () => ({ default: { show: vi.fn() } }));+vi.mock("./code_editor_context_menu.js", () => ({+ buildCodeEditorContextMenuItems: vi.fn(async () => null)+}));vi.mock("./table_context_menu.js", () => ({buildTableContextMenuSections: vi.fn(async () => null),hasTableCellSelection: vi.fn(async () => false)@@ -32,6 +35,7 @@ import { buildBlockReferenceMenuItems } from "../services/block_reference.js";import { copyHtml, copyTextWithToast } from "../services/clipboard_ext.js";import server from "../services/server.js";import { setEditorNoteId } from "../widgets/react/NoteStore.js";+import { buildCodeEditorContextMenuItems } from "./code_editor_context_menu.js";import contextMenu, { type MenuCommandItem, type MenuItem } from "./context_menu.js";import {buildTableContextMenuSections,@@ -261,6 +265,36 @@ describe("buildNoteContextMenuItems", () => {});});+ it("puts the text tools of a code editor below the clipboard rows", async () => {+ const line = document.createElement("div");+ vi.mocked(buildCodeEditorContextMenuItems).mockResolvedValueOnce([+ { title: "LINES" }, { title: "CASE" }+ ]);+ const host = browserLikeHost({+ paste: { enabled: true, run: vi.fn(), runAsPlainText: vi.fn(), read: vi.fn() }+ });++ const items = await build({ isEditable: true, element: line }, host);++ expect(buildCodeEditorContextMenuItems).toHaveBeenCalledWith(line);+ expect(titles(items)).toEqual([+ "electron_context_menu.cut",+ "electron_context_menu.copy",+ "electron_context_menu.paste",+ "---",+ "LINES",+ "CASE",+ "---",+ "electron_context_menu.search_online",+ "electron_context_menu.search_in_trilium"+ ]);+ });++ it("looks for text tools only over an element that takes typing", async () => {+ await build({ isEditable: false, element: document.createElement("div") });+ expect(buildCodeEditorContextMenuItems).not.toHaveBeenCalled();+ });+it("puts the table sections around the clipboard rows and hands them the element", async () => {const cell = document.createElement("td");vi.mocked(buildTableContextMenuSections).mockResolvedValueOnce({diff --git a/apps/client/src/menus/note_context_menu.ts b/apps/client/src/menus/note_context_menu.tsindex 79c231bee2..4b7cdc73be 100644--- a/apps/client/src/menus/note_context_menu.ts+++ b/apps/client/src/menus/note_context_menu.ts@@ -7,6 +7,7 @@ import { t } from "../services/i18n.js";import options from "../services/options.js";import server from "../services/server.js";import utils from "../services/utils.js";+import { buildCodeEditorContextMenuItems } from "./code_editor_context_menu.js";import contextMenu, { type MenuItem } from "./context_menu.js";import { splitMenuItem } from "./context_menu_utils.js";import { buildTableContextMenuSections, hasTableCellSelection } from "./table_context_menu.js";@@ -139,6 +140,9 @@ export async function buildNoteContextMenuItems(const blockReferenceItems = target.isEditable? await buildBlockReferenceMenuItems(target.element, host.paste): null;+ const codeEditorItems = target.isEditable+ ? await buildCodeEditorContextMenuItems(target.element)+ : null;const hasText = !hasCellSelection && target.selectionText.trim().length > 0;const hasClipboardContent = hasText || hasCellSelection;@@ -250,6 +254,10 @@ export async function buildNoteContextMenuItems(...tableSections.delete, { kind: "separator" }, tableSections.select);}+ if (codeEditorItems) {+ items.push({ kind: "separator" }, ...codeEditorItems);+ }+if (hasText) {const { selectionText } = target;const shortenedSelection = selectionText.length > 15diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 0ab1c27afc..21b4dea82a 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -4835,5 +4835,27 @@},"hide_keyboard_button": {"title": "Hide keyboard"+ },+ "code_editor_context_menu": {+ "line_operations": "Line operations",+ "sort_ascending": "Sort ascending",+ "sort_descending": "Sort descending",+ "shuffle_lines": "Shuffle lines",+ "reverse_lines": "Reverse line order",+ "deduplicate_lines": "Deduplicate lines",+ "line_removal": "Line removal",+ "trim_leading": "Trim leading",+ "trim_leading_tooltip": "Removes the whitespace at the start of each line",+ "trim_trailing": "Trim trailing",+ "trim_trailing_tooltip": "Removes the whitespace at the end of each line",+ "trim_both": "Trim both",+ "trim_both_tooltip": "Removes the whitespace at the start and at the end of each line",+ "remove_blank_lines": "Remove blank lines",+ "text_transform": "Text transform",+ "to_uppercase": "To uppercase",+ "to_lowercase": "To lowercase",+ "to_sentence_case": "To sentence case",+ "to_title_case": "To title case",+ "remove_diacritics": "Remove diacritics"}}diff --git a/apps/server/src/assets/help/help_content.json b/apps/server/src/assets/help/help_content.jsonindex 78b2c5c287..40d42e4825 100644--- a/apps/server/src/assets/help/help_content.json+++ b/apps/server/src/assets/help/help_content.json@@ -155,7 +155,7 @@"_help_NdowYOC1GFKS": "<p>Tables are a powerful feature for <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a> notes, since editing them is generally easy.</p><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:176/204;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/2_Tables_image.png\" width=\"176\" height=\"204\"></figure><p>To create a table, simply press the table button and select with the mouse the desired amount of columns and rows, as indicated in the adjacent figure.</p><p>Since v0.107.0, the same menu starts with an <em>Insert table…</em> item, for a table larger than the grid or to type its size instead:</p><ol><li>Click the <span class=\"tn-icon cke cke-table\"></span>button and select <em>Insert table…</em>. A small form opens at the cursor.</li><li>Enter the number of <em>Columns</em> (up to 100) and <em>Rows</em> (up to 1000). The table can have at most 5000 cells in total, for example 1000 rows of 5 columns.</li><li>Press <em>Insert</em> or <kbd>Enter</kbd>.</li></ol><p>To close the form without inserting a table, press <kbd>Esc</kbd> or click outside it. From the keyboard, <kbd>Tab</kbd> moves between <em>Insert table…</em> and the grid while the menu is open.</p><p>On the <a class=\"reference-link\" href=\"#root/_help_RDslemsQ6gCp\">Mobile Frontend</a>, the <span class=\"tn-icon cke cke-table\"></span>button opens the form directly, without the grid.</p><h2>Formatting toolbar</h2><p>When a table is selected, a special formatting toolbar will appear:</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/3_Tables_image.png\" width=\"384\" height=\"100\"><h2>Context menu</h2><p>Since v0.106.0, right-clicking anywhere inside a table opens a context menu with the most common table operations:</p><ul><li><em>Insert row above</em> and <em>Insert row below</em> insert a blank row next to the row of the current cell. When the selection spans multiple rows, the same number of rows is inserted.</li><li><em>Insert column to the left</em> and <em>Insert column to the right</em> work the same way for columns.</li><li>Since v0.107.0, <em>Set as header</em> or <em>Set header up to this row</em>, depending on the selection, turns rows into header rows, which always start at the top of the table:<ul><li><em>Set as header</em> shows when the selection starts at the first row, and makes every selected row a header row.</li><li><em>Set header up to this row</em> shows when the selection is in a single row below the first, and makes that row and every row above it header rows.</li><li>Neither shows when the selection spans several rows below the first.</li><li>A check mark shows that the rows are already header rows. Choosing the item again turns them, and every header row below them, back into regular rows. For example, in a table with five header rows, choosing <em>Set header up to this row</em> on the third row leaves only the first two as header rows.</li></ul></li><li><em>Merge cells</em> merges the selected cells into one. The selected cells must form a rectangle.</li><li><em>Split cell</em> splits each selected cell in two, either <em>Vertically</em> or <em>Horizontally</em>. <em>Unmerge cells</em>, in the same submenu, turns each merged cell in the selection back into the single cells it covers, keeping its content in the top-left one; cells that are not merged stay as they are.</li><li><em>Distribute columns evenly</em> splits the combined width of the columns the selection touches equally between them. The other columns and the width of the table stay as they are. It needs a selection spanning at least two columns; a merged cell counts for every column it covers.</li><li><em>Cut</em>, <em>Copy</em> and <em>Copy as Markdown</em> act on the selected cells. Since v0.107.0, <em>Copy</em> and <em>Paste</em> open submenus with their variants, such as <em>Copy as Markdown</em> and <em>Paste as plain text</em>; clicking <em>Copy</em> or <em>Paste</em> itself still copies or pastes:<ul><li>Cutting or copying produces a smaller table holding just the selected cells. Pasting it over a cell selection replaces those cells; pasting elsewhere inserts it as a table of its own. Cutting clears the cells without removing rows or columns.</li><li><em>Copy as Markdown</em> converts the selected cells to a Markdown table. A selected header row becomes the Markdown header; without one, an empty header row is emitted, since Markdown tables require one.</li></ul></li><li>Since v0.107.0, <em>Paste rows above</em> and <em>Paste rows below</em>, in the <em>Paste</em> submenu, paste the clipboard as new rows next to the row of the current cell, instead of over the cells from the cursor on. They show only when the selection is in a single row, and, like <em>Paste</em>, only where the clipboard can be read:<ul><li>A copied table becomes one new row for each of its rows, filled from the first column. When it has more columns than the table, the table gains columns, as with a regular paste. Other content goes in the first cell of a single new row.</li><li>The new rows are selected afterwards.</li><li>When merged cells join the row to others, the new rows go above or below that whole block of rows.</li></ul></li><li><em>Sort</em>, below the clipboard section, sorts the rows by the column of the current cell, in <em>Ascending</em> or <em>Descending</em> order. See <a href=\"#sorting-rows\">Sorting rows</a>.</li><li><em>Delete row</em> and <em>Delete column</em>, below <em>Sort</em>, remove every row or column the selection touches, even when only some of their cells are selected.</li><li><em>Delete table</em> removes the whole table and leaves an empty paragraph in its place. In a table nested inside another, only the inner table is removed.</li><li>Since v0.107.0, <em>Select</em>, below <em>Delete table</em>, selects the cells of every row (<em>Row</em>) or column (<em>Column</em>) the selection touches, or every cell of the table (<em>Table</em>). Unlike the <span class=\"tn-icon cke cke-drag-handle\"></span>button, which selects the table as a whole, <em>Table</em> selects its cells, so cell operations such as <em>Merge cells</em> apply to all of them. In a table nested inside another, <em>Table</em> selects only the cells of the inner table.</li></ul><p>Right-clicking a cell that is not part of the current selection moves the cursor there first, so the menu always applies to the cell under the pointer.</p><aside class=\"admonition note\"><p>In the browser, Trilium's menu replaces the browser's own context menu inside tables. To reach the browser's menu (for example for its spell checking suggestions), hold <kbd>Shift</kbd> while right-clicking. The desktop application is unaffected, since its menu already includes the spelling suggestions. In the browser, the menu also offers <em>Paste</em> only when the page can read the clipboard, which requires a secure (HTTPS) context and your permission; otherwise, paste with <kbd>Ctrl</kbd>+<kbd>V</kbd>.</p></aside><h2>Navigating a table</h2><ul><li>Using the mouse:<ul><li>Click on a cell to focus it.</li><li>Click the <span class=\"tn-icon cke cke-return-arrow\"></span> button at the top or the bottom of a table to insert an empty paragraph near it.</li><li>Click the <span style=\"--tn-color:hsl(0,0%,60%);color:hsl(0,0%,60%);\"><span class=\"tn-icon cke cke-drag-handle\"></span></span> button at the top-left of the table to select it entirely (for easy copy-pasting or cutting) or drag and drop it to relocate the table.</li></ul></li><li>Using the keyboard:<ul><li>Use the arrow keys on the keyboard to easily navigate between cells.</li><li>It's also possible to use <kbd>Tab</kbd> to go to the next cell and Shift+Tab to go to the previous cell.</li><li>Unlike arrow keys, pressing <kbd>Tab</kbd> at the end of the table (last row, last column) will create a new row automatically.</li><li>To select multiple cells, hold <kbd>Shift</kbd> while using the arrow keys.</li></ul></li><li>Using touch:<ul><li>Since v0.107.0, touching a table outlines the cell with the cursor, or the selected cells, and shows a handle at each corner of the outline.</li><li>To select multiple cells, drag one of the handles across the table. The cell at the opposite corner stays selected, so the selection grows or shrinks as the finger moves. The note and wide tables scroll when the handle reaches the edge of the screen.</li></ul></li></ul><h2>Resizing cells</h2><ul><li>Columns can be resized by hovering the mouse over the border of two adjacent cells and dragging it.</li><li>To give several columns the same width, select cells across them and choose <em>Distribute columns evenly</em> from the <span class=\"tn-icon cke cke-table-column\"></span>button of the formatting toolbar or from the <a href=\"#context-menu\">context menu</a>.</li><li>By default, the row height is not adjustable using the mouse, but it can be configured from the cell settings (see below).</li><li>To adjust exactly the width (in pixels or percentages) of a cell, select the <span class=\"tn-icon cke cke-table-cell-properties\"></span> button.</li></ul><h3>Resizing with touch</h3><p>Since v0.107.0, touching a table shows a bar at the bottom of the note, above the formatting toolbar on mobile. The bar has a segment for each column of the table, with a divider at the end of each column. Only the divider of the column with the cursor is a handle that resizes; the other dividers only mark where the columns meet, so a swipe across them scrolls instead. When several cells are selected, each column they cover has a handle.</p><ul><li>To resize a column, place the cursor in one of its cells or tap its segment, then drag its handle. The table grows or shrinks with the column, and scrolls when the handle reaches the edge of the screen. The column snaps to its starting width and to the widths of the columns beside it.</li><li>To cancel a resize, drag the handle back to where it started, or touch the screen with a second finger.</li><li>To give a column and the next one the same width, double-tap the handle between them.</li><li>To select a column, tap its segment. To open the column menu, touch and hold the segment.</li><li>To scroll a wide table sideways, swipe along the bar.</li></ul><p>A wide table scrolls a little past its end, so the handle of its last column stays away from the edge of the screen, where a swipe navigates back.</p><h2>Wide tables</h2><p>Since v0.107.0, a table can be wider than the <a class=\"reference-link\" href=\"#root/_help_t596jLvPrqkS\">Content width</a>. Such a table scrolls sideways, while the rest of the note keeps its width.</p><ul><li>A new table is as wide as the content. To make it wider, drag the right border of its last column past the edge of the content. The border snaps to the edge and holds there briefly, so the table is easy to bring back to the width of the content.</li><li>To set an exact width, enter a percentage above <code>100%</code> or a width in pixels in the <span class=\"tn-icon cke cke-table-properties\"></span> <a href=\"#table-properties\">table properties</a>.</li><li>A table whose content needs more room than the note, such as a pasted table with many columns, also scrolls instead of stretching the note.</li><li>Wide tables scroll the same way in read-only notes and on shared pages.</li><li>When printing or exporting to PDF, a wide table is shrunk to fit the page.</li></ul><p>Tables inside other blocks, such as block quotes, admonitions, collapsible blocks, columns or tabs, are limited to the width of their block and do not scroll.</p><h3>Mobile support</h3><p>On the <a class=\"reference-link\" href=\"#root/_help_RDslemsQ6gCp\">Mobile Frontend</a>, a table keeps the width it has on a desktop and scrolls sideways, instead of squeezing its columns into the width of the screen. The full width of a table is the <em>Max content width</em> set in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Appearance</em> → <em>Content Width</em> on the mobile device, 1200 pixels by default. For example, a table set to <code>50%</code> is 600 pixels wide.</p><p>To resize columns on mobile, use the bar described in <a href=\"#resizing-with-touch\">Resizing with touch</a>.</p><h2>Long tables</h2><p>Since v0.107.0, the header rows of a table stay visible at the top of the note while you scroll through the rest of the table, and leave with the end of the table. This also works in read-only notes, on shared pages and in wide tables.</p><p>To turn rows into header rows, use <em>Set as header</em> in the <a href=\"#context-menu\">context menu</a>, or <em>Header row</em> in the <span class=\"tn-icon cke cke-table-row\"></span> button of the formatting toolbar.</p><p>To let header rows scroll away with the rest of the table, turn off <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text Notes</em> → <em>Features</em> → <em>Use sticky header rows for tables</em>. The setting applies to the current device only, and shared pages keep their sticky header rows.</p><h2>Inserting new rows and new columns</h2><ul><li>To insert a new column, click on a desired location, then press the <span class=\"tn-icon cke cke-table-column\"></span> button from the formatting toolbar and select <em>Insert column left or right.</em></li><li>To insert a new row, click on a desired location, then press the <span class=\"tn-icon cke cke-table-row\"></span> button and select <em>Insert row above</em> or <em>below</em>.<ul><li>A quicker alternative to creating a new row while at the end of the table is to press the <kbd>Tab</kbd> key.</li></ul></li><li>Both operations are also available in the <a href=\"#context-menu\">context menu</a>, which inserts as many rows or columns as the selection spans.</li></ul><h2>Moving rows and columns</h2><p>Since v0.106.0, rows and columns can be reordered with the keyboard:</p><ul><li><kbd>Alt</kbd>+<kbd>Up</kbd> and <kbd>Alt</kbd>+<kbd>Down</kbd> move the rows touched by the selection up or down.</li><li><kbd>Alt</kbd>+<kbd>Left</kbd> and <kbd>Alt</kbd>+<kbd>Right</kbd> move the columns touched by the selection left or right.</li></ul><p>Merged cells are never split by a move. The rows or columns held together by a merged cell travel as one block, and moving toward such a block jumps over it entirely.</p><p>When the table has a header row, a header row moved below the header area becomes a regular row, and a regular row moved into the header area becomes a header row. Header columns behave the same way.</p><p>Outside of tables, <kbd>Alt</kbd>+<kbd>Left</kbd> and <kbd>Alt</kbd>+<kbd>Right</kbd> keep navigating the note history, and <kbd>Alt</kbd>+<kbd>Up</kbd> and <kbd>Alt</kbd>+<kbd>Down</kbd> keep moving the current paragraph.</p><h2>Sorting rows</h2><p>Since v0.107.0, the rows of a table can be sorted by the values of one column:</p><ul><li>To sort all the rows, place the cursor in any cell of the column to sort by, then select <em>Sort</em> → <em>Ascending</em> or <em>Descending</em> from the <a href=\"#context-menu\">context menu</a>. The same items are in the <span class=\"tn-icon bx bx-sort-alt-2\"></span>button of the formatting toolbar.</li><li>To sort only some of the rows, select their cells in the column to sort by, then sort the same way. Sorting is not available while the selection spans more than one column.</li></ul><p>Header rows always stay at the top of the table and are never sorted. A sort can be undone with <kbd>Ctrl</kbd>+<kbd>Z</kbd>.</p><h3>How values are compared</h3><p>Each cell is read as plain text, so formatting does not affect the order. Trilium then detects what kind of value the cell holds:</p><figure class=\"table\"><table><thead><tr><th>Kind</th><th>Examples</th><th>Compared by</th></tr></thead><tbody><tr><td>Time</td><td><code>15:02</code>, <code>15:02:38</code>, <code>3:02 PM</code></td><td>The time of day.</td></tr><tr><td>Date</td><td><code>2026-09-30</code>, <code>2026-09-30 15:02</code>, <code>30 September 2026</code>, <code>Wednesday, 30 September 2026</code>, <code>2026-09-30T15:02:38+03:00</code></td><td>The date and time.</td></tr><tr><td>Number</td><td><code>12</code>, <code>-3.5</code>, <code>1,234.56</code>, <code>$ 12.04</code>, <code>21 RON</code>, <code>24.5m</code></td><td>The numeric value.</td></tr><tr><td>Text</td><td>Anything else.</td><td>Alphabetically, ignoring case, with numbers inside the text in numeric order (<code>Item 9</code> before <code>Item 10</code>). Accents count, so <code>a</code> and <code>á</code> differ.</td></tr><tr><td>Empty</td><td>An empty cell, or one holding only spaces.</td><td>Not compared. Empty cells always go last.</td></tr></tbody></table></figure><p>Ascending order puts times first, then dates, numbers and text. Descending order reverses it. Empty cells go last in both directions.</p><p>Numbers, dates and times with the same value are ordered by their text, so <code>5 apples</code> comes before <code>5 pears</code>. Rows whose cells hold the same text, ignoring case, keep their relative order.</p><ul><li>Dates are also recognized in the formats of the note's language, such as <code>30.09.2026</code> or <code>30. September 2026</code> for German, and in the format chosen in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Text Notes</em> → <em>Editor</em> → <em>Date/time format</em> for <a href=\"#root/_help_CohkqWQC1iBv\">inserting the date and time</a>.</li><li>A number can start with a currency symbol, such as <code>$</code>, <code>€</code> or <code>£</code>. Whatever follows the number, such as a unit, is ignored, so units are not converted: <code>1 km</code> sorts before <code>500 m</code>. A cell that starts with letters, such as <code>RON 21</code>, is text.</li><li>The decimal separator follows the language of the note: <code>1.500</code> is one and a half in English, but one thousand five hundred in German. A comma or period that is not followed by exactly three digits is always read as a decimal separator, so <code>1,5</code> is one and a half in either language.</li><li>The language of the note set in the <a class=\"reference-link\" href=\"#root/_help_AlJ73vBCjWDw\">Status bar</a> via the <span class=\"tn-icon bx bx-globe\"></span> icon, or else the default content language. See <a class=\"reference-link\" href=\"#root/_help_veGu4faJErEM\">Content language & Right-to-left support</a>.</li></ul><h3>Merged cells</h3><p>Rows joined by a merged cell are kept together and move as one block. The block is sorted by the value in its first row. When the block has more than one cell in the sorted column, the other cells do not affect the order, and a message says so: <em>Some rows were sorted together because merged cells tie them to each other</em>.</p><p>When the selection covers only part of such a block, the whole block is sorted.</p><h2>Merging cells</h2><p>To merge two or more cells together, simply select them via drag & drop and press the <span class=\"tn-icon cke cke-table-merge-cell\"></span> button from the formatting toolbar.</p><p>More options are available by pressing the arrow next to it:</p><ul><li>Click on a single cell and select Merge cell up/down/right/left to merge with an adjacent cell.</li><li>Select <em>Merge selected cells</em> to merge the selected cells, the same as pressing the button itself.</li><li>Select <em>Split cell vertically</em> or <em>horizontally</em>, to split a cell into multiple cells (can also be used to undo a merge).</li><li>Select <em>Unmerge cells</em> to turn each merged cell in the selection back into the single cells it covers, keeping its content in the top-left one.</li></ul><p><em>Merge selected cells</em> and <em>Unmerge cells</em> are available since v0.107.0. Merging and splitting are also available by right-clicking the selected cells, via the <a href=\"#context-menu\">context menu</a>, where <em>Unmerge cells</em> is in the <em>Split cell</em> submenu.</p><h2>Table properties</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:312/311;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Tables_image.png\" width=\"312\" height=\"311\"></figure><p>The table properties can be accessed via the <span class=\"tn-icon cke cke-table-properties\"></span> button and allows for the following adjustments:</p><ul><li>Border (not the border of the cells, but the outer rim of the table), which includes the style (single, double), color and width.</li><li>The background color, with none set by default.</li><li>The width and height of the table in percentage (must end with <code>%</code>) or pixels (must end with <code>px</code>).</li><li>The alignment of the table.<ul><li>Left or right-aligned, case in which the text will flow next to it.</li><li>Centered, case in which text will avoid the table, regardless of the table width.</li></ul></li></ul><p>The table will immediately update to reflect the changes, but the <em>Save</em> button must be pressed for the changes to persist.</p><h2>Cell properties</h2><figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:320/386;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/1_Tables_image.png\" width=\"320\" height=\"386\"></figure><p>Similarly to table properties, the <span class=\"tn-icon cke cke-table-cell-properties\"></span> button opens a popup which adjusts the styling of one or more cells (based on the user's selection).</p><p>The following options can be adjusted:</p><ul><li>The border style, color and width (same as table properties), but applying to the current cell only.</li><li>The background color, with none set by default.</li><li>The width and height of the cell in percentage (must end with <code>%</code>) or pixels (must end with <code>px</code>).</li><li>The padding (the distance of the text compared to the cell's borders).</li><li>The alignment of the text, both horizontally (left, centered, right, justified) and vertically (top, middle or bottom).</li></ul><p>The cell will immediately update to reflect the changes, but the <em>Save</em> button must be pressed for the changes to persist.</p><h2>Border and background colors</h2><p>The border and background colors of tables and cells adapt to the <a href=\"#root/_help_Wy267RK4M69c\">theme</a>, the same way as <a href=\"#root/_help_Gr6xFaF6ioJ5\">text colors</a> do. A color picked from the palette, chosen with the color picker or typed in is shown in a lighter or darker shade that suits the current theme, so borders stay visible and text stays readable on the background. The hue stays the same, and the table keeps the color as it was picked.</p><p>Colors applied with older versions of Trilium are shown exactly as they were picked, until the note is next edited.</p><p>Older browsers that can't adapt colors show them exactly as they were picked.</p><h2>Caption</h2><p>Press the <span class=\"tn-icon cke cke-caption\"></span> button to insert a caption or a text description of the table, which is going to be displayed above the table.</p><h2>Table borders</h2><p>By default, tables will come with a predefined gray border.</p><p>To adjust the borders, follow these steps:</p><ol><li>Select the table.</li><li>In the floating panel, select the <em>Table properties</em> option (<span class=\"tn-icon cke cke-table-properties\"></span>).<ol><li>Look for the <em>Border</em> section at the top of the newly opened panel.</li><li>This will control the outer borders of the table.</li><li>Select a style for the border. Generally <em>Single</em> is the desirable option.</li><li>Select a color for the border.</li><li>Select a width for the border, expressed in pixels.</li></ol></li><li>Select all the cells of the table and then press the <em>Cell properties</em> option (<span class=\"tn-icon cke cke-table-cell-properties\"></span>).<ol><li>This will control the inner borders of the table, at cell level.</li><li>Note that it's possible to change the borders individually by selecting one or more cells, case in which it will only change the borders that intersect these cells.</li><li>Repeat the same steps as from step (2).</li></ol></li></ol><h3>Tables with invisible borders</h3><p>Tables can be set to have invisible borders in order to allow for basic layouts (columns, grids) of text or <a href=\"#root/_help_mT0HEkOsz6i1\">images</a> without the distraction of their border:</p><ol><li>First insert a table with the desired number of columns and rows.</li><li>Select the entire table.</li><li>In <em>Table properties</em>, set:<ol><li><em>Style</em> to <em>Single</em></li><li><em>Color</em> to <code>transparent</code></li><li>Width to <code>1px</code>.</li></ol></li><li>In Cell Properties, set the same as on the previous step.</li></ol><h2>Table indentation</h2><p>Since v0.104.1, tables can be indented as a block (the whole table moves, rather than just the content of a cell).</p><ol><li>Click the <span style=\"--tn-color:hsl(0,0%,60%);color:hsl(0,0%,60%);\"><span class=\"tn-icon cke cke-drag-handle\"></span></span> button to select the entire table. Otherwise, the indentation applies only to the current cell's content.</li><li>Press <kbd>Tab</kbd> to increase the indent, or <kbd>Shift</kbd>+<kbd>Tab</kbd> to decrease it. Alternatively, use the indentation buttons in the formatting toolbar.</li></ol><p>Markdown does not support indented tables, so the indentation is lost when converting to Markdown.</p><h2>Markdown import/export</h2><p>Simple tables are exported in GitHub-flavored Markdown format (e.g. a series of <code>|</code> items). If the table is found to be more complex (it contains HTML elements, has custom sizes or images), the table is converted to a HTML one instead.</p><p>Generally formatting loss should be minimal when exported to Markdown due to the fallback to HTML formatting.</p>","_help_pwc194wlRzcH": "<figure class=\"image image-style-align-right\"><img style=\"aspect-ratio:265/108;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/Text%20Snippets_image.png\" width=\"265\" height=\"108\"></figure><p>Text Snippets are closely related to <a class=\"reference-link\" href=\"#root/_help_KC1HB96bqqHX\">Templates</a>, but instead of defining the content of an entire note, text snippets are pieces of formatted text that can easily be inserted in a text note.</p><h2>Creating a text snippet</h2><p>In the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>: </p><ol><li>Right click a note where to place the text snippet.</li><li>Select <em>Insert child note</em>.</li><li>Select <em>More</em> → <em>Text snippet</em>.</li></ol><p>Afterwards, simply type in the content of the note the desired text. The text can be formatted in the same manner as a normal text note.</p><p>The title of the note will become the title of the template. Optionally, a description can be added in the <a class=\"reference-link\" href=\"#root/_help_OFXdgB2nNk1F\">Promoted Attributes</a> section.</p><h2>Inserting a snippet</h2><p>Once a snippet is created, there are two options to insert it:</p><ol><li>From the <a class=\"reference-link\" href=\"#root/_help_nRhnJkTT8cPs\">Formatting toolbar</a>, by looking for the <span class=\"tn-icon cke cke-trilium-template\"></span> button.</li><li>Using <a class=\"reference-link\" href=\"#root/_help_ZlN4nump6EbW\">Slash Commands</a>: <ol><li>To look for a specific template, start typing the name of the template (its title).</li><li>To look for all the templates, type <code>template</code>.</li></ol></li></ol><aside class=\"admonition tip\"><p>A newly created snippet doesn't appear? Generally it takes up to a few seconds to refresh the list of templates once you make a change.</p><p>If this doesn't happen, <a href=\"#root/_help_s8alTXmpFR61\">reload the application</a> and <a href=\"#root/_help_wy8So3yZZlH9\">report the issue</a>to us. </p></aside><h2>Limitations</h2><ul><li>Whenever a snippet is created, deleted or its title/description are modified, all the open text notes will need to be refreshed. This causes a slight flash for usually under a second, but it can cause some discomfort.</li><li>Unlike <a class=\"reference-link\" href=\"#root/_help_KC1HB96bqqHX\">Templates</a>, the snippets cannot be limited to a particular <a href=\"#root/_help_9sRHySam5fXb\">workspace</a>.</li></ul>","_help_fASfBrYnquKU": "<h2>Extended task states</h2><figure class=\"image image-style-align-left\"><img style=\"aspect-ratio:303/264;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Text/To-do%20Lists_image.png\" width=\"303\" height=\"264\"></figure><p>In Trilium, to-do items aren't limited to a simple \"done\" or \"not done.\" Tasks can also be marked as <em>in progress</em> (\"doing\"), <em>under consideration</em> (\"maybe\"), or <em>cancelled</em> (\"won't do\"), thus giving a more accurate picture of where things actually stand.</p><p>Right-click the checkbox and select the desired state. Alternatively, press <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Enter </kbd> to cycle through the task states. Tapping or left-clicking the checkbox will always toggle between \"None\" and \"Done\".</p><p>Task states are fully preserved when converting between <a class=\"reference-link\" href=\"#root/_help_iPIMuisry3hd\">Text</a> and <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> notes, in both directions.</p><h3>Customizing the extended task states</h3><p>Task states are customizable: you can reorder them, create new ones with different colors and symbols, or delete the ones you don't need. See <a class=\"reference-link\" href=\"#root/_help_i16PM6A7GXdU\">Customizing to-do task states</a> for more details.</p><h2>Keyboard shortcuts</h2><p>When at the beginning on an empty paragraph, type the following to insert a to-do list:</p><ul><li><code>[ ]</code> for an unchecked item</li><li><code>[x]</code> for a checked item</li></ul><p>Extended task states are supported as well, using its corresponding <em>Markdown symbol</em>. These are the defaults but they can be changed if needed (see <a class=\"reference-link\" href=\"#root/_help_i16PM6A7GXdU\">Customizing to-do task states</a>):</p><ul><li><code>[/]</code> for “Doing”.</li><li><code>[?]</code> for “Maybe”.</li><li><code>[-]</code> for “Cancelled”.</li></ul><p>To reorder the item under the cursor, press <kbd>Alt</kbd>+<kbd>Up</kbd> or <kbd>Alt</kbd>+<kbd>Down</kbd>. To reorder multiple items, select them first.</p><h2>See also</h2><ul><li>To-do lists are meant for small task lists. For more complicated, day-to-day task tracking consider using a <a class=\"reference-link\" href=\"#root/_help_CtBQqbwXDx1w\">Kanban Board</a> collection instead.</li></ul>",- "_help_6f9hih2hXXZk": "<p>Trilium supports creating \"code\" notes, i.e. notes which contain some sort of formal code - be it programming language (C++, JavaScript), structured data (JSON, XML) or other types of codes (CSS etc.).</p><p>This can be useful for a few things:</p><ul><li>computer programmers can store code snippets as notes with syntax highlighting</li><li>JavaScript code notes can be executed inside Trilium for some extra functionality<ul><li>we call such JavaScript code notes \"scripts\" – see <a class=\"reference-link\" href=\"#root/_help_CdNpE2pqjmI6\">Scripting</a></li></ul></li><li>JSON, XML etc. can be used as storage for structured data (typically used in conjunction with scripting)</li></ul><p>For shorter snippets of code that can be embedded in <a href=\"#root/_help_iPIMuisry3hd\">Text</a> notes, see <a href=\"#root/_help_QxEyIjRBizuC\">Code blocks</a>.</p><p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Code_image.jpg\"></p><h2>Creating a code note</h2><p>In the <a href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>, right-click a note and select <em>Insert child note</em> or <em>Insert note after</em>, then:</p><ul><li>To create a plain text code note, select <em>Code</em>.</li><li>To create a code note in a given language, hover <em>Code</em> and select the language. The list shows the languages enabled in the options (see below), and ends with <em>Configure code notes...</em>, which opens them.</li></ul><h2>Adjusting the language of a code note</h2><p>To change the language of a code note, look for the <span class=\"tn-icon bx bx-code\"></span> icon in the <a class=\"reference-link\" href=\"#root/_help_AlJ73vBCjWDw\">Status bar</a>. When clicked it will reveal the list of available languages (which can be customized according to the section below). The menu also features a search bar to quickly filter, and icons to visually distinguish some of the programming languages.</p><p>On the <a class=\"reference-link\" href=\"#root/_help_RDslemsQ6gCp\">Mobile Frontend</a>, the same list is available in the <a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a> → <em>Note settings</em> → <em>Change language mode</em>.</p><h2>Adjusting the list of languages</h2><p>Trilium supports syntax highlighting for many languages, but by default displays only some of them. The supported languages can be adjusted by going to <a href=\"#root/_help_4TIF1oA4VQRO\">Options</a>, then <em>Code Notes</em> and looking for the <em>Available MIME types in the dropdown</em> section. Simply check any of the items to add them to the list, or un-check them to remove them from the list.</p><p>Note that the list of languages is not immediately refreshed, you'd have to manually <a href=\"#root/_help_s8alTXmpFR61\">refresh the application</a>.</p><p>The list of languages is also shared with the <a href=\"#root/_help_QxEyIjRBizuC\">Code blocks</a> feature of <a href=\"#root/_help_iPIMuisry3hd\">Text</a> notes.</p><h2>Word wrap</h2><p>Long lines can be displayed on multiple lines:</p><ul><li>Globally for all code notes, from <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes.</em></li><li>For a particular note, by going to the menu in <a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a> and selecting <em>Word wrap</em> and selecting the appropriate option:<ul><li><em>Auto</em>, to respect the global word wrap for code notes.</li><li><em>On</em> or <em>Off</em>, to change the state of the word wrap for this note regardless of the global option.</li></ul></li></ul><aside class=\"admonition note\"><p>Word wrapping can also be adjusted at note level through the <code>#wrapLines</code> <a href=\"#root/_help_HI6GBBIduIgv\">label</a>, which can also be inherited.</p></aside><h2>Line numbers</h2><p>The numbers at the start of each line can be hidden from <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em> → <em>Editor</em> → <em>Line numbers</em>. The setting applies to every code editor, such as the source of a <a href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> note, and to code shown without its editor (see <em>Color schemes</em> below).</p><p>An included code note or an embedded code file can show or hide them on its own through the <em>Line numbers</em> submenu of its <em>More actions</em> menu, see <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>. Its <em>Auto</em> entry follows the setting.</p><h2>Adjusting options using the status bar</h2><p>The status bar at the bottom of the editor shows the current indentation settings and language. Clicking on the indentation indicator opens a menu with three sections:</p><ol><li><em>Indent Using</em> — switch between Spaces and Tabs (<code>#indentWithTabs</code>). If a per-note override is active, a \"Reset to default\" option appears.</li><li><em>Display Width</em> — choose from preset widths (1, 2, 3, 4, 6, 8). Changes are saved as a per-note <code>#tabWidth</code> label.</li><li><em>Re-indent Content To</em> — convert existing indentation to a different style. For example, re-indent a file from 4 spaces to 2 spaces, or from spaces to tabs. This rewrites the leading whitespace on every line while preserving alignment remainders.</li></ol><p>Clicking the language indicator lets you change the note's MIME type. As in the <em>Note type</em> selector, typing narrows the list of languages.</p><p>The same two menus are in the toolbar of a code note or a code file included in a text note, see <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</p><h3>Re-indentation</h3><p>When you re-indent content, the editor:</p><ul><li>Measures the visual column width of each line's leading whitespace using the current style</li><li>Calculates indent levels and any alignment remainder</li><li>Rebuilds the leading whitespace in the target style</li><li>Preserves non-leading whitespace, blank lines, and content without indentation</li></ul><h2>Color schemes</h2><p>Since Trilium 0.94.0 the colors of code notes can be customized by going <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → Code Notes and looking for the <em>Appearance</em> section.</p><p>A code note or a code file shown without its editor, such as in an <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>, on the cards of <a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a> or in a tooltip, uses the same colors and line numbers as the editor does. A printout uses the <em>Light theme</em>. A <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a> uses the VS Code light or dark theme, following the mode of the page.</p><aside class=\"admonition note\"><p><strong>Why are there only a few themes whereas the code block themes for text notes have a lot?</strong><br>The reason is that Code notes use a different technology than the one used in Text notes, and as such there is a more limited selection of themes. If you find a CodeMirror 6 (not 5) theme that you would like to use, let us know and we might consider adding it to the set of default themes. There is no possibility of adding new themes (at least for now), since the themes are defined in JavaScript and not at CSS level.</p></aside><h2>Programming ligatures</h2><p>If you see <code>!=</code> displayed as <code>≠</code> or <code>-></code> as <code>→</code> inside a code note, those are <em>font ligature</em>: the default monospace font draws certain character pairs as a single symbol. The underlying text is not changed by Trilium (unlike text notes which have <a class=\"reference-link\" href=\"#root/_help_oI7GoyilXXAr\">Automatic replacements</a>), 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><h2>Virtual keyboard behavior</h2><p>When using a virtual keyboard, keyboard suggestions and corrections are controlled as follows:</p><ul><li>For <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> and plain text code notes, the autocorrect is <strong>on</strong>, as well as automatic capitalization.</li><li>For all the other code notes, the autocorrect is off in order to avoid issues when typing code.</li></ul><aside class=\"admonition note\"><p>Not all browsers and platforms respect this value, so the keyboard suggestions might appear without autocorrecting or the browser might disregard this and autocorrect anyway.</p></aside>",+ "_help_6f9hih2hXXZk": "<p>Trilium supports creating \"code\" notes, i.e. notes which contain some sort of formal code - be it programming language (C++, JavaScript), structured data (JSON, XML) or other types of codes (CSS etc.).</p><p>This can be useful for a few things:</p><ul><li>computer programmers can store code snippets as notes with syntax highlighting</li><li>JavaScript code notes can be executed inside Trilium for some extra functionality<ul><li>we call such JavaScript code notes \"scripts\" – see <a class=\"reference-link\" href=\"#root/_help_CdNpE2pqjmI6\">Scripting</a></li></ul></li><li>JSON, XML etc. can be used as storage for structured data (typically used in conjunction with scripting)</li></ul><p>For shorter snippets of code that can be embedded in <a href=\"#root/_help_iPIMuisry3hd\">Text</a> notes, see <a href=\"#root/_help_QxEyIjRBizuC\">Code blocks</a>.</p><p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Code_image.jpg\"></p><h2>Creating a code note</h2><p>In the <a href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>, right-click a note and select <em>Insert child note</em> or <em>Insert note after</em>, then:</p><ul><li>To create a plain text code note, select <em>Code</em>.</li><li>To create a code note in a given language, hover <em>Code</em> and select the language. The list shows the languages enabled in the options (see below), and ends with <em>Configure code notes...</em>, which opens them.</li></ul><h2>Adjusting the language of a code note</h2><p>To change the language of a code note, look for the <span class=\"tn-icon bx bx-code\"></span> icon in the <a class=\"reference-link\" href=\"#root/_help_AlJ73vBCjWDw\">Status bar</a>. When clicked it will reveal the list of available languages (which can be customized according to the section below). The menu also features a search bar to quickly filter, and icons to visually distinguish some of the programming languages.</p><p>On the <a class=\"reference-link\" href=\"#root/_help_RDslemsQ6gCp\">Mobile Frontend</a>, the same list is available in the <a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a> → <em>Note settings</em> → <em>Change language mode</em>.</p><h2>Adjusting the list of languages</h2><p>Trilium supports syntax highlighting for many languages, but by default displays only some of them. The supported languages can be adjusted by going to <a href=\"#root/_help_4TIF1oA4VQRO\">Options</a>, then <em>Code Notes</em> and looking for the <em>Available MIME types in the dropdown</em> section. Simply check any of the items to add them to the list, or un-check them to remove them from the list.</p><p>Note that the list of languages is not immediately refreshed, you'd have to manually <a href=\"#root/_help_s8alTXmpFR61\">refresh the application</a>.</p><p>The list of languages is also shared with the <a href=\"#root/_help_QxEyIjRBizuC\">Code blocks</a> feature of <a href=\"#root/_help_iPIMuisry3hd\">Text</a> notes.</p><h2>Word wrap</h2><p>Long lines can be displayed on multiple lines:</p><ul><li>Globally for all code notes, from <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes.</em></li><li>For a particular note, by going to the menu in <a class=\"reference-link\" href=\"#root/_help_8YBEPzcpUgxw\">Note menu</a> and selecting <em>Word wrap</em> and selecting the appropriate option:<ul><li><em>Auto</em>, to respect the global word wrap for code notes.</li><li><em>On</em> or <em>Off</em>, to change the state of the word wrap for this note regardless of the global option.</li></ul></li></ul><aside class=\"admonition note\"><p>Word wrapping can also be adjusted at note level through the <code>#wrapLines</code> <a href=\"#root/_help_HI6GBBIduIgv\">label</a>, which can also be inherited.</p></aside><h2>Line numbers</h2><p>The numbers at the start of each line can be hidden from <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Code Notes</em> → <em>Editor</em> → <em>Line numbers</em>. The setting applies to every code editor, such as the source of a <a href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> note, and to code shown without its editor (see <em>Color schemes</em> below).</p><p>An included code note or an embedded code file can show or hide them on its own through the <em>Line numbers</em> submenu of its <em>More actions</em> menu, see <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>. Its <em>Auto</em> entry follows the setting.</p><h2>Adjusting options using the status bar</h2><p>The status bar at the bottom of the editor shows the current indentation settings and language. Clicking on the indentation indicator opens a menu with three sections:</p><ol><li><em>Indent Using</em> — switch between Spaces and Tabs (<code>#indentWithTabs</code>). If a per-note override is active, a \"Reset to default\" option appears.</li><li><em>Display Width</em> — choose from preset widths (1, 2, 3, 4, 6, 8). Changes are saved as a per-note <code>#tabWidth</code> label.</li><li><em>Re-indent Content To</em> — convert existing indentation to a different style. For example, re-indent a file from 4 spaces to 2 spaces, or from spaces to tabs. This rewrites the leading whitespace on every line while preserving alignment remainders.</li></ol><p>Clicking the language indicator lets you change the note's MIME type. As in the <em>Note type</em> selector, typing narrows the list of languages.</p><p>The same two menus are in the toolbar of a code note or a code file included in a text note, see <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>.</p><h3>Re-indentation</h3><p>When you re-indent content, the editor:</p><ul><li>Measures the visual column width of each line's leading whitespace using the current style</li><li>Calculates indent levels and any alignment remainder</li><li>Rebuilds the leading whitespace in the target style</li><li>Preserves non-leading whitespace, blank lines, and content without indentation</li></ul><h2>Text tools</h2><p>To change the selected lines or text, right-click the selection and pick an entry from one of these submenus:</p><ul><li><em>Line operations</em>: <em>Sort ascending</em>, <em>Sort descending</em>, <em>Shuffle lines</em>, <em>Reverse line order</em> and <em>Deduplicate lines</em>, which keeps the first copy of each line.</li><li><em>Line removal</em>: <em>Trim leading</em>, <em>Trim trailing</em> and <em>Trim both</em> remove the whitespace at the start, at the end or at both ends of each line. <em>Remove blank lines</em> also removes the lines that hold only whitespace.</li><li><em>Text transform</em>: <em>To uppercase</em>, <em>To lowercase</em>, <em>To sentence case</em>, <em>To title case</em> and <em>Remove diacritics</em>.</li></ul><p>The line operations and the line removals change every line that the selection touches, even partly. The text transforms change only the selected text. Each change is undone in one step with <kbd>Ctrl</kbd>+<kbd>Z</kbd>.</p><ul><li>Sorting reads numbers, dates and times by their value, as sorting a table does (see <a class=\"reference-link\" href=\"#root/_help_NdowYOC1GFKS\">Tables</a>), and ignores the case of letters and the indentation. Blank lines go last.</li><li><em>To sentence case</em> lowercases the text and capitalizes the first word of each sentence and of each line. <em>To title case</em> capitalizes every word except minor words such as \"of\" and \"the\", which stay lowercase unless they start or end a sentence.</li><li><em>Remove diacritics</em> turns letters such as <code>é</code>, <code>ș</code> and <code>ł</code> into <code>e</code>, <code>s</code> and <code>l</code>, and removes the vowel points of Hebrew and Arabic. Letters such as <code>ß</code> and <code>æ</code> stay as they are.</li><li>Sorting and the case changes follow the language set in <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → <em>Language & Region</em> → <em>Default content language</em>. In Turkish, for example, an uppercase <code>i</code> is <code>İ</code>.</li></ul><h2>Color schemes</h2><p>Since Trilium 0.94.0 the colors of code notes can be customized by going <a class=\"reference-link\" href=\"#root/_help_4TIF1oA4VQRO\">Options</a> → Code Notes and looking for the <em>Appearance</em> section.</p><p>A code note or a code file shown without its editor, such as in an <a class=\"reference-link\" href=\"#root/_help_nBAXQFj20hS1\">Include Note</a>, on the cards of <a class=\"reference-link\" href=\"#root/_help_GTwFsgaA0lCt\">Collections</a> or in a tooltip, uses the same colors and line numbers as the editor does. A printout uses the <em>Light theme</em>. A <a href=\"#root/_help_R9pX4DGra2Vt\">shared page</a> uses the VS Code light or dark theme, following the mode of the page.</p><aside class=\"admonition note\"><p><strong>Why are there only a few themes whereas the code block themes for text notes have a lot?</strong><br>The reason is that Code notes use a different technology than the one used in Text notes, and as such there is a more limited selection of themes. If you find a CodeMirror 6 (not 5) theme that you would like to use, let us know and we might consider adding it to the set of default themes. There is no possibility of adding new themes (at least for now), since the themes are defined in JavaScript and not at CSS level.</p></aside><h2>Programming ligatures</h2><p>If you see <code>!=</code> displayed as <code>≠</code> or <code>-></code> as <code>→</code> inside a code note, those are <em>font ligature</em>: the default monospace font draws certain character pairs as a single symbol. The underlying text is not changed by Trilium (unlike text notes which have <a class=\"reference-link\" href=\"#root/_help_oI7GoyilXXAr\">Automatic replacements</a>), 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><h2>Virtual keyboard behavior</h2><p>When using a virtual keyboard, keyboard suggestions and corrections are controlled as follows:</p><ul><li>For <a class=\"reference-link\" href=\"#root/_help_6RM1Q7ppFVoj\">Markdown</a> and plain text code notes, the autocorrect is <strong>on</strong>, as well as automatic capitalization.</li><li>For all the other code notes, the autocorrect is off in order to avoid issues when typing code.</li></ul><aside class=\"admonition note\"><p>Not all browsers and platforms respect this value, so the keyboard suggestions might appear without autocorrecting or the browser might disregard this and autocorrect anyway.</p></aside>","_help_m523cpzocqaD": "<p>Trilium allows you to save common searches as notes within the note tree. The search results will appear as sub-notes under these \"saved search\" notes. Here is an example of how it works:</p><figure class=\"image image-style-align-center image_resized\" style=\"width:50%;\"><img style=\"aspect-ratio:812/585;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Saved%20Search_saved-search.gif\" width=\"812\" height=\"585\"></figure><p>A saved search runs when you open it, and when you expand it in the note tree. A saved search in a tab that is not shown, such as a background tab restored at startup, runs when you switch to that tab. Its results stay until you run the search again with the <em>Search</em> button of the search parameters. If the query has an error, it appears as a notification.</p><p>In <a class=\"reference-link\" href=\"#root/_help_64ZTlUPgEPtW\">Safe mode</a>, and when the request fails, the search does not run on its own. Press <em>Search now</em> to run it.</p><p>Once a search is saved, the <em>Search parameters</em> is still available underneath the <a class=\"reference-link\" href=\"#root/_help_l7pigIGu01K2\">Title</a> in order to be able to change the settings later on but it will appear collapsed by default.</p><h2>Location</h2><p>By default, saved searches are stored in the day note. However, you can designate a different note to store saved searches by marking it with the <code>#searchHome</code> label. Additionally, for <a href=\"#root/_help_9sRHySam5fXb\">workspaces</a>, you can use the <code>#workspaceSearchHome</code> label to specify a storage location for saved searches within that workspace.</p>","_help_iRwzGnHPzonm": "<p>Relation map is a type of note which visualizes notes and their <a href=\"#root/_help_zEY4DaJG4YT5\">relations</a>.</p><h2>Interaction</h2><ul><li>To create a new note and add it to the map, press the <span class=\"tn-icon bx bx-note\"></span> <em>Add note</em> button at the bottom of the map, then click anywhere on the map to place it there.<ul><li>While the map waits for the click, a translucent box follows the mouse to show where the note will go. To cancel, press the button again (now labeled <em>Cancel</em>) or press <kbd>Esc</kbd>.</li><li>The note is created as a child of the map, with the default title of a new note. It opens in the note panel (see below) with its title selected, so you can type its name straight away.</li></ul></li><li>An existing note can also be dragged from the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>. It will be placed at the position it's dragged on.<ul><li>Multiple notes can also be dragged via <a class=\"reference-link\" href=\"#root/_help_yTjUdsOi4CIE\">Multiple selection</a>. The notes will be positioned near the dragged position without overlapping.</li><li>The dragged note can be a sub-child of the map, or it can be at any arbitrary position.</li></ul></li><li>Notes can also be pasted onto the map. Copy or cut them in the <a class=\"reference-link\" href=\"#root/_help_oPVyFC7WL2Lp\">Note Tree</a>, then click the map and press <kbd>Ctrl</kbd>+<kbd>V</kbd>, or right click an empty part of the map and select <em>Paste note(s)</em>.<ul><li>With <kbd>Ctrl</kbd>+<kbd>V</kbd>, the notes are placed under the mouse, or in the middle of the map if the mouse is not over it. From the right click menu, they are placed where the menu was opened.</li><li>Copied notes stay where they are in the tree. Cut notes are moved under the map, as if they had been pasted into it in the tree.</li><li>Links to notes, such as an <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> copied from a text note, can be pasted the same way. If the clipboard holds no link to a note, the notes last copied or cut in the tree are pasted.</li><li>The right click menu of an empty part of the map also has <em>Add note</em>, which creates a new note where the menu was opened.</li></ul></li><li>To create a relationship, hold the mouse on the dot on the right of a note and then:<ul><li>Drag it over another note to create a relationship pointing from the first note to the second one.</li><li>Drag over the same note to create a self-referencing relationship (represented as a loop).</li><li>Once dragged, a popover next to the relationship asks for its name. Type a new name and press <kbd>Enter</kbd>, or pick a relation name already in use from the suggestions. To cancel, press <kbd>Esc</kbd>, close the popover or click elsewhere on the map.</li></ul></li><li>Each note is shown as a card with its icon and title, colored in the note's color the same way as the cards of a <a class=\"reference-link\" href=\"#root/_help_CtBQqbwXDx1w\">Kanban Board</a>.</li><li>Hovering a note highlights its relationships, in the note's color if it has one, and fades the other relationships.</li><li>To view or edit a note, click it on the map. This opens the note panel (see below).<ul><li>To open the note in a new tab instead, <kbd>Ctrl</kbd>+click it or click it with the middle mouse button. <kbd>Shift</kbd>+click opens it in a new window. The right click menu offers the same options.</li></ul></li><li>To edit the title of a note, change its color or delete it (either from the map, or delete it completely), right click the note.</li><li>To rename or delete a relationship, right click it and select the corresponding option.</li><li>On a <a href=\"#root/_help_CoFPLs3dRlXc\">read-only</a> map, notes cannot be moved and relationships cannot be drawn, renamed or deleted. The right click menu of a note only offers to open it, and a relationship has no right click menu.</li><li>To move around the map, drag an empty part of it, and zoom with the mouse wheel or the <span class=\"tn-icon bx bx-minus-circle\"></span> and <span class=\"tn-icon bx bx-plus-circle\"></span> buttons at the bottom-right corner. Clicking the zoom percentage goes back to 100%, and <span class=\"tn-icon bx bx-scan\"></span> <em>Fit to view</em> zooms and pans so that all the notes are visible.<ul><li>Once the map has been clicked, the arrow keys or <kbd>W</kbd> <kbd>A</kbd> <kbd>S</kbd> <kbd>D</kbd> pan it, and <kbd>+</kbd> and <kbd>-</kbd> zoom it. The <kbd>?</kbd> button at the top-right corner of the map lists all its keyboard shortcuts.</li></ul></li></ul><h2>Note panel</h2><p>When a note on the map is clicked, a panel opens to the right of the map and the note is highlighted. If the panel would cover the note, or the note is partly off-screen, the map pans to bring it into view. The panel contains:</p><ul><li>The title and icon of the note, both editable.</li><li>A <span class=\"tn-icon bx bx-expand-alt\"></span> button to expand the panel over the whole map, and to restore it afterwards.</li><li>Buttons to interact with the note:<ul><li><span class=\"tn-icon bx bx-log-in\"></span> Open the note in the current tab, or, through the <span class=\"tn-icon bx bx-dots-horizontal-rounded\"></span> menu, in a new tab, split, window or the quick edit popup.</li><li>A <span class=\"tn-icon bx bx-palette\"></span> color picker to change the color of the note.</li><li>A <span class=\"tn-icon bx bx-trash\"></span> button to remove the note from the map, which can optionally delete the note as well.</li></ul></li><li>The <a class=\"reference-link\" href=\"#root/_help_OFXdgB2nNk1F\">Promoted Attributes</a> of the note, if any.</li><li>The note's content, which can be edited directly from the panel.</li></ul><p>The color picker and the remove button are not shown if the map is read-only.</p><p>Clicking another note on the map switches the panel to it. Similarly, clicking an <a class=\"reference-link\" href=\"#root/_help_hrZ1D00cLbal\">Internal (reference) links</a> inside the panel switches the panel to that note, as long as it is on the map.</p><p>To close the panel, press the <span class=\"tn-icon bx bx-x\"></span> button at its top-right, click an empty part of the map, or press <kbd>Esc</kbd>.</p><p>On mobile, the note opens as a dialog over the whole screen instead of a panel.</p><h2>Development process demo</h2><p>This is a basic example how you can create simple diagram using relation maps:</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Relation%20Map_relation-map-dev-process.png\" width=\"934\" height=\"667\"><p>And this is how you can create it:</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Relation%20Map_relation-map-dev-process-demo.gif\" width=\"812\" height=\"585\"><p>We start completely from scratch by first creating new note called \"Development process\" and changing its type to \"Relation map\". After that we create new notes one by one and place them by clicking into the map. We also drag <a href=\"#root/_help_zEY4DaJG4YT5\">relations</a>between notes and name them. That's all!</p><p>Items on the map - \"Specification\", \"Development\", \"Testing\" and \"Demo\" are actually notes which have been created under \"Development process\" note - you can click on them and write some content. Connections between notes are called \"<a href=\"#root/_help_zEY4DaJG4YT5\">relations</a>\".</p><h2>Family demo</h2><p>This is more complicated demo using some advanced concepts. Resulting diagram is here:</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Relation%20Map_relation-map-family.png\" width=\"941\" height=\"758\"><p>This is how you get to it:</p><img src=\"{{helpAssets}}/User%20Guide/Note%20Types/Relation%20Map_relation-map-family-demo.gif\" width=\"812\" height=\"585\"><p>There are several steps here:</p><ul><li>we start with empty relation map and two existing notes representing Prince Philip and Queen Elizabeth II. These two notes already have <code>isPartnerOf</code> <a href=\"#root/_help_zEY4DaJG4YT5\">relations</a>defined.<ul><li>There are actually two \"inverse\" relations (one from Philip to Elizabeth and one from Elizabeth to Philip)</li></ul></li><li>we drag both notes to relation map and place to suitable position. Notice how the existing <code>isPartnerOf</code> relations are displayed.</li><li>now we create new note - we name it \"Prince Charles\" and place it on the relation map by clicking on the desired position. The note is by default created under the relation map note (visible in the note tree on the left).</li><li>we create two new relations <code>isChildOf</code> targeting both Philip and Elizabeth<ul><li>now there's something unexpected - we can also see the relation to display another <code>hasChild</code> relation. This is because there's a <a href=\"#root/_help_OFXdgB2nNk1F\">relation definition</a> which puts <code>isChildOf</code> as an \"<a href=\"#root/_help_OFXdgB2nNk1F\">inverse</a>\" relation of <code>hasChildOf</code> (and vice versa) and thus it is created automatically.</li></ul></li><li>we create another note for Princess Diana and create <code>isPartnerOf</code> relation from Charles. Again notice how the relation has arrows both ways - this is because <code>isPartnerOf</code> definition specifies its inverse relation as again \"isPartnerOf\" so the opposite relation is created automatically.</li><li>as the last step we pan & zoom the map to fit better to window dimensions.</li></ul><p>Relation definitions mentioned above come from \"Person template\" note which is assigned to any child of \"My Family Tree\" relation note. You can play with the whole thing in the <a href=\"#root/_help_wX4HbRucYSDD\">demo notes</a>.</p><h2>Details</h2><p>You can specify which relations should be displayed with comma delimited names of relations in <code>displayRelations</code> label.</p><p>Alternatively, you can specify comma delimited list of relation names in <code>hideRelations</code> which will display all relations, except for the ones defined in the label.</p><h2>See also</h2><ul><li><a class=\"reference-link\" href=\"#root/_help_bdUJEHsAPYQR\">Note Map</a> is a similar concept.</li></ul>","_help_bdUJEHsAPYQR": "<figure class=\"image image_resized\" style=\"width:72.68%;\"><img style=\"aspect-ratio:1311/1271;\" src=\"{{helpAssets}}/User%20Guide/Note%20Types/Note%20Map_image.png\" width=\"1311\" height=\"1271\"></figure><p>A Note map is a note type which displays a standalone version of the feature of the same name: <a class=\"reference-link\" href=\"#root/_help_BCkXAVs63Ttv\">Note Map (Link map, Tree map)</a>. Consult that page for more information on how the note map works and what it displays.</p><p>Once created, the note map will display the relations between notes. Only the notes that are part of the parent of the note map will be displayed (including their children).</p><h2>Root note</h2><p>The root note defines the starting point of the graph, from which the relations and the hierarchy are derived from.</p><p>There are three possible root notes:</p><ul><li>The default root note is the parent note of the note map.</li><li>To use the currently <a href=\"#root/_help_OR8WJ7Iz9K4U\">hoisted note</a> instead, set the <code>mapRootNoteId</code> label to <code>hoisted</code>.</li><li>To use a specific note instead, set <code>mapRootNoteId</code> to the <a class=\"reference-link\" href=\"#root/_help_m1lbrzyKDaRB\">Note ID</a> of the desired note.</li></ul><h2>Customization</h2><p>The note map can be customized using the following <a class=\"reference-link\" href=\"#root/_help_HI6GBBIduIgv\">Labels</a>:</p><figure class=\"table\"><table><thead><tr><th>Label</th><th>Description</th></tr></thead><tbody><tr><td><code>#mapIncludeRelation</code></td><td>Comma-delimited relation names to include from the note map.</td></tr><tr><td><code>#mapExcludeRelation</code></td><td>Comma-delimited relation names to exclude from the note map.</td></tr><tr><td><code>#mapRootNoteId</code></td><td>The ID of the note the map roots from, or <code>hoisted</code>. See the root note section above for more information.</td></tr></tbody></table></figure>",diff --git a/docs/User Guide/User Guide/Note Types/Code.md b/docs/User Guide/User Guide/Note Types/Code.mdindex d52b849e9b..1292d47f31 100644--- a/docs/User Guide/User Guide/Note Types/Code.md+++ b/docs/User Guide/User Guide/Note Types/Code.md@@ -72,6 +72,21 @@ When you re-indent content, the editor:* Rebuilds the leading whitespace in the target style* Preserves non-leading whitespace, blank lines, and content without indentation+## Text tools++To change the selected lines or text, right-click the selection and pick an entry from one of these submenus:++* _Line operations_: _Sort ascending_, _Sort descending_, _Shuffle lines_, _Reverse line order_ and _Deduplicate lines_, which keeps the first copy of each line.+* _Line removal_: _Trim leading_, _Trim trailing_ and _Trim both_ remove the whitespace at the start, at the end or at both ends of each line. _Remove blank lines_ also removes the lines that hold only whitespace.+* _Text transform_: _To uppercase_, _To lowercase_, _To sentence case_, _To title case_ and _Remove diacritics_.++The line operations and the line removals change every line that the selection touches, even partly. The text transforms change only the selected text. Each change is undone in one step with <kbd>Ctrl</kbd>+<kbd>Z</kbd>.++* Sorting reads numbers, dates and times by their value, as sorting a table does (see <a class="reference-link" href="Text/Tables.md">Tables</a>), and ignores the case of letters and the indentation. Blank lines go last.+* _To sentence case_ lowercases the text and capitalizes the first word of each sentence and of each line. _To title case_ capitalizes every word except minor words such as "of" and "the", which stay lowercase unless they start or end a sentence.+* _Remove diacritics_ turns letters such as `é`, `ș` and `ł` into `e`, `s` and `l`, and removes the vowel points of Hebrew and Arabic. Letters such as `ß` and `æ` stay as they are.+* Sorting and the case changes follow the language set in <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Language & Region_ → _Default content language_. In Turkish, for example, an uppercase `i` is `İ`.+## Color schemesSince Trilium 0.94.0 the colors of code notes can be customized by going <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → Code Notes and looking for the _Appearance_ section.diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.tsindex 039f7e7fda..f7e867ff33 100644--- a/packages/codemirror/src/index.ts+++ b/packages/codemirror/src/index.ts@@ -22,6 +22,9 @@ export { default as ColorThemes, type ThemeDefinition, type ThemeVariant, getTheexport {default as SharedHistory, type HostHistory, type HostHistoryStep} from "./shared_history.js";+export {+ hasSelectedText, runLineOperation, runTextTransform, type TextToolTarget+} from "./text_tools.js";export {isScriptMime, type ScriptApiContext, SCRIPT_MIME_BACKEND, SCRIPT_MIME_FRONTEND,type TypeCompletionEntrydiff --git a/packages/codemirror/src/shared_history.spec.ts b/packages/codemirror/src/shared_history.spec.tsindex d5cdb966a6..78d86732bf 100644--- a/packages/codemirror/src/shared_history.spec.ts+++ b/packages/codemirror/src/shared_history.spec.ts@@ -1,3 +1,4 @@+import { isolateHistory } from "@codemirror/commands";import { EditorSelection, Transaction, type TransactionSpec } from "@codemirror/state";import { EditorView } from "@codemirror/view";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -140,6 +141,31 @@ describe("SharedHistory", () => {expect(host.undo()).toBe(false);});+ it("ends a step around a change marked with `isolateHistory`, as `history()` does", () => {+ const host = createHost();+ const { view } = setUp(host, "");+ const isolatedType = (at: number, text: string, isolate: "before" | "after" | "full") =>+ view.dispatch({+ changes: { from: at, insert: text },+ selection: EditorSelection.cursor(at + text.length),+ userEvent: "input.type",+ annotations: isolateHistory.of(isolate)+ });++ type(view, 0, "a");+ isolatedType(1, "b", "full");+ type(view, 2, "c");+ expect(host.done).toHaveLength(3);++ isolatedType(3, "d", "before");+ type(view, 4, "e");+ expect(host.done).toHaveLength(4);++ isolatedType(5, "f", "after");+ type(view, 6, "g");+ expect(host.done).toHaveLength(5);+ });+it("leaves loaded content out of the history, and ends the step before it", () => {const host = createHost();const { view } = setUp(host, "");diff --git a/packages/codemirror/src/shared_history.ts b/packages/codemirror/src/shared_history.tsindex edcb25d1f2..b40e7f10ba 100644--- a/packages/codemirror/src/shared_history.ts+++ b/packages/codemirror/src/shared_history.ts@@ -1,3 +1,4 @@+import { isolateHistory } from "@codemirror/commands";import { type ChangeSet, type EditorSelection, type Text, Transaction } from "@codemirror/state";import type { EditorView } from "@codemirror/view";@@ -69,9 +70,11 @@ export default class SharedHistory {}const time = Date.now();+ const isolate = tr.annotation(isolateHistory);if (tr.annotation(Transaction.addToHistory) === false) {this.open = undefined;- } else if (this.open && canJoin(this.open, tr, time)) {+ } else if (this.open && isolate !== "before" && isolate !== "full"+ && canJoin(this.open, tr, time)) {const { step } = this.open;step.changes = step.changes.compose(tr.changes);step.after = tr.newDoc;@@ -91,6 +94,10 @@ export default class SharedHistory {});this.open = { step, entry, time };}++ if (isolate === "after" || isolate === "full") {+ this.open = undefined;+ }}private apply(step: Step, isUndo: boolean) {diff --git a/packages/codemirror/src/text_tools.spec.ts b/packages/codemirror/src/text_tools.spec.tsnew file mode 100644index 0000000000..c71be47345--- /dev/null+++ b/packages/codemirror/src/text_tools.spec.ts@@ -0,0 +1,248 @@+import { history, isolateHistory, undo } from "@codemirror/commands";+import {+ EditorSelection, EditorState, type Extension, type SelectionRange, Text, Transaction+} from "@codemirror/state";+import type { LineOperation, TextTransform } from "@triliumnext/commons";+import { describe, expect, it } from "vitest";++import { hasSelectedText, runLineOperation, runTextTransform } from "./text_tools.js";++describe("hasSelectedText", () => {+ it("tells whether any range of the selection holds text", () => {+ expect(hasSelectedText(createTarget("a|b").state)).toBe(false);+ expect(hasSelectedText(createTarget("|a[b]").state)).toBe(true);+ });+});++describe("runLineOperation", () => {+ it("changes the whole lines the selection touches, and selects them", () => {+ const target = createTarget("keep\nc[2\nb2\na]2\nkeep");+ expect(runLineOperation(target, "sortAscending")).toBe(true);+ expect(target.marked).toBe("keep\n[a2\nb2\nc2]\nkeep");+ });++ it("leaves out the line that a selection ends at the start of", () => {+ const target = createTarget("[c\nb\n]a");+ runLineOperation(target, "sortAscending");+ expect(target.marked).toBe("[b\nc]\na");+ });++ it("changes each block of lines on its own, joining the ranges on one line", () => {+ const target = createTarget("[b\na] [x]\nz\n[d\nc]", 2);+ runLineOperation(target, "sortAscending");+ expect(target.marked).toBe("[a x\nb]\nz\n[c\nd]");+ expect(target.state.selection.mainIndex).toBe(1);++ const trimmed = createTarget("[ b\n a] [x] ");+ runLineOperation(trimmed, "trimBoth");+ expect(trimmed.marked).toBe("[b\na x]");++ const withCursor = createTarget("x|y\n[c\nb]", 1);+ runLineOperation(withCursor, "sortAscending");+ expect(withCursor.marked).toBe("xy\n[b\nc]");+ });++ it("runs each operation on the lines", () => {+ expect(run("[ b \n\n a \n a ]", "deduplicate")).toBe("[ b \n\n a ]");+ expect(run("[1\n2\n3]", "reverse")).toBe("[3\n2\n1]");+ expect(run("x\n [b ]", "trimLeading")).toBe("x\n[b ]");+ expect(run("x\n [b ]", "trimTrailing")).toBe("x\n[ b]");+ expect(run("x\n [b ]", "trimBoth")).toBe("x\n[b]");+ expect(run("[a\n \n\nb]", "removeBlankLines")).toBe("[a\nb]");+ expect(run("[10\n9\n\nb\nA]", "sortDescending")).toBe("[b\nA\n10\n9\n]");+ });++ it("passes the locale, the date formats and the random source on", () => {+ const sorted = createTarget("[01.10.26\n30.09.26]");+ runLineOperation(sorted, "sortAscending", { locale: "en", dateFormats: [ "DD.MM.YY" ] });+ expect(sorted.marked).toBe("[30.09.26\n01.10.26]");++ const collated = createTarget("[z\nä\na]");+ runLineOperation(collated, "sortAscending", { locale: "sv" });+ expect(collated.marked).toBe("[a\nz\nä]");++ const shuffled = createTarget("[a\nb\nc\nd]");+ runLineOperation(shuffled, "shuffle", { random: () => 0 });+ expect(shuffled.marked).toBe("[b\nc\nd\na]");+ });++ it("removes the line break of a block that has no line left", () => {+ expect(run("a\n[\n ]\nb", "removeBlankLines")).toBe("a\n|b");+ expect(run("a\n[\n ]", "removeBlankLines")).toBe("a|");+ expect(run("[ \n]x", "removeBlankLines")).toBe("|x");+ expect(run("[\n]x", "removeBlankLines")).toBe("|x");+ expect(run("[\n ]", "removeBlankLines")).toBe("|");+ });++ it("keeps the line breaks of the editor", () => {+ const target = createTarget("[b\na]", 0, [ EditorState.lineSeparator.of("\r\n") ]);+ runLineOperation(target, "sortAscending");+ expect(target.state.sliceDoc()).toBe("a\r\nb");+ expect(target.marked).toBe("[a\nb]");+ });++ it("dispatches nothing when the lines do not change", () => {+ const target = createTarget("[a\nb]");+ expect(runLineOperation(target, "sortAscending")).toBe(true);+ expect(target.transactions).toHaveLength(0);+ });++ it("refuses a selection without text and a read-only editor", () => {+ expect(runLineOperation(createTarget("b\n|a"), "sortAscending")).toBe(false);+ const readOnly = createTarget("[b\na]", 0, [ EditorState.readOnly.of(true) ]);+ expect(runLineOperation(readOnly, "sortAscending")).toBe(false);+ expect(readOnly.transactions).toHaveLength(0);+ });++ it("makes one undo step that later typing does not join", () => {+ const target = createTarget("[c\nb\na]", 0, [ history() ]);+ runLineOperation(target, "sortAscending");+ runLineOperation(target, "reverse");+ target.dispatch(target.state.update({+ changes: { from: 5, insert: "!" },+ userEvent: "input.type"+ }));+ expect(target.state.sliceDoc()).toBe("c\nb\na!");++ undo(target);+ expect(target.state.sliceDoc()).toBe("c\nb\na");+ undo(target);+ expect(target.state.sliceDoc()).toBe("a\nb\nc");+ undo(target);+ expect(target.state.sliceDoc()).toBe("c\nb\na");++ const [ transaction ] = target.transactions;+ expect(transaction.annotation(Transaction.userEvent)).toBe("input.transform");+ expect(transaction.annotation(isolateHistory)).toBe("full");+ expect(transaction.scrollIntoView).toBe(true);+ });+});++describe("runTextTransform", () => {+ it("changes each range of the selection and keeps it selected", () => {+ expect(transform("[hello] world| [foo]", "upperCase")).toBe("[HELLO] world| [FOO]");+ expect(transform("[straße] x", "upperCase", "de")).toBe("[STRASSE] x");+ expect(transform("[ÉTÉ]", "removeDiacritics")).toBe("[ETE]");+ });++ it("reads the rest of the line to find where words and sentences start and end", () => {+ expect(transform("Hello world. [FOO bar]", "sentenceCase")).toBe("Hello world. [Foo bar]");+ expect(transform("hel[LO WORLD]", "sentenceCase")).toBe("hel[lo world]");+ expect(transform("[FIRST\nSECOND]", "sentenceCase")).toBe("[First\nSecond]");+ expect(transform("the lord [OF THE] rings", "titleCase")).toBe("the lord [of the] rings");+ expect(transform("the lord of the [rings]", "titleCase")).toBe("the lord of the [Rings]");+ });++ it("uses the locale", () => {+ expect(transform("[istanbul]", "upperCase", "tr")).toBe("[İSTANBUL]");+ expect(transform("[istanbul]", "upperCase", "en")).toBe("[ISTANBUL]");+ });++ it("keeps the direction of a range", () => {+ const target = createTarget("abc");+ target.dispatch(target.state.update({ selection: EditorSelection.range(3, 0) }));+ runTextTransform(target, "upperCase");+ expect(target.state.selection.main).toMatchObject({ anchor: 3, head: 0 });+ });++ it("selects the new length of a text with line breaks of the editor", () => {+ const target = createTarget("[ab\ncd]", 0, [ EditorState.lineSeparator.of("\r\n") ]);+ runTextTransform(target, "upperCase");+ expect(target.state.sliceDoc()).toBe("AB\r\nCD");+ expect(target.marked).toBe("[AB\nCD]");+ });++ it("dispatches nothing for unchanged text, and refuses what it cannot change", () => {+ const unchanged = createTarget("[ABC]");+ expect(runTextTransform(unchanged, "upperCase")).toBe(true);+ expect(unchanged.transactions).toHaveLength(0);++ expect(runTextTransform(createTarget("ab|c"), "upperCase")).toBe(false);+ const readOnly = createTarget("[abc]", 0, [ EditorState.readOnly.of(true) ]);+ expect(runTextTransform(readOnly, "upperCase")).toBe(false);+ });++ it("makes one undo step", () => {+ const target = createTarget("[abc] [def]", 0, [ history() ]);+ runTextTransform(target, "upperCase");+ expect(target.state.sliceDoc()).toBe("ABC DEF");+ undo(target);+ expect(target.state.sliceDoc()).toBe("abc def");+ expect(target.transactions[0].annotation(isolateHistory)).toBe("full");+ });+});++interface Target {+ readonly state: EditorState;+ dispatch(transaction: Transaction): void;+ readonly transactions: Transaction[];+ /** The document, with `[` and `]` around each selected range and `|` at each cursor. */+ readonly marked: string;+}++/**+ * A state and a dispatch function that keeps the transactions. In `marked`, `[` and `]` surround a+ * selected range and `|` is a cursor; `mainIndex` picks the main range.+ */+function createTarget(marked: string, mainIndex = 0, extensions: Extension[] = []): Target {+ let doc = "";+ let rangeStart = 0;+ const ranges: SelectionRange[] = [];+ for (const character of marked) {+ if (character === "[") {+ rangeStart = doc.length;+ } else if (character === "]") {+ ranges.push(EditorSelection.range(rangeStart, doc.length));+ } else if (character === "|") {+ ranges.push(EditorSelection.cursor(doc.length));+ } else {+ doc += character;+ }+ }++ // Built from lines: an editor with a line separator of its own does not split a string at "\n".+ let state = EditorState.create({+ doc: Text.of(doc.split("\n")),+ selection: EditorSelection.create(ranges.length ? ranges : [ EditorSelection.cursor(0) ],+ mainIndex),+ extensions: [ EditorState.allowMultipleSelections.of(true), ...extensions ]+ });+ const transactions: Transaction[] = [];+ return {+ get state() {+ return state;+ },+ dispatch(transaction) {+ transactions.push(transaction);+ state = transaction.state;+ },+ transactions,+ get marked() {+ return markSelection(state);+ }+ };+}++function markSelection(state: EditorState) {+ const text = state.doc.toString();+ let result = "";+ let position = 0;+ for (const range of state.selection.ranges) {+ result += text.slice(position, range.from);+ result += range.empty ? "|" : `[${text.slice(range.from, range.to)}]`;+ position = range.to;+ }+ return result + text.slice(position);+}++function run(marked: string, operation: LineOperation) {+ const target = createTarget(marked);+ runLineOperation(target, operation, { locale: "en" });+ return target.marked;+}++function transform(marked: string, name: TextTransform, locale = "en") {+ const target = createTarget(marked);+ runTextTransform(target, name, { locale });+ return target.marked;+}diff --git a/packages/codemirror/src/text_tools.ts b/packages/codemirror/src/text_tools.tsnew file mode 100644index 0000000000..2eddc0b69b--- /dev/null+++ b/packages/codemirror/src/text_tools.ts@@ -0,0 +1,157 @@+import { isolateHistory } from "@codemirror/commands";+import {+ type ChangeSpec, EditorSelection, type EditorState, type Transaction, type TransactionSpec+} from "@codemirror/state";+import {+ type LineOperation, type LineOperationOptions, type TextTransform, type TextTransformOptions,+ transformLines, transformText+} from "@triliumnext/commons";++/** What the text tools change: an `EditorView`, or a state with a dispatch function. */+export interface TextToolTarget {+ readonly state: EditorState;+ dispatch(transaction: Transaction): void;+}++/** Whether the selection holds any text for the text tools to change. */+export function hasSelectedText(state: EditorState) {+ return state.selection.ranges.some((range) => !range.empty);+}++/**+ * Applies `operation` to the whole lines that the selection touches, in one undo step, and selects+ * the changed lines. Each range of the selection changes its own lines. Returns `false` when+ * nothing is selected or the editor is read-only.+ */+export function runLineOperation(+ target: TextToolTarget,+ operation: LineOperation,+ options: LineOperationOptions = {}+) {+ const { state } = target;+ if (state.readOnly || !hasSelectedText(state)) {+ return false;+ }++ const { blocks, mainIndex } = getLineBlocks(state);+ const changes = state.changes(blocks.flatMap((block) => {+ const lines = state.sliceDoc(block.from, block.to).split(state.lineBreak);+ const result = transformLines(lines, operation, options);+ return isSameLines(lines, result) ? [] : [ toLineChange(state, block, result) ];+ }));+ if (changes.empty) {+ return true;+ }++ const ranges = blocks.map((block) =>+ EditorSelection.range(changes.mapPos(block.from, -1), changes.mapPos(block.to, 1)));+ target.dispatch(state.update({+ changes,+ selection: EditorSelection.create(ranges, mainIndex),+ ...EDIT+ }));+ return true;+}++/**+ * Applies `transform` to each range of the selection, in one undo step, and keeps the ranges+ * selected. Returns `false` when nothing is selected or the editor is read-only.+ */+export function runTextTransform(+ target: TextToolTarget,+ transform: TextTransform,+ options: Pick<TextTransformOptions, "locale"> = {}+) {+ const { state } = target;+ if (state.readOnly || !hasSelectedText(state)) {+ return false;+ }++ let isChanged = false;+ const spec = state.changeByRange((range) => {+ const text = state.sliceDoc(range.from, range.to);+ const replaced = transformText(text, transform, {+ locale: options.locale,+ before: state.sliceDoc(state.doc.lineAt(range.from).from, range.from),+ after: state.sliceDoc(range.to, state.doc.lineAt(range.to).to)+ });+ if (replaced === text) {+ return { range };+ }++ isChanged = true;+ const end = range.from + state.toText(replaced).length;+ return {+ changes: { from: range.from, to: range.to, insert: replaced },+ range: range.anchor === range.from+ ? EditorSelection.range(range.from, end)+ : EditorSelection.range(end, range.from)+ };+ });++ if (isChanged) {+ target.dispatch(state.update(spec, EDIT));+ }+ return true;+}++/** A run of whole lines, from the start of the first to the end of the last. */+interface LineBlock {+ from: number;+ to: number;+}++/** The text tools change the document as one undo step, which later typing does not join. */+const EDIT = {+ scrollIntoView: true,+ userEvent: "input.transform",+ annotations: isolateHistory.of("full")+} satisfies TransactionSpec;++/**+ * The blocks of lines that the ranges of the selection touch, and the index of the block of the+ * main range. A range that ends at the start of a line leaves that line out, and ranges that+ * touch one line share a block.+ */+function getLineBlocks(state: EditorState) {+ const { doc, selection } = state;+ const blocks: LineBlock[] = [];+ let mainIndex = 0;++ for (const [ index, range ] of selection.ranges.entries()) {+ if (range.empty) continue;++ const first = doc.lineAt(range.from);+ let last = doc.lineAt(range.to);+ if (range.to === last.from && last.number > first.number) {+ last = doc.line(last.number - 1);+ }++ const previous = blocks[blocks.length - 1];+ if (previous && first.from <= previous.to) {+ previous.to = Math.max(previous.to, last.to);+ } else {+ blocks.push({ from: first.from, to: last.to });+ }+ if (index === selection.mainIndex) {+ mainIndex = blocks.length - 1;+ }+ }++ return { blocks, mainIndex };+}++function isSameLines(lines: string[], result: string[]) {+ return lines.length === result.length && lines.every((line, index) => line === result[index]);+}++/** Replaces `block` with `lines`. With no lines, it also removes a line break next to the block. */+function toLineChange(state: EditorState, block: LineBlock, lines: string[]): ChangeSpec {+ if (lines.length) {+ return { from: block.from, to: block.to, insert: lines.join(state.lineBreak) };+ }+ if (block.to < state.doc.length) {+ return { from: block.from, to: block.to + 1 };+ }+ return { from: Math.max(block.from - 1, 0), to: block.to };+}diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex 83613ed983..35bbb05a59 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -24,6 +24,7 @@ export * from "./lib/attribute_names.js";export * from "./lib/search_syntax.js";export * from "./lib/sort_criteria.js";export * from "./lib/auto_sort.js";+export * from "./lib/text_transforms.js";export * from "./lib/note_type_ids.js";export * from "./lib/promoted_attribute_definition_parser.js";export { default as promotedAttributeDefinitionParser } from "./lib/promoted_attribute_definition_parser.js";diff --git a/packages/commons/src/lib/text_transforms.spec.ts b/packages/commons/src/lib/text_transforms.spec.tsnew file mode 100644index 0000000000..3824387d92--- /dev/null+++ b/packages/commons/src/lib/text_transforms.spec.ts@@ -0,0 +1,175 @@+import { describe, expect, it } from "vitest";++import {+ type LineOperation, type TextTransformOptions, transformLines, transformText+} from "./text_transforms.js";++function lines(operation: LineOperation, input: string[], locale = "en") {+ return transformLines(input, operation, { locale });+}++function sentenceCase(text: string, locale = "en", context: TextTransformOptions = {}) {+ return transformText(text, "sentenceCase", { locale, ...context });+}++function titleCase(text: string, locale = "en", context: TextTransformOptions = {}) {+ return transformText(text, "titleCase", { locale, ...context });+}++function removeDiacritics(text: string) {+ return transformText(text, "removeDiacritics");+}++describe("transformLines", () => {+ it("sorts with auto-sort: by value, ignoring case and indentation, blank lines last", () => {+ const input = [ "item 10", "", " Banana", "item 9", "apple", "1.5", "10" ];+ expect(lines("sortAscending", input))+ .toEqual([ "1.5", "10", "apple", " Banana", "item 9", "item 10", "" ]);+ expect(lines("sortDescending", input))+ .toEqual([ "item 10", "item 9", " Banana", "apple", "10", "1.5", "" ]);+ expect(lines("sortAscending", [ "2026-09-30", "15:02", "3" ]))+ .toEqual([ "15:02", "2026-09-30", "3" ]);+ });++ it("sorts by the collation and the number format of the locale", () => {+ expect(lines("sortAscending", [ "ä", "z", "a" ], "de")).toEqual([ "a", "ä", "z" ]);+ expect(lines("sortAscending", [ "ä", "z", "a" ], "sv")).toEqual([ "a", "z", "ä" ]);+ expect(lines("sortAscending", [ "1.250", "1.3" ], "en")).toEqual([ "1.250", "1.3" ]);+ expect(lines("sortAscending", [ "1.250", "1.3" ], "de")).toEqual([ "1.3", "1.250" ]);+ expect(transformLines([ "01.10.26", "30.09.26" ], "sortAscending", {+ locale: "en",+ dateFormats: [ "DD.MM.YY" ]+ })).toEqual([ "30.09.26", "01.10.26" ]);+ });++ it("shuffles with the given random source, leaving the input alone", () => {+ const input = [ "a", "b", "c", "d" ];+ expect(transformLines(input, "shuffle", { random: () => 0 }))+ .toEqual([ "b", "c", "d", "a" ]);+ expect(input).toEqual([ "a", "b", "c", "d" ]);+ expect(transformLines(input, "shuffle").toSorted()).toEqual(input);+ });++ it("reverses and deduplicates, keeping the first copy of each line", () => {+ expect(lines("reverse", [ "a", "b", "c" ])).toEqual([ "c", "b", "a" ]);+ expect(lines("deduplicate", [ "b", "a", "b", "a ", "", "a", "" ]))+ .toEqual([ "b", "a", "a ", "" ]);+ });++ it("trims and removes blank lines by any Unicode whitespace", () => {+ const input = [ "\u{a0}\u{3000}x\t", " y ", "", " \t\u{3000}" ];+ expect(lines("trimLeading", input)).toEqual([ "x\t", "y ", "", "" ]);+ expect(lines("trimTrailing", input)).toEqual([ "\u{a0}\u{3000}x", " y", "", "" ]);+ expect(lines("trimBoth", input)).toEqual([ "x", "y", "", "" ]);+ expect(lines("removeBlankLines", input)).toEqual([ "\u{a0}\u{3000}x\t", " y " ]);+ expect(lines("removeBlankLines", [ "", " " ])).toEqual([]);+ });+});++describe("transformText", () => {+ it("changes the case by the rules of the locale", () => {+ expect(transformText("straße", "upperCase", { locale: "de" })).toBe("STRASSE");+ expect(transformText("istanbul", "upperCase", { locale: "tr" })).toBe("İSTANBUL");+ expect(transformText("IRMAK", "lowerCase", { locale: "tr" })).toBe("ırmak");+ expect(transformText("IRMAK", "lowerCase", { locale: "en" })).toBe("irmak");+ expect(transformText("άλφα", "upperCase", { locale: "el" })).toBe("ΑΛΦΑ");+ expect(transformText("ΟΔΟΣ ΚΑΙ ΟΣ", "lowerCase", { locale: "el" })).toBe("οδος και ος");+ expect(transformText("abc", "upperCase")).toBe("ABC");+ expect(transformText("abc", "upperCase", { locale: "en_rtl" })).toBe("ABC");+ });++ it("starts each sentence and each line with a capital in sentence case", () => {+ expect(sentenceCase("THE HOBBIT. AND MORE")).toBe("The hobbit. And more");+ expect(sentenceCase("hello world! is it? yes.")).toBe("Hello world! Is it? Yes.");+ expect(sentenceCase("first LINE\nSECOND line\n\n third"))+ .toBe("First line\nSecond line\n\n Third");+ expect(sentenceCase("he said \"STOP.\" then LEFT")).toBe("He said \"stop.\" Then left");+ expect(sentenceCase("- BUY MILK (OR TEA.) next")).toBe("- Buy milk (or tea.) Next");+ });++ it("leaves a sentence that starts with a number without a capital", () => {+ expect(sentenceCase("3 APPLES. 2 PEARS")).toBe("3 apples. 2 pears");+ expect(sentenceCase("PI IS 3.14 OR SO")).toBe("Pi is 3.14 or so");+ });++ it("finds sentences in other scripts", () => {+ expect(sentenceCase("¿QUÉ PASA? NADA.", "es")).toBe("¿Qué pasa? Nada.");+ expect(sentenceCase("ԲԱՐԵՒ։ ԻՆՉՊԵՍ ԵՍ", "hy")).toBe("Բարեւ։ Ինչպես ես");+ expect(sentenceCase("Η ΟΔΟΣ ΕΙΝΑΙ ΕΔΩ. ΝΑΙ", "el")).toBe("Η οδος ειναι εδω. Ναι");+ expect(sentenceCase("İSTANBUL IŞIK", "tr")).toBe("İstanbul ışık");+ expect(sentenceCase("ПРИВЕТ, МИР. КАК ДЕЛА", "ru")).toBe("Привет, мир. Как дела");+ });++ it("reads the rest of the line to tell where a sentence or a word starts", () => {+ expect(sentenceCase("FOO bar", "en", { before: "Hello world. " })).toBe("Foo bar");+ expect(sentenceCase("WORLD", "en", { before: "Hello " })).toBe("world");+ expect(sentenceCase("LO WORLD", "en", { before: "hel" })).toBe("lo world");+ expect(sentenceCase(" TODO", "en", { before: " - " })).toBe(" Todo");+ });++ it("capitalizes every word but the minor ones in title case", () => {+ expect(titleCase("the lord of the rings")).toBe("The Lord of the Rings");+ expect(titleCase("THE HOBBIT")).toBe("The Hobbit");+ expect(titleCase("of mice and men")).toBe("Of Mice and Men");+ expect(titleCase("what are you looking for")).toBe("What Are You Looking For");+ expect(titleCase("don't stop me now")).toBe("Don't Stop Me Now");+ expect(titleCase("a well-known fact")).toBe("A Well-Known Fact");+ expect(titleCase("the first. the second\nthe third"))+ .toBe("The First. The Second\nThe Third");+ expect(titleCase("1st place")).toBe("1st Place");+ expect(titleCase("e\u{301}cole")).toBe("E\u{301}cole");+ });++ it("uses the minor words of the language, and none for a language without a list", () => {+ expect(titleCase("el señor de los anillos", "es")).toBe("El Señor de los Anillos");+ expect(titleCase("le seigneur des anneaux", "fr")).toBe("Le Seigneur des Anneaux");+ expect(titleCase("în căutarea timpului pierdut", "ro"))+ .toBe("În Căutarea Timpului Pierdut");+ expect(titleCase("sagan om ringen", "sv")).toBe("Sagan Om Ringen");+ expect(titleCase("istanbul ve izmir", "tr")).toBe("İstanbul Ve İzmir");+ });++ it("writes the capitals that differ from the uppercase letter", () => {+ expect(titleCase("ijsselmeer en ijmuiden", "nl")).toBe("IJsselmeer en IJmuiden");+ expect(titleCase("ijs", "en")).toBe("Ijs");+ expect(titleCase("džep ljubav njiva dz", "hr")).toBe("Džep Ljubav Njiva Dz");+ expect(titleCase("საქართველო", "ka")).toBe("საქართველო");+ expect(transformText("საქართველო", "upperCase", { locale: "ka" })).toBe("ᲡᲐᲥᲐᲠᲗᲕᲔᲚᲝ");+ expect(titleCase("άλφα ΟΣ", "el")).toBe("Άλφα Ος");+ expect(titleCase("\u{fb01}sh", "en")).toBe("Fish");+ });++ it("reads the rest of the line to tell the first and the last word", () => {+ const line = { before: "the lord ", after: " rings" };+ expect(titleCase("OF THE", "en", line)).toBe("of the");+ expect(titleCase("rings", "en", { before: "the lord of the " })).toBe("Rings");+ expect(titleCase("lo", "en", { before: "hel" })).toBe("lo");+ expect(titleCase("the lo", "en", { after: "rd of" })).toBe("The Lo");+ });++ it("removes the accents and marks of Latin, Greek and Cyrillic letters", () => {+ expect(removeDiacritics("Ștefan Țară façade Łódź Ærø")).toBe("Stefan Tara facade Lodz Æro");+ expect(removeDiacritics("Tiếng Việt, Đà Nẵng")).toBe("Tieng Viet, Da Nang");+ expect(removeDiacritics("Ħ ħ Ŧ ŧ ƀ ɨ Ǿ ŀ")).toBe("H h T t b i O l");+ expect(removeDiacritics("Καλημέρα ΆΛΦΑ")).toBe("Καλημερα ΑΛΦΑ");+ expect(removeDiacritics("ёлка, йод")).toBe("елка, иод");+ expect(removeDiacritics("cafe\u{301} na\u{308}i\u{308}ve")).toBe("cafe naive");+ // The Angstrom sign, which decomposes to A with a ring.+ expect(removeDiacritics("\u{212b}")).toBe("A");+ });++ it("removes the vowel points of Hebrew and Arabic", () => {+ expect(removeDiacritics("שָׁלוֹם")).toBe("שלום");+ expect(removeDiacritics("مَرْحَبًا")).toBe("مرحبا");+ });++ it("keeps the marks that spell letters, and characters without diacritics", () => {+ // Devanagari vowel signs, Thai, kana voicing marks, Hangul, a CJK compatibility ideograph,+ // letters that are not a base letter with a mark, an astral emoji and letter, the Ohm sign.+ const unchanged = "हिन्दी ไทย がぎ 한국어 \u{f900} ß æ œ \u{fb01} ı 😀 𝒜 \u{2126} plain";+ expect(removeDiacritics(unchanged)).toBe(unchanged);+ // Marks on symbols: decomposed and precomposed "≠", a stray mark, a keycap emoji.+ const symbols = "a =\u{338} \u{2260} \u{2209} \u{301} 1\u{fe0f}\u{20e3}";+ expect(removeDiacritics(symbols)).toBe(symbols);+ });+});diff --git a/packages/commons/src/lib/text_transforms.ts b/packages/commons/src/lib/text_transforms.tsnew file mode 100644index 0000000000..cc060b3333--- /dev/null+++ b/packages/commons/src/lib/text_transforms.ts@@ -0,0 +1,268 @@+import { autoSort } from "./auto_sort.js";+import { toLanguageTag } from "./i18n.js";++/** A change made to each line of a block of lines. */+export type LineOperation =+ | "sortAscending"+ | "sortDescending"+ | "shuffle"+ | "reverse"+ | "deduplicate"+ | "trimLeading"+ | "trimTrailing"+ | "trimBoth"+ | "removeBlankLines";++/** A change made to the letters of a text. */+export type TextTransform =+ | "upperCase"+ | "lowerCase"+ | "sentenceCase"+ | "titleCase"+ | "removeDiacritics";++export interface LineOperationOptions {+ /** A Trilium locale id or a BCP 47 tag, for sorting. Defaults to the runtime's locale. */+ locale?: string;+ /** More date formats for sorting to recognize, in Day.js syntax. */+ dateFormats?: string[];+ /** Returns a random number from 0 to 1, for shuffling. Defaults to `Math.random`. */+ random?: () => number;+}++export interface TextTransformOptions {+ /** A Trilium locale id or a BCP 47 tag. Defaults to the runtime's locale. */+ locale?: string;+ /** The text before `text` on its line, to tell if `text` starts a word or a sentence. */+ before?: string;+ /** The text after `text` on its line, to tell if `text` ends a sentence. */+ after?: string;+}++/**+ * Applies `operation` to `lines` and returns the new lines. Sorting uses `autoSort`, so numbers,+ * dates and times sort by their value and blank lines go last. Deduplication keeps the first copy.+ */+export function transformLines(+ lines: readonly string[],+ operation: LineOperation,+ options: LineOperationOptions = {}+): string[] {+ switch (operation) {+ case "sortAscending":+ case "sortDescending":+ return autoSort(lines, (line) => line, {+ locale: options.locale,+ dateFormats: options.dateFormats,+ isDescending: operation === "sortDescending"+ });+ case "shuffle":+ return shuffle(lines, options.random ?? Math.random);+ case "reverse":+ return lines.toReversed();+ case "deduplicate":+ return [ ...new Set(lines) ];+ case "trimLeading":+ return lines.map((line) => line.trimStart());+ case "trimTrailing":+ return lines.map((line) => line.trimEnd());+ case "trimBoth":+ return lines.map((line) => line.trim());+ case "removeBlankLines":+ return lines.filter((line) => line.trim() !== "");+ }+}++/**+ * Applies `transform` to `text` and returns the new text. Case changes follow the rules of the+ * locale, such as the dotted capital İ of Turkish. Sentence case and title case lowercase the text,+ * then capitalize the first word of each sentence, or each word except minor words such as "of".+ * A line break ends a sentence.+ */+export function transformText(+ text: string,+ transform: TextTransform,+ options: TextTransformOptions = {}+): string {+ const locale = toLanguageTag(options.locale ?? new Intl.Collator().resolvedOptions().locale);++ switch (transform) {+ case "upperCase":+ return text.toLocaleUpperCase(locale);+ case "lowerCase":+ return text.toLocaleLowerCase(locale);+ case "sentenceCase":+ return changeWordCase(text, locale, options, (word) => word.isSentenceStart);+ case "titleCase": {+ const minorWords = MINOR_WORDS.get(languageOf(locale));+ const isMinor = (word: Word) => !!minorWords?.has(word.text.toLocaleLowerCase(locale));+ return changeWordCase(text, locale, options, (word, next) =>+ word.isSentenceStart || !next || next.isSentenceStart || !isMinor(word));+ }+ case "removeDiacritics":+ return removeDiacritics(text);+ }+}++interface Word {+ start: number;+ end: number;+ text: string;+ /** Whether the word is the first one of its line or comes after a sentence terminator. */+ isSentenceStart: boolean;+}++// A letter or a digit, then letters, marks and digits, with apostrophes inside: "don't", "l'eau".+const WORD = /[\p{L}\p{N}][\p{L}\p{M}\p{N}]*(?:['’][\p{L}\p{M}\p{N}]+)*/gu;+// A line break, or a sentence terminator with any closing quotes and brackets, then whitespace.+const SENTENCE_BREAK = /[\n\r\u{2028}\u{2029}]|\p{Sentence_Terminal}\S*\s/u;++/** Words that title case keeps in lowercase, except as the first or last word of a sentence. */+const MINOR_WORDS = new Map(Object.entries({+ de: "an am auf aus bei das dem den der des die ein eine einem einen einer eines für im in mit "+ + "nach oder über und unter von vor zu zum zur",+ en: "a an and as at but by for in nor of on or per the to via vs",+ es: "a al con de del e el en la las lo los o para por sin sobre u un una unas unos y",+ fr: "à au aux avec dans de des du en et la le les ou par pour sans sur un une",+ it: "a al alla con da dei del della delle di e fra gli i il in la le lo nel nella o per su tra "+ + "un una uno",+ nl: "aan bij de een en het in met of om op te uit van voor",+ pt: "a as com da das de do dos e em na nas no nos o os ou para por sem um uma",+ ro: "a al ale cu de din în la o ori pe sau și un"+}).map(([ language, words ]) => [ language, new Set(words.split(" ")) ]));++/** The lowercase letters whose capital is not their uppercase: Latin digraphs such as "dž". */+const TITLE_CASE_LETTERS = new Map([ [ "dž", "Dž" ], [ "lj", "Lj" ], [ "nj", "Nj" ], [ "dz", "Dz" ] ]);+// Georgian Mkhedruli letters, whose uppercase (Mtavruli) is only for text in all caps.+const GEORGIAN = /[\u{10d0}-\u{10fa}\u{10fd}-\u{10ff}]/u;++// A letter with combining marks, or a letter that can be precomposed with a diacritic: not ASCII,+// kana, CJK or Hangul. A mark on a symbol stays, such as the slash of "≠" or a keycap emoji.+const LETTER = /\p{L}\p{M}+|[^\P{L}\0-\x7f\u{3040}-\u{9fff}\u{ac00}-\u{d7af}\u{f900}-\u{faff}]/gu;+// Diacritics, but not the marks that are part of the spelling, such as Devanagari vowel signs,+// Thai vowels and the kana voicing marks.+const DIACRITIC = new RegExp([+ // Combining diacritical marks and the blocks that extend them.+ "[\u{0300}-\u{036f}\u{1ab0}-\u{1aff}\u{1dc0}-\u{1dff}\u{20d0}-\u{20ff}\u{fe20}-\u{fe2f}]",+ // Hebrew points and cantillation marks.+ "[\u{0591}-\u{05bd}\u{05bf}\u{05c1}\u{05c2}\u{05c4}\u{05c5}\u{05c7}]",+ // Arabic vowel marks and Quranic annotation marks.+ "[\u{0610}-\u{061a}\u{064b}-\u{065f}\u{0670}]",+ "[\u{06d6}-\u{06dc}\u{06df}-\u{06e4}\u{06e7}\u{06e8}\u{06ea}-\u{06ed}]"+].join("|"), "gu");+/** Letters with a stroke, a bar or a middle dot, which Unicode does not decompose. */+const PLAIN_LETTERS = new Map([+ [ "Ⱥ", "A" ], [ "ⱥ", "a" ], [ "Ƀ", "B" ], [ "ƀ", "b" ], [ "Ȼ", "C" ], [ "ȼ", "c" ],+ [ "Đ", "D" ], [ "đ", "d" ], [ "Ɇ", "E" ], [ "ɇ", "e" ], [ "Ǥ", "G" ], [ "ǥ", "g" ],+ [ "Ħ", "H" ], [ "ħ", "h" ], [ "Ɨ", "I" ], [ "ɨ", "i" ], [ "Ɉ", "J" ], [ "ɉ", "j" ],+ [ "Ŀ", "L" ], [ "ŀ", "l" ], [ "Ł", "L" ], [ "ł", "l" ], [ "Ø", "O" ], [ "ø", "o" ],+ [ "Ɍ", "R" ], [ "ɍ", "r" ], [ "Ŧ", "T" ], [ "ŧ", "t" ], [ "Ʉ", "U" ], [ "ʉ", "u" ],+ [ "Ɏ", "Y" ], [ "ɏ", "y" ], [ "Ƶ", "Z" ], [ "ƶ", "z" ]+]);++function shuffle(lines: readonly string[], random: () => number) {+ const result = [ ...lines ];+ // Fisher-Yates.+ for (let i = result.length - 1; i > 0; i--) {+ const j = Math.floor(random() * (i + 1));+ [ result[i], result[j] ] = [ result[j], result[i] ];+ }+ return result;+}++/**+ * Lowercases the words of `text` and capitalizes those that `isCapital` picks. The words are found+ * in the whole line, so a word or a sentence that starts before `text` is not capitalized again.+ */+function changeWordCase(+ text: string,+ locale: string,+ { before = "", after = "" }: TextTransformOptions,+ isCapital: (word: Word, next: Word | undefined) => boolean+) {+ const line = before + text + after;+ const start = before.length;+ const end = start + text.length;+ const words = findWords(line);++ let result = "";+ let position = start;+ for (const [ index, word ] of words.entries()) {+ if (word.end <= start) continue;+ if (word.start >= end) break;++ const from = Math.max(word.start, start);+ const to = Math.min(word.end, end);+ const part = line.slice(from, to);+ const isCapitalized = from === word.start && isCapital(word, words[index + 1]);+ result += line.slice(position, from)+ + (isCapitalized ? capitalize(part, locale) : part.toLocaleLowerCase(locale));+ position = to;+ }+ return result + line.slice(position, end);+}++function findWords(line: string): Word[] {+ const words: Word[] = [];+ let previousEnd = 0;+ for (const match of line.matchAll(WORD)) {+ const [ text ] = match;+ const start = match.index;+ words.push({+ start,+ end: start + text.length,+ text,+ isSentenceStart: !words.length || SENTENCE_BREAK.test(line.slice(previousEnd, start))+ });+ previousEnd = start + text.length;+ }+ return words;+}++/** Lowercases `word` and gives it a capital first letter. */+function capitalize(word: string, locale: string) {+ // Lowercased as a whole, so that a Greek sigma at the end of the word becomes "ς".+ const lower = word.toLocaleLowerCase(locale);+ // Dutch writes the digraph "ij" as one letter: "IJsselmeer".+ if (languageOf(locale) === "nl" && lower.startsWith("ij")) {+ return `IJ${lower.slice(2)}`;+ }++ const [ first ] = lower;+ return toCapitalLetter(first, locale) + lower.slice(first.length);+}++function toCapitalLetter(letter: string, locale: string) {+ const titleCase = TITLE_CASE_LETTERS.get(letter);+ if (titleCase) {+ return titleCase;+ }+ if (GEORGIAN.test(letter)) {+ return letter;+ }++ // Greek drops the accents only in text written in all caps.+ const upper = languageOf(locale) === "el"+ ? letter.toUpperCase()+ : letter.toLocaleUpperCase(locale);+ // A letter such as "ß" uppercases to two, "SS", and only the first one is a capital.+ const [ first ] = upper;+ return first + upper.slice(first.length).toLocaleLowerCase(locale);+}++function languageOf(locale: string) {+ return locale.split("-")[0];+}++/**+ * Removes the diacritics from the letters of `text`. A letter without a diacritic is not+ * normalized, because normalization also changes letters such as the Ohm sign.+ */+function removeDiacritics(text: string) {+ return text.replace(LETTER, (original) => {+ const decomposed = original.normalize("NFD");+ const stripped = decomposed.replace(DIACRITIC, "");+ const letter = stripped === decomposed ? original : stripped.normalize("NFC");+ return PLAIN_LETTERS.get(letter) ?? letter;+ });+}