Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 3 additions & 3 deletions packages/editor/src/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;
}
Expand All @@ -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);
}

Expand Down
49 changes: 42 additions & 7 deletions packages/editor/src/markdown/serialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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);
Expand All @@ -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;
Expand Down Expand Up @@ -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,
Expand All @@ -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).
Expand Down Expand Up @@ -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,
});
Expand All @@ -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. */
Expand Down Expand Up @@ -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;
Expand Down
13 changes: 12 additions & 1 deletion packages/editor/test/dialect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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!] };
Expand Down Expand Up @@ -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([
Expand Down
Loading