Skip to content

Build your personal knowledge base with Trilium Notes

feat(text): indent paragraphs led by tabs when pasting plain text

Elian Dorand464633239fe
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.html
index 011885e192..ab13e5e2e0 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
@@ -25,6 +25,9 @@
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>
+<p>The reverse also works: when plain text is pasted into a text note, each
+ paragraph whose lines all start with tabs is indented by one level per
+ tab. Pasting into a code block keeps the tabs as they are.</p>
<h2>Markdown import</h2>
<p>If the clipboard contains Markdown text, it can be easily imported into
text notes. Simply copy a Markdown-formatted text and press the&nbsp;<span
diff --git a/docs/User Guide/User Guide/Note Types/Text/Other features.md b/docs/User Guide/User Guide/Note Types/Text/Other features.md
index 02fb5cd6fd..7ab73bb082 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
@@ -12,6 +12,8 @@ Paragraphs can be indented using the following buttons from the <a class="refer
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.
+The reverse also works: when plain text is pasted into a text note, each paragraph whose lines all start with tabs is indented by one level per tab. Pasting into a code block keeps the tabs as they are.
+
## Markdown import
If 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/clipboard_plain_text_indent.spec.ts b/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.spec.ts
index 46e177bc08..c6b33ec6c5 100644
--- a/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.spec.ts
+++ b/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.spec.ts
@@ -1,4 +1,4 @@
-import { _setModelData as setModelData, Essentials, Heading, Indent, IndentBlock, Paragraph } from "ckeditor5";
+import { _setModelData as setModelData, CodeBlock, Essentials, Heading, Indent, IndentBlock, Paragraph } from "ckeditor5";
import type { ClassicEditor, ViewDocumentFragment } from "ckeditor5";
import { describe, expect, it } from "vitest";
@@ -94,6 +94,86 @@ describe("ClipboardPlainTextIndent", () => {
expect(viewToIndentedPlainText(editor, content)).not.toContain("\t");
});
+
+ describe("on paste", () => {
+ const PLUGINS = [Essentials, Paragraph, Indent, IndentBlock, CodeBlock];
+
+ async function pasteInto(text: string, { html = "", plugins = [...PLUGINS, ClipboardPlainTextIndent], config = {} } = {}) {
+ const editor = await createTestEditor(plugins, config);
+ paste(editor, text, html);
+ return editor.getData();
+ }
+
+ function paste(editor: ClassicEditor, text: string, html = "") {
+ const dataTransfer = recordingDataTransfer();
+ dataTransfer.setData("text/plain", text);
+ if (html) {
+ dataTransfer.setData("text/html", html);
+ }
+ editor.editing.view.document.fire("paste", { dataTransfer, preventDefault: () => {}, stopPropagation: () => {} });
+ }
+
+ it("turns lines led by tabs into paragraphs indented one level per tab", async () => {
+ const text = [
+ "Plain text", "\tOne", "\t\tTwo", "\t\t\tThree", "\t\t\tThree again", "\t\tTwo", "\tOne", "Plain text"
+ ].join("\n\n");
+
+ expect(await pasteInto(text)).toBe([
+ "<p>Plain text</p>",
+ `<p style="margin-left:40px;">One</p>`,
+ `<p style="margin-left:80px;">Two</p>`,
+ `<p style="margin-left:120px;">Three</p>`,
+ `<p style="margin-left:120px;">Three again</p>`,
+ `<p style="margin-left:80px;">Two</p>`,
+ `<p style="margin-left:40px;">One</p>`,
+ "<p>Plain text</p>"
+ ].join(""));
+ });
+
+ it("indents a paragraph by the tabs all of its lines share", async () => {
+ const data = await pasteInto("\t\tDeeper\n\tShallower\n\n\tSame\n\tSame\n\nNone\n\tSome");
+
+ expect(data).toMatch(/^<p style="margin-left:40px;">(&nbsp;| )+Deeper<br>Shallower<\/p>/);
+ expect(data).toContain(`<p style="margin-left:40px;">Same<br>Same</p>`);
+ expect(data).toMatch(/<p>None<br>(&nbsp;| )+Some<\/p>$/);
+ });
+
+ it("restores what a copy of indented paragraphs wrote", async () => {
+ const html = `<p>Top</p><p style="margin-left:40px;">One<br>Two</p><p style="margin-left:80px;">Deep</p>`;
+ const source = await createEditor(html);
+
+ expect(await pasteInto(copy(source).getData("text/plain"))).toBe(html);
+ });
+
+ it("counts levels in the configured offset and indents right-to-left content on the right", async () => {
+ expect(await pasteInto("\t\tTwo", { config: { indentBlock: { offset: 2, unit: "em" } } }))
+ .toBe(`<p style="margin-left:4em;">Two</p>`);
+ expect(await pasteInto("\tShalom", { config: { language: { content: "he" } } }))
+ .toBe(`<p style="margin-right:40px;">Shalom</p>`);
+ });
+
+ it("keeps the tabs of a paste into a code block", async () => {
+ const editor = await createTestEditor([...PLUGINS, ClipboardPlainTextIndent]);
+ setModelData(editor.model, `<codeBlock language="plaintext">[]</codeBlock>`);
+ paste(editor, "\tfoo\n\tbar");
+
+ expect(editor.getData()).toBe(`<pre><code class="language-plaintext">\tfoo\n\tbar</code></pre>`);
+ });
+
+ it("leaves the paste to CKEditor when there is HTML, no leading tab, or no margin-based indent", async () => {
+ const cases: [string, Parameters<typeof pasteInto>[1]][] = [
+ ["\tTabbed", { html: "<p>Tabbed</p>" }],
+ ["Inner\ttab\n\nNo indent", {}],
+ ["\tTabbed", { config: { indentBlock: { classes: ["indent-1", "indent-2"] } } }],
+ ["\tTabbed", { plugins: [Essentials, Paragraph, ClipboardPlainTextIndent] }]
+ ];
+
+ for (const [text, options] of cases) {
+ const plugins = (options?.plugins ?? PLUGINS).filter((plugin) => plugin !== ClipboardPlainTextIndent);
+ expect(await pasteInto(text, options)).toBe(await pasteInto(text, { ...options, plugins }));
+ }
+ });
+ });
});
function recordingDataTransfer() {
diff --git a/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.ts b/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.ts
index 167a33d015..69f87509fe 100644
--- a/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.ts
+++ b/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.ts
@@ -1,5 +1,5 @@
-import { ClipboardPipeline, Plugin, UpcastWriter, viewToPlainText } from "ckeditor5";
-import type { Editor, EditingView, ViewDocumentClipboardOutputEvent, ViewDocumentFragment, ViewElement, ViewNode } from "ckeditor5";
+import { ClipboardPipeline, Plugin, plainTextToHtml, UpcastWriter, viewToPlainText } from "ckeditor5";
+import type { Editor, EditingView, ViewDocumentClipboardInputEvent, 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"]);
@@ -11,6 +11,10 @@ const INDENTABLE_BLOCKS = new Set(["p", "h1", "h2", "h3", "h4", "h5", "h6"]);
* 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.
+ *
+ * In the other direction, a paste that carries only plain text turns the tabs that lead every line of
+ * a paragraph into that paragraph's indent, so the copy round-trips. A paste into a code block keeps
+ * its tabs, as `CodeBlockEditing` rebuilds the content from the plain text after this plugin.
*/
export default class ClipboardPlainTextIndent extends Plugin {
@@ -34,9 +38,52 @@ export default class ClipboardPlainTextIndent extends Plugin {
},
{ priority: "lowest" }
);
+
+ // `high`, to replace the HTML before `ClipboardPipeline` converts it at `low` priority.
+ this.listenTo<ViewDocumentClipboardInputEvent>(
+ this.editor.editing.view.document,
+ "clipboardInput",
+ (_evt, data) => {
+ if (data.dataTransfer.getData("text/html")) {
+ return;
+ }
+
+ const html = indentedPlainTextToHtml(this.editor, data.dataTransfer.getData("text/plain"));
+ if (html) {
+ data.content = html;
+ }
+ },
+ { priority: "high" }
+ );
}
}
+/**
+ * Converts plain text to HTML as `plainTextToHtml()` does, with the tabs that lead every line of a
+ * paragraph turned into that paragraph's indent: one level per tab, as a margin `IndentBlock` reads
+ * back. Returns `null` when no line starts with a tab, or when `IndentBlock` is not loaded or
+ * indents with classes.
+ */
+export function indentedPlainTextToHtml(editor: Editor, text: string): string | null {
+ if (!/^\t/m.test(text) || !editor.plugins.has("IndentBlock") || editor.config.get("indentBlock")?.classes?.length) {
+ return null;
+ }
+
+ const offset = indentOffset(editor);
+ const side = editor.locale.contentLanguageDirection === "rtl" ? "right" : "left";
+
+ return text.split(/\r?\n\r?\n/).map((paragraph) => {
+ const lines = paragraph.split(/\r?\n/);
+ const level = Math.min(...lines.filter((line) => line.trim()).map(leadingTabs));
+ const indented = Number.isFinite(level) && level > 0;
+ const body = plainTextToHtml(indented ? lines.map((line) => line.slice(level)).join("\n") : paragraph)
+ .replace(/^<p>([\s\S]*)<\/p>$/, "$1");
+ const style = indented ? ` style="margin-${side}:${level * offset.value}${offset.unit}"` : "";
+
+ return `<p${style}>${body}</p>`;
+ }).join("");
+}
+
/**
* 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.
@@ -109,6 +156,10 @@ function indentLevel(block: ViewElement, offset: { value: number; unit: string }
return match[2] === offset.unit ? Math.max(1, Math.round(value / offset.value)) : 1;
}
+function leadingTabs(line: string) {
+ return line.length - line.replace(/^\t+/, "").length;
+}
+
/** 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"));