From 21bcdd23adeb665f9907a69517ab453e35c3207b Mon Sep 17 00:00:00 2001 From: g4lb Date: Mon, 30 Nov 2026 15:05:56 +0200 Subject: [PATCH] fix(clipboard): copy text without escapes that it does not need Copied text/plain was the saved Markdown, so a "$" that the math syntax escapes pasted as "\$": rm -rf \$(brew --cache) in a terminal. text/plain now leaves out each extension escape that the content reads back the same without. The HTML still carries the saved Markdown, so a paste into the editor does not change. --- docs/architecture.md | 2 +- packages/editor/src/editor.ts | 6 +-- packages/editor/src/markdown/serialize.ts | 49 +++++++++++++++++++---- packages/editor/test/dialect.test.ts | 13 +++++- 4 files changed, 58 insertions(+), 12 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 2ac49b0..20467fa 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -117,7 +117,7 @@ How it works: - Delete, duplicate and paste are pure commands on a block range: `deleteBlocks`, `duplicateBlocks` and `replaceBlocks`. Each re-nests list items that would end up deeper than the item above allows, for example the nested items of a deleted parent. - Copying whole blocks uses `serializeBlocks`, so a selected empty line is copied as ` ` rather than dropped as trailing whitespace. -**Copying text.** A text selection is copied as Markdown (`text/plain`) and as HTML that carries the same Markdown (`data-mbe-markdown`), so a paste into the editor is lossless and a paste elsewhere gets Markdown. A selection inside one block is copied as its inline content, as a paragraph: a word of a heading pastes as a word, not as a heading, as in Notion and ProseMirror, and a selection inside one table cell does the same. Inside one code or raw block, `text/plain` is the text as written, so it pastes into a terminal or another code block as code, while the HTML carries the escaped Markdown for a paste into a paragraph. A selection across blocks copies the blocks, cut at its ends. Whole blocks, with their type, are copied through the block selection (Escape, then Mod+C). +**Copying text.** A text selection is copied as Markdown (`text/plain`) and as HTML that carries the same Markdown (`data-mbe-markdown`), so a paste into the editor is lossless and a paste elsewhere gets Markdown. The `text/plain` Markdown leaves out each extension escape that it reads back the same without (`copyMarkdown`), so `rm -rf $(brew --cache)` pastes into a terminal as typed. The HTML carries the Markdown as saved, with every escape. A selection inside one block is copied as its inline content, as a paragraph: a word of a heading pastes as a word, not as a heading, as in Notion and ProseMirror, and a selection inside one table cell does the same. Inside one code or raw block, `text/plain` is the text as written, so it pastes into a terminal or another code block as code, while the HTML carries the escaped Markdown for a paste into a paragraph. A selection across blocks copies the blocks, cut at its ends. Whole blocks, with their type, are copied through the block selection (Escape, then Mod+C). ## Source mode diff --git a/packages/editor/src/editor.ts b/packages/editor/src/editor.ts index 6973a06..c14d3eb 100644 --- a/packages/editor/src/editor.ts +++ b/packages/editor/src/editor.ts @@ -18,7 +18,7 @@ import { type ChangeKind, History } from './history'; import { DEFAULT_LABELS, type Labels } from './labels'; import { type Icon, type IconName, type Icons, builtinIcon, iconNode } from './icons'; import { parseMarkdown } from './markdown/parse'; -import { serializeBlocks, serializeMarkdown } from './markdown/serialize'; +import { copyMarkdown, serializeBlocks, serializeMarkdown } from './markdown/serialize'; import { type MarkdownSource, loadMarkdown } from './markdown/source'; import { type MarkdownOptions, type ResolvedMarkdown, resolveMarkdown } from './markdown/options'; import type { Extension, SyntaxView } from './extension'; @@ -2862,7 +2862,7 @@ export class Editor { e.preventDefault(); const doc: Doc = { blocks: cmd.closeSections(this.state.doc.blocks.slice(range.from, range.to + 1).map(cmd.cloneBlock)) }; // serializeBlocks keeps a selected empty line, which serializeMarkdown drops at the end. - writeClipboard(e.clipboardData, doc, serializeBlocks(doc.blocks, this.markdown)); + writeClipboard(e.clipboardData, doc, serializeBlocks(doc.blocks, this.markdown), copyMarkdown(doc.blocks, this.markdown)); if (cut && !this.readOnly) this.deleteSelectedBlocks(); return; } @@ -2877,7 +2877,7 @@ export class Editor { // with its escapes, travels with the HTML for a paste into a paragraph. const only = selected.length === 1 && selected[0]!.type === 'paragraph' ? selected[0] : null; const code = only && isPlainTextBlock(getBlock(this.state.doc, this.state.selection.focus.blockId)); - writeClipboard(e.clipboardData, doc, markdown, code ? inlineText(only.content) : markdown); + writeClipboard(e.clipboardData, doc, markdown, code ? inlineText(only.content) : copyMarkdown(doc.blocks, this.markdown, true)); if (cut && !this.readOnly) this.run(cmd.deleteSelection); } diff --git a/packages/editor/src/markdown/serialize.ts b/packages/editor/src/markdown/serialize.ts index aa3ee91..5e67510 100644 --- a/packages/editor/src/markdown/serialize.ts +++ b/packages/editor/src/markdown/serialize.ts @@ -53,6 +53,18 @@ import { emailLiterals, isLiteralBoundary, literalHref, urlLiteralAt } from './a import { type InlineSyntax, type MarkdownOptions, type ResolvedMarkdown, resolveMarkdown } from './options'; import { type MarkdownSource, saveWithSource } from './source'; +/** + * Markdown for the `text/plain` flavour of a copy: like `serializeBlocks`, + * but without the extension escapes that the content reads back the same + * without. The copied HTML carries the saved form. + */ +export function copyMarkdown(blocks: readonly Block[], options?: MarkdownOptions, dropEmptyEnd = false): string { + // With `dropEmptyEnd`, like `serializeMarkdown` without its final line ending. + let end = blocks.length; + while (dropEmptyEnd && end > 0 && isEmptyParagraph(blocks[end - 1]!)) end--; + return serializeBlocks(blocks.slice(0, end), options, true); +} + export function serializeMarkdown(doc: Doc, options: SerializeOptions = {}): string { if (options.source) return saveWithSource(doc.blocks, options.source, options); // Empty lines at the end render as nothing, so they are not written. @@ -71,8 +83,8 @@ export interface SerializeOptions extends MarkdownOptions { } /** Blocks as Markdown, without a final line ending. */ -export function serializeBlocks(blocks: readonly Block[], options?: MarkdownOptions): string { - const ctx = contexts(options); +export function serializeBlocks(blocks: readonly Block[], options?: MarkdownOptions, copy = false): string { + const ctx = contexts(options, copy); let out = ''; let prev: Block | null = null; const lists = new ListState(ctx.paragraph); @@ -88,7 +100,7 @@ export function serializeBlocks(blocks: readonly Block[], options?: MarkdownOpti let end = i + 1; while (end < blocks.length && sameQuote(block, blocks[end])) end++; const inner = blocks.slice(i, end).map(unquote); - let body = serializeBlocks(inner, options); + let body = serializeBlocks(inner, options, copy); // A list that cannot interrupt a paragraph needs a blank line after the marker. if (kind !== 'quote') body = `[!${kind.toUpperCase()}]\n${interrupts(inner[0]!) ? '' : '\n'}${body}`; if (out) out += separator; @@ -267,13 +279,20 @@ interface InlineContext { */ readonly newline: 'break' | 'soft' | 'entity'; readonly options: ResolvedMarkdown; + /** The `text/plain` of a copy: see `copyMarkdown`. */ + readonly copy?: boolean; + /** + * Escape the characters of syntax extensions (`options.escape`) only at + * the start of a line, where they can open a block. + */ + readonly fewerEscapes?: boolean; } -function contexts(options: MarkdownOptions | undefined) { +function contexts(options: MarkdownOptions | undefined, copy = false) { const o = resolveMarkdown(options); - const inline = { lineStart: false, newline: 'entity', options: o } satisfies InlineContext; + const inline = { lineStart: false, newline: 'entity', options: o, copy } satisfies InlineContext; return { - paragraph: { lineStart: true, newline: o.breaks ? 'soft' : 'break', options: o } satisfies InlineContext, + paragraph: { lineStart: true, newline: o.breaks ? 'soft' : 'break', options: o, copy } satisfies InlineContext, // Headings and table cells are one line: a line break is written as a character reference. heading: inline, cell: inline, @@ -290,6 +309,18 @@ const EMPHASIS: readonly EmphasisMark[] = ['bold', 'italic', 'strike']; const isEmphasis = (m: Mark): m is EmphasisMark => (EMPHASIS as readonly Mark[]).includes(m); function inlineToMarkdown(inline: Inline, ctx: InlineContext): string { + const out = renderInline(inline, ctx); + // Saved Markdown escapes every character of an extension's syntax. Copied + // text leaves out the escapes it reads back the same without (a lone "$" + // is not math), so a command pastes into a terminal as typed. + const escape = ctx.options.escape; + if (!ctx.copy || !escape || ![...escape].some((ch) => out.includes('\\' + ch))) return out; + const fewer = renderInline(inline, { ...ctx, fewerEscapes: true }); + if (fewer === out || !sameInline(parseInline(fewer, ctx.options), representableInline(inline))) return out; + return fewer; +} + +function renderInline(inline: Inline, ctx: InlineContext): string { const spans = representableInline(inline); // Links that are GFM autolink literals are written bare, as typed, when the // output reads back the same; otherwise in angle brackets or as [text](url). @@ -753,6 +784,7 @@ function escapeText( endsLine, blockSyntax: ctx.lineStart && startsLine, escape: ctx.options.escape, + fewerEscapes: ctx.fewerEscapes, inline: ctx.options.inline, autolinks: ctx.options.autolinks && !tok.inLink, }); @@ -772,6 +804,8 @@ function escapeLine( blockSyntax: boolean; /** Characters syntax extensions need escaped. */ escape?: string; + /** Escape `escape` characters only where a line starts block syntax. */ + fewerEscapes?: boolean; /** Inline syntax extensions, some of which may read a backslash escape as a token. */ inline?: readonly InlineSyntax[]; /** GFM autolink literals are on: plain text that looks like a URL must not read back as a link. */ @@ -834,7 +868,8 @@ function escapeLine( out += next === '[' ? bs('!') : ch; break; default: - out += o.escape && o.escape.includes(ch) ? bs(ch) : ch; + // With fewerEscapes, only where the character could open a block. + out += o.escape?.includes(ch) && (!o.fewerEscapes || (i === 0 && o.blockSyntax)) ? bs(ch) : ch; } } return out; diff --git a/packages/editor/test/dialect.test.ts b/packages/editor/test/dialect.test.ts index c1d1417..8b3453d 100644 --- a/packages/editor/test/dialect.test.ts +++ b/packages/editor/test/dialect.test.ts @@ -8,7 +8,7 @@ import { footnotes } from '../src/extensions/footnotes'; import { math, mathSource } from '../src/extensions/math'; import type { MarkdownOptions } from '../src/markdown/options'; import { parseMarkdown } from '../src/markdown/parse'; -import { serializeMarkdown } from '../src/markdown/serialize'; +import { copyMarkdown, serializeMarkdown } from '../src/markdown/serialize'; import { loadMarkdown } from '../src/markdown/source'; const NOTES: MarkdownOptions = { breaks: true, setext: false, syntax: [math().markdown!, footnotes().markdown!] }; @@ -36,6 +36,17 @@ describe('math', () => { expect(rewrite('price \\$5')).toBe('price \\$5\n'); }); + it('copies dollar signs that are not math without their escapes', () => { + const copy = (md: string) => copyMarkdown(parseMarkdown(md, NOTES).blocks, NOTES); + expect(copy('rm -rf \\$(brew --cache)')).toBe('rm -rf $(brew --cache)'); + expect(copy('costs \\$5 and \\$10')).toBe('costs $5 and $10'); + // An escape that keeps text from reading back as math stays. + expect(copy('a \\$x\\$')).toBe('a \\$x\\$'); + for (const md of ['rm -rf \\$(brew --cache)', '\\$x\\$ and $y$', 'a **\\$b** c\\$', '\\$$\n\\$$']) { + expect(shape(parseMarkdown(copy(md), NOTES)), md).toEqual(shape(parseMarkdown(md, NOTES))); + } + }); + it('reads $$ fences as raw math blocks, also in the middle of a paragraph', () => { const md = 'before\n$$\n\\int_0^1 x\\,dx\n= \\frac12\n$$\nafter'; expect(shape(parseMarkdown(md, NOTES))).toEqual([