Skip to content

Build your personal knowledge base with Trilium Notes

fix(text): keep blank lines and menu pastes in plain-text indentation

Elian Doran07e507ebc38a
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 c6b33ec6c5..fde4d3a5f9 100644
--- a/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.spec.ts
+++ b/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.spec.ts
@@ -136,10 +136,14 @@ describe("ClipboardPlainTextIndent", () => {
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>$/);
+
+ expect(await pasteInto("\tOne\n\n\n\n\tTwo")).toBe(
+ `<p style="margin-left:40px;">One</p><p>&nbsp;</p><p style="margin-left:40px;">Two</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 html = `<p>Top</p><p style="margin-left:40px;">One<br><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);
diff --git a/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.ts b/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.ts
index 69f87509fe..9bcc303efd 100644
--- a/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.ts
+++ b/packages/ckeditor5/src/plugins/clipboard_plain_text_indent.ts
@@ -5,16 +5,8 @@ import type { Editor, EditingView, ViewDocumentClipboardInputEvent, ViewDocument
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.
- *
- * 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.
+ * Writes `IndentBlock` indents to the `text/plain` clipboard flavor as one tab per level, and reads
+ * them back from a paste that carries only plain text.
*/
export default class ClipboardPlainTextIndent extends Plugin {
@@ -59,10 +51,8 @@ export default class ClipboardPlainTextIndent extends Plugin {
}
/**
- * 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.
+ * Converts plain text to HTML, indenting each paragraph by the tabs that lead all of its lines.
+ * Returns `null` when no line starts with a tab or `IndentBlock` cannot read back a margin.
*/
export function indentedPlainTextToHtml(editor: Editor, text: string): string | null {
if (!/^\t/m.test(text) || !editor.plugins.has("IndentBlock") || editor.config.get("indentBlock")?.classes?.length) {
@@ -74,19 +64,19 @@ export function indentedPlainTextToHtml(editor: Editor, text: string): string |
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}"` : "";
+ const level = sharedTabs(lines);
+ const strip = new RegExp(`^\\t{0,${level}}`);
+ // Converted line by line, so that a blank line stays a `<br>` inside the paragraph.
+ const body = lines.map((line) => plainTextToHtml(line.replace(strip, ""))).join("<br>");
+ const style = level ? ` 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.
+ * Serializes `fragment` as `viewToPlainText()` does, prefixing each line of an indented block with
+ * one tab per level. The fragment is unchanged afterwards.
*/
export function viewToIndentedPlainText(editor: Editor, fragment: ViewDocumentFragment): string {
const view = editor.editing.view;
@@ -137,10 +127,7 @@ function indentOffset(editor: Editor) {
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.
- */
+/** The indent levels of `block`. A margin in a unit other than the configured one counts as one. */
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);
@@ -156,8 +143,16 @@ 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;
+/** The number of tabs that lead every non-blank line, or 0 when all lines are blank. */
+function sharedTabs(lines: string[]) {
+ let shared = Infinity;
+ for (const line of lines) {
+ if (line.trim()) {
+ shared = Math.min(shared, line.length - line.replace(/^\t+/, "").length);
+ }
+ }
+
+ return Number.isFinite(shared) ? shared : 0;
}
/** Whether nothing follows `node` inside `block`, so a line break there starts no new line of text. */
diff --git a/packages/ckeditor5/src/plugins/cuttonote.spec.ts b/packages/ckeditor5/src/plugins/cuttonote.spec.ts
index 7f95e520a6..3e98f89529 100644
--- a/packages/ckeditor5/src/plugins/cuttonote.spec.ts
+++ b/packages/ckeditor5/src/plugins/cuttonote.spec.ts
@@ -2,6 +2,7 @@ import {
_getModelData as getModelData,
_setModelData as setModelData,
ClassicEditor,
+ CodeBlock,
Essentials,
Indent,
IndentBlock,
@@ -14,6 +15,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
import { installGlobMock } from "../../test/globals-test-kit.js";
+import ClipboardPlainTextIndent from "./clipboard_plain_text_indent.js";
import CutToNotePlugin from "./cuttonote.js";
describe("CutToNotePlugin", () => {
@@ -114,6 +116,27 @@ describe("CutToNotePlugin", () => {
expect(editor.getData()).toContain("ef");
});
+ describe("pasteContent hands the flavors to the paste listeners, as a native paste does", () => {
+ let pasteEditor: ClassicEditor;
+
+ beforeEach(async () => {
+ pasteEditor = await createTestEditor([
+ Essentials, Paragraph, Indent, IndentBlock, CodeBlock, ClipboardPlainTextIndent, CutToNotePlugin
+ ]);
+ });
+
+ it("indents plain text led by tabs", () => {
+ pasteEditor.pasteContent("", "\tIndented");
+ expect(pasteEditor.getData()).toBe(`<p style="margin-left:40px;">Indented</p>`);
+ });
+
+ it("pastes plain text into a code block", () => {
+ setModelData(pasteEditor.model, `<codeBlock language="plaintext">[]</codeBlock>`);
+ pasteEditor.pasteContent("", "\tfoo");
+ expect(pasteEditor.getData()).toBe(`<pre><code class="language-plaintext">\tfoo</code></pre>`);
+ });
+ });
+
describe("capturePasteTarget", () => {
it("pastes at the selection captured before the content arrived", () => {
setModelData(editor.model, "<paragraph>a[]b</paragraph><paragraph>cd</paragraph>");
diff --git a/packages/ckeditor5/src/plugins/cuttonote.ts b/packages/ckeditor5/src/plugins/cuttonote.ts
index 3b5105cd22..e17192f490 100644
--- a/packages/ckeditor5/src/plugins/cuttonote.ts
+++ b/packages/ckeditor5/src/plugins/cuttonote.ts
@@ -98,7 +98,8 @@ export default class CutToNotePlugin extends Plugin {
/**
* Runs `html` (or `text` when `html` is empty) through the clipboard paste pipeline, as a
* paste at the current selection. Pasting a table into a multi-cell table selection merges
- * it the way a native paste does.
+ * it the way a native paste does. Both flavors also go on the event's `dataTransfer`, where
+ * listeners such as `CodeBlockEditing` read them.
*/
pasteContent(html: string, text: string) {
const content = html || (text ? plainTextToHtml(text) : "");
@@ -106,10 +107,18 @@ export default class CutToNotePlugin extends Plugin {
return;
}
+ const dataTransfer = new DataTransfer();
+ if (html) {
+ dataTransfer.setData("text/html", html);
+ }
+ if (text) {
+ dataTransfer.setData("text/plain", text);
+ }
+
const view = this.editor.editing.view;
view.focus();
view.document.fire("clipboardInput", {
- dataTransfer: new ViewDataTransfer(new DataTransfer()),
+ dataTransfer: new ViewDataTransfer(dataTransfer),
content,
method: "paste",
targetRanges: null