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
feat(text): keep block indentation when copying as plain text (closes #1442)
Elian Doranea887f3747dc
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Other features.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Other features.htmlindex 28de4cb494..011885e192 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Other features.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Other features.html@@ -20,6 +20,11 @@href="#root/_help_S6Xx8QIWTV66">Lists</a> (for nesting) and <aclass="reference-link" href="#root/_help_NdowYOC1GFKS">Tables</a>.</li></ul>+<p>When indented paragraphs or headings are copied and pasted as plain text,+ for example into a <a class="reference-link" href="#root/_help_6f9hih2hXXZk">Code</a> note+ or another application, each indentation level becomes a tab at the start+ of the line. A copy that stays within a single paragraph contains only+ its text, without the indentation.</p><h2>Markdown import</h2><p>If the clipboard contains Markdown text, it can be easily imported intotext notes. Simply copy a Markdown-formatted text and press the <spandiff --git a/docs/User Guide/User Guide/Note Types/Text/Other features.md b/docs/User Guide/User Guide/Note Types/Text/Other features.mdindex 443336e772..02fb5cd6fd 100644--- a/docs/User Guide/User Guide/Note Types/Text/Other features.md+++ b/docs/User Guide/User Guide/Note Types/Text/Other features.md@@ -10,6 +10,8 @@ Paragraphs can be indented using the following buttons from the <a class="refer* For convenience, keyboard shortcuts are also available. Press <kbd>Tab</kbd> to indent or <kbd>Shift</kbd>+<kbd>Tab</kbd> to decrease the indentation. These shortcuts work even if the cursor is not at the beginning of a paragraph or a list.* Apart from paragraphs, the indent button is also enabled in <a class="reference-link" href="Lists.md">Lists</a> (for nesting) and <a class="reference-link" href="Tables.md">Tables</a>.+When indented paragraphs or headings are copied and pasted as plain text, for example into a <a class="reference-link" href="../Code.md">Code</a> note or another application, each indentation level becomes a tab at the start of the line. A copy that stays within a single paragraph contains only its text, without the indentation.+## Markdown importIf the clipboard contains Markdown text, it can be easily imported into text notes. Simply copy a Markdown-formatted text and press the <span class="tn-icon cke cke-trilium-markdown-mark"></span> to insert its visual representation.diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.tsindex 6c775a2b57..29899a1318 100644--- a/packages/ckeditor5/src/plugins.ts+++ b/packages/ckeditor5/src/plugins.ts@@ -42,6 +42,7 @@ import ImageActions from "./plugins/image_actions.js";import ClipboardBareImage from "./plugins/clipboard_bare_image.js";import ClipboardImageEmbed from "./plugins/clipboard_image_embed.js";import ClipboardPageStyles from "./plugins/clipboard_page_styles.js";+import ClipboardPlainTextIndent from "./plugins/clipboard_plain_text_indent.js";import PasteFromVsCode from "./plugins/paste_from_vscode.js";import TriliumSnippets from "./plugins/snippets/snippets.js";import TriliumAiAssistant from "./plugins/ai_assistant/ai_assistant.js";@@ -121,6 +122,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [ClipboardImageEmbed,ClipboardBareImage,ClipboardPageStyles,+ ClipboardPlainTextIndent,PasteFromVsCode,AdaptiveColors,TriliumSnippets,diff --git a/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.spec.ts b/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.spec.tsnew file mode 100644index 0000000000..46e177bc08--- /dev/null+++ b/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.spec.ts@@ -0,0 +1,106 @@+import { _setModelData as setModelData, Essentials, Heading, Indent, IndentBlock, Paragraph } from "ckeditor5";+import type { ClassicEditor, ViewDocumentFragment } from "ckeditor5";+import { describe, expect, it } from "vitest";++import { createTestEditor } from "../../test/editor-kit.js";+import ClipboardPlainTextIndent, { viewToIndentedPlainText } from "./clipboard_plain_text_indent.js";++describe("ClipboardPlainTextIndent", () => {+ async function createEditor(html: string, extraConfig = {}) {+ const editor = await createTestEditor(+ [Essentials, Paragraph, Heading, Indent, IndentBlock, ClipboardPlainTextIndent],+ extraConfig+ );+ editor.setData(html);+ editor.execute("selectAll");+ return editor;+ }++ function copy(editor: ClassicEditor) {+ const dataTransfer = recordingDataTransfer();+ editor.editing.view.document.fire("copy", { dataTransfer, preventDefault: () => {}, method: "copy" });+ return dataTransfer;+ }++ it("prefixes each indented block with one tab per indent level", async () => {+ const editor = await createEditor([+ "<p>Top</p>",+ `<p style="margin-left:40px">One</p>`,+ `<p style="margin-left:80px">Two</p>`,+ `<h2 style="margin-left:40px">Heading</h2>`,+ "<p>Back</p>"+ ].join(""));++ expect(copy(editor).getData("text/plain")).toBe("Top\n\n\tOne\n\n\t\tTwo\n\n\tHeading\n\nBack");+ });++ it("indents every line of a block that holds soft breaks, but not past a trailing one", async () => {+ const editor = await createEditor(`<p style="margin-left:40px">First<br>Second<br><strong>Third<br></strong></p><p>End</p>`);++ expect(copy(editor).getData("text/plain")).toBe("\tFirst\n\tSecond\n\tThird\n\n\nEnd");+ });++ it("writes nothing for a copy of an empty selection", async () => {+ const editor = await createEditor(`<p style="margin-left:40px">One</p>`);+ setModelData(editor.model, `<paragraph blockIndent="40px">[]One</paragraph>`);++ expect(copy(editor).store).not.toHaveProperty("text/plain");+ });++ it("leaves a copy inside one block unindented, as CKEditor copies only its text", async () => {+ const editor = await createEditor(`<p style="margin-left:40px">One</p>`);++ expect(copy(editor).getData("text/plain")).toBe("One");+ });++ it("leaves the HTML flavor untouched", async () => {+ const editor = await createEditor(`<p style="margin-left:40px">One</p><p>Two</p>`);++ expect(copy(editor).getData("text/html")).toBe(`<p style="margin-left:40px;">One</p><p>Two</p>`);+ });++ it("counts levels against the configured offset and gives a foreign unit one level", async () => {+ const editor = await createEditor(+ `<p style="margin-left:4em">Two</p><p style="margin-left:15px">Foreign</p>`,+ { indentBlock: { offset: 2, unit: "em" } }+ );++ expect(copy(editor).getData("text/plain")).toBe("\t\tTwo\n\n\tForeign");+ });++ it("reads the right margin of right-to-left content", async () => {+ const editor = await createEditor(`<p style="margin-right:40px">Shalom</p><p>End</p>`, { language: { content: "he" } });++ expect(copy(editor).getData("text/plain")).toBe("\tShalom\n\nEnd");+ });++ it("serializes a fragment without changing it", async () => {+ const editor = await createEditor(`<p>One</p><p style="margin-left:40px">Two<br>Three</p>`);+ const content = editor.data.toView(+ editor.model.getSelectedContent(editor.model.document.selection),+ { isClipboardPipeline: true }+ );+ const before = editor.data.processor.toData(content);++ expect(viewToIndentedPlainText(editor, content)).toBe("One\n\n\tTwo\n\tThree");+ expect(editor.data.processor.toData(content)).toBe(before);+ });++ it("does not indent a block whose margin is zero or not a length", async () => {+ const editor = await createEditor("");+ const content = editor.data.processor.toView(+ `<p style="margin-left:0px">Zero</p><p style="margin-left:auto">Auto</p>`+ ) as ViewDocumentFragment;++ expect(viewToIndentedPlainText(editor, content)).not.toContain("\t");+ });+});++function recordingDataTransfer() {+ const store: Record<string, string> = {};+ return {+ store,+ setData: (type: string, data: string) => { store[type] = data; },+ getData: (type: string) => store[type] ?? ""+ };+}diff --git a/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.ts b/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.tsnew file mode 100644index 0000000000..167a33d015--- /dev/null+++ b/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.ts@@ -0,0 +1,116 @@+import { ClipboardPipeline, Plugin, UpcastWriter, viewToPlainText } from "ckeditor5";+import type { Editor, EditingView, ViewDocumentClipboardOutputEvent, ViewDocumentFragment, ViewElement, ViewNode } from "ckeditor5";++/** The blocks that `IndentBlock` indents with a margin. */+const INDENTABLE_BLOCKS = new Set(["p", "h1", "h2", "h3", "h4", "h5", "h6"]);++/**+ * Keeps block indentation in the `text/plain` clipboard flavor.+ *+ * `IndentBlock` stores an indent as a `margin-left` style, which CKEditor's `viewToPlainText()`+ * drops, so text pasted into a code note or another application loses it. The plugin rewrites the+ * `text/plain` flavor with one tab per indent level at the start of each line of an indented block.+ * The `text/html` flavor keeps the margin and is left as it is.+ */+export default class ClipboardPlainTextIndent extends Plugin {++ static get requires() {+ return [ClipboardPipeline] as const;+ }++ static get pluginName() {+ return "ClipboardPlainTextIndent" as const;+ }++ init() {+ // `lowest`, so that the text replaces the one `ClipboardPipeline` sets at `low`.+ this.listenTo<ViewDocumentClipboardOutputEvent>(+ this.editor.editing.view.document,+ "clipboardOutput",+ (_evt, data) => {+ if (!data.content.isEmpty) {+ data.dataTransfer.setData("text/plain", viewToIndentedPlainText(this.editor, data.content));+ }+ },+ { priority: "lowest" }+ );+ }+}++/**+ * Serializes `fragment` to plain text as `viewToPlainText()` does, with each line of an indented+ * block prefixed by one tab per indent level. The fragment is unchanged afterwards.+ */+export function viewToIndentedPlainText(editor: Editor, fragment: ViewDocumentFragment): string {+ const view = editor.editing.view;+ const writer = new UpcastWriter(view.document);+ const offset = indentOffset(editor);++ const insertions: { parent: ViewElement; index: number; tabs: string }[] = [];+ for (const { item } of view.createRangeIn(fragment)) {+ if (!item.is("element") || !INDENTABLE_BLOCKS.has(item.name)) {+ continue;+ }++ const level = indentLevel(item, offset);+ if (!level) {+ continue;+ }++ const tabs = "\t".repeat(level);+ insertions.push({ parent: item, index: 0, tabs });+ for (const { item: inner } of view.createRangeIn(item)) {+ if (inner.is("element", "br") && inner.parent?.is("element") && inner.index !== null+ && !isLastInBlock(view, inner, item)) {+ insertions.push({ parent: inner.parent, index: inner.index + 1, tabs });+ }+ }+ }++ // Inserting from the last position backwards keeps the earlier indexes valid.+ const inserted: ViewNode[] = [];+ for (const { parent, index, tabs } of insertions.reverse()) {+ const text = writer.createText(tabs);+ writer.insertChild(index, text, parent);+ inserted.push(text);+ }++ try {+ return viewToPlainText(editor.data.htmlProcessor.domConverter, fragment);+ } finally {+ for (const text of inserted) {+ writer.remove(text);+ }+ }+}++/** The width of one indent level, from the `indentBlock` config `IndentBlock` defaults to `40px`. */+function indentOffset(editor: Editor) {+ const config = editor.config.get("indentBlock");+ return { value: config?.offset ?? 40, unit: config?.unit ?? "px" };+}++/**+ * The number of indent levels of `block`. A margin in another unit than the configured one, such as+ * one pasted from a word processor, counts as one level.+ */+function indentLevel(block: ViewElement, offset: { value: number; unit: string }) {+ const margin = block.getStyle("margin-left") ?? block.getStyle("margin-right");+ const match = margin?.trim().match(/^(\d*\.?\d+)([a-z%]*)$/i);+ if (!match) {+ return 0;+ }++ const value = Number(match[1]);+ if (value <= 0) {+ return 0;+ }++ return match[2] === offset.unit ? Math.max(1, Math.round(value / offset.value)) : 1;+}++/** Whether nothing follows `node` inside `block`, so a line break there starts no new line of text. */+function isLastInBlock(view: EditingView, node: ViewNode, block: ViewElement) {+ const rest = view.createRange(view.createPositionAfter(node), view.createPositionAt(block, "end"));+ return rest.getItems().next().done === true;+}diff --git a/packages/ckeditor5/src/plugins/cuttonote.spec.ts b/packages/ckeditor5/src/plugins/cuttonote.spec.tsindex c56475ca36..7f95e520a6 100644--- a/packages/ckeditor5/src/plugins/cuttonote.spec.ts+++ b/packages/ckeditor5/src/plugins/cuttonote.spec.ts@@ -3,6 +3,8 @@ import {_setModelData as setModelData,ClassicEditor,Essentials,+ Indent,+ IndentBlock,List,Paragraph,Table,@@ -89,6 +91,13 @@ describe("CutToNotePlugin", () => {expect(editor.getSelectedPlainText()).toBe("bar");});+ it("keeps block indentation in getSelectedPlainText, as a native copy does", async () => {+ const indentEditor = await createTestEditor([Essentials, Paragraph, Indent, IndentBlock, CutToNotePlugin]);+ setModelData(indentEditor.model, `<paragraph>[One</paragraph><paragraph blockIndent="80px">Two]</paragraph>`);++ expect(indentEditor.getSelectedPlainText()).toBe("One\n\n\t\tTwo");+ });+it("pasteContent runs the given flavors through the clipboard paste pipeline", () => {setModelData(editor.model, "<paragraph>a[]b</paragraph>");editor.pasteContent("<span>X</span>", "X");diff --git a/packages/ckeditor5/src/plugins/cuttonote.ts b/packages/ckeditor5/src/plugins/cuttonote.tsindex c7853c6c33..3b5105cd22 100644--- a/packages/ckeditor5/src/plugins/cuttonote.ts+++ b/packages/ckeditor5/src/plugins/cuttonote.ts@@ -5,11 +5,12 @@ import {ModelLiveRange,Plugin,plainTextToHtml,- ViewDataTransfer,- viewToPlainText+ ViewDataTransfer} from 'ckeditor5';import type { ModelRange, ViewDocumentFragment } from 'ckeditor5';+import { viewToIndentedPlainText } from './clipboard_plain_text_indent.js';+/** A selection pinned by `capturePasteTarget()` for a paste whose content arrives later. */export interface PasteTarget {/**@@ -67,11 +68,11 @@ export default class CutToNotePlugin extends Plugin {}/**- * Returns the selected content as plain text, through the same `viewToPlainText` the native- * copy uses for the `text/plain` clipboard flavor.+ * Returns the selected content as plain text, through the same `viewToIndentedPlainText()` the+ * native copy uses for the `text/plain` clipboard flavor.*/getSelectedPlainText() {- return viewToPlainText(this.editor.editing.view.domConverter, this.getSelectedViewFragment());+ return viewToIndentedPlainText(this.editor, this.getSelectedViewFragment());}/**