Skip to content
Edytor
Esc
↑↓navigate↵open⌘Jpreview
On this page

Clipboard

How Edytor copies, cuts and pastes, the clipboard formats it writes, how pasted HTML becomes blocks and marks, and where plugins can step in.

Edytor handles copy, cut, paste and drop from its document model instead of letting the browser copy rendered HTML. Copies between Edytor editors keep every block, mark and inline block; copies to other apps get clean HTML and plain text; pasted HTML is mapped onto your block kinds and marks.

Copy and cut

Copy and cut write three formats:

Format Content
application/x-edytor-fragment The copied content as Edytor JSON.
text/html HTML built from your kinds and marks, with the same JSON embedded in a data-edytor-fragment attribute.
text/plain The text, one line per block.

The embedded copy lets a paste into another Edytor editor keep full fidelity even when the clipboard drops the custom format, which some browsers and apps do.

What gets copied:

  • A text range inside one block copies that text with its marks and inline blocks.
  • A text range across blocks copies the blocks it touches, cut at the range’s ends. A closed toggle’s hidden body is copied exactly when deleting the range would delete it: with a toggle the range covers, or starts at the header of. Cut deletes the range as Backspace does, so a cut, or a copy followed by Backspace, never loses or duplicates it.
  • A block selection copies exactly the selected blocks, as whole blocks: a selected list or code block with everything in it (selection.selectedMembers), a selected parent’s unselected children left out (Block selection).
  • A mark whose record says copy: false is left out, in every format: a comment’s anchor (comment:<id>) is not copied, as in Notion, so pasted text is not commented. Its other marks are kept.

Copy works in readonly mode and never creates an undo step. Cut is one undo step and is ignored in readonly mode.

How content is exported

The HTML and plain text come from the definitions, so exporting a kind looks like rendering it:

  • A block kind’s html form: a tag name that wraps the content then the children (the rich text plugin uses blockquote for quotes, li for list items), or a function of the block and its serialized content and children. The default is <p> around the content. A block’s colours are a class on its element, as in Notion’s export: block-color-red, block-color-red_background.
  • A block kind’s plain form, a function; the default is the content, then the children, one per line.
  • A mark’s tag and attributes: bold exports <strong>, a link <a href>, a color <span style="color: …">. A mark without a tag exports its text only.
  • An inline block’s plain function; by default an inline block exports nothing to plain text. Its html function gives its HTML (an equation writes MathML); by default it is an empty <span data-edytor-inline-block>.

See Custom blocks for declaring these forms. The same forms export a whole document, as HTML or Markdown, in the browser or on a server: Import and export.

Paste

A paste is handled by the first rule that applies:

  1. An Edytor fragment, from the custom format or embedded in the HTML. Pasted with full fidelity.
  2. A plugin’s onPaste hook, if one calls prevent().
  3. Files (an image from the clipboard, say): ignored unless a plugin’s onPaste handled them. A media plugin given an upload handles them: each file becomes a block of the kind that takes it, uploaded (Pasted and dropped files).
  4. External text/html, imported as blocks and marks (below).
  5. Markdown text/plain, as its blocks (Pasting markdown).
  6. text/plain, one block per line.

Shift+paste (Mod+Shift+V) pastes the plain text only and skips rules 1 to 5, plugin hooks included. Plain text takes the marks at the caret.

Pasting a link over selected text links it, as in Notion: with rich text and a text range selected outside a code block, a paste whose plain text is one URL (http:, https: or mailto:) makes the selected text a link to it and keeps it selected, instead of replacing it. At a caret, a URL is inserted as a link, and undo gives the plain URL back first. This is the rich text plugin’s onPaste hook (rule 2). Text that is not one URL, a caret inside a link or inline code, and Shift+paste paste as usual.

Paste is one undo step and is ignored in readonly mode. Dropping content from outside the editor follows the same rules. Dragging text inside the editor moves it: see Dragging text.

Where pasted content goes

The same placement applies to Edytor fragments, HTML and multi-line text:

  • One line joins the text at the caret. Into an empty block, a line of another kind gives the block its kind too (a heading pasted into an empty paragraph makes a heading), except the first line of a toggle, open or closed, or of a callout or quote with nested lines, which keeps its kind and takes the text only. A pasted line’s nested lines come under the block it joins, except a closed toggle’s: they go after it, so nothing lands in its hidden body.
  • Several lines split the block at the caret: the first line joins the text before the caret, the last line takes the text after it, and the others go between. Pasting the lines X and Y into Hello|World gives HelloX and YWorld. The block’s children go with the text after the caret to the last line; a closed toggle’s hidden body stays with the first line. At the end of the first line of an open toggle, or of a callout or quote with nested lines, the nested lines stay where they are and what follows the first pasted line becomes its first nested lines, as Enter there opens a first nested line; when that first line is empty, it keeps its kind and takes the first pasted line’s text only, even an open toggle with no nested lines yet. In the middle of that line, the nested lines go with the text after the caret.
  • A list block from an Edytor fragment, a code block, a divider or an image never joins text: a list and a code block show no text line of their own, and a divider or an image is a block of its own (an image’s caption belongs to it). It is inserted as a block, and the text after the caret moves to a new line of the same kind after it, as Enter splits the line (at the end of an open toggle’s, a callout’s or a quote’s first line with nested lines, the pasted blocks lead the nested lines instead, as above). Pasting x and a divider into hello| world gives hellox, the divider, then world. At the start of a block such content goes before it. A list or a code block replaces an empty block; after a divider or an image, the empty line stays for the caret.
  • List items from HTML (<ul><li>one</li><li>two</li></ul>) are lines of their own kind, not a list block, and join like other lines: pasted at hello| world they give helloone and a bulleted item two world; at |hello world, one and a bulleted item twohello world.
  • Inside a code block everything pastes as plain code lines: a list’s items, a code block’s lines and paragraphs each become one line.
  • Blocks copied from a block selection are inserted as whole blocks after the caret’s block, replacing it when it is empty.
  • The caret ends after the pasted content: at the end of its last line (a list’s last item, a code block’s last line), or on the line after a pasted divider or image.
  • With blocks selected, the pasted content replaces them.
  • A pasted range replaces the selected text first.

Pasted blocks and inline blocks always get new ids, so pasting twice never creates duplicates. Their marks, data, children and order are kept.

Pasted and dropped files

Each media plugin takes its own uploader, upload (createImagePlugin({ upload }), and the same for the file, video and audio plugins); every kind whose plugin has one takes the files of a paste or a drop that are its own, as Notion does: an image (image/*) to the image block, a video (video/*) to the video block, an audio file (audio/*) to the audio block, and any other file to the file block, which takes only what no other kind takes, wherever it is listed. Each file is sent with its kind’s plugin’s upload. A kind whose plugin has no upload takes no files: no drop line for them, no Upload in its empty block, and its files go to the file block when that one uploads (else nowhere).

  • The files become one block each, in the clipboard’s order, each of its own kind, placed as pasted blocks are (after the caret’s line). All of them are one command and one undo step. A file no kind takes is left out.
  • Dropped files land where the drop indicator shows, as Notion does. While files are dragged from your desktop over the editor, the editor draws the line a block drag draws, under the same rules: the upper half of a block’s row is before it, the lower half after it (moved right past one indent, inside it), the right edge of a row beside it (a new column, when a layout kind is listed), and the margins reorder the row next to them. While they are dragged, the line shows only at places that take the blocks those files become (by their type); a file no listed uploader takes shows no line and is not inserted. Where the browser hides the files’ types, the line shows wherever any uploaded kind fits. The drop places the files there; with no place under the pointer, at the drop point. It works with or without the block handles, the page and the editor’s scroller scroll when the pointer nears their edges, as in a block drag, and the drag leaving the editor clears the line. A readonly view shows no line and takes no drop. The drop line and the file drop come with the media plugins: without one given an upload, the editor ignores a drop that carries files (no line, no block, and the browser does not open the file in place of the page). A drop of text or HTML from another app still lands at the drop point in the text.
  • Each block shows its file at once in this view: an image from a local object URL (never stored, revoked once the upload ends), another file its name and size, with a bar, with “Uploading…”, that fills as your upload reports progress. upload(file, report) may call report.progress(fraction) (0 to 1) as the file goes; without it the bar is indeterminate. A peer sees the empty block until the URL arrives.
  • The URL upload answers fills the block (a file’s with its name and size) outside the history, so the paste stays the one step: undo removes the block, URL included, and redo brings it back whole, even when the upload ended while it was undone.
  • A failed upload, or an answer that is no accepted source, leaves the block empty, its panel open with “The upload failed: try again or paste a link.”
  • A paste whose HTML shows text (an office app also puts a picture of the copied text on the clipboard) is imported as HTML instead. A readonly view takes nothing.
  • A plugin’s onPaste hook sees a drop of files with at, the indicator’s placement ({ block, position }, position one of before, after, inside, left, right), and may claim it first.
import { createImagePlugin } from 'edytor';

export const image = createImagePlugin({
	upload: (file, report) =>
		new Promise<string>((resolve, reject) => {
			const request = new XMLHttpRequest();
			request.open('POST', '/api/uploads');
			request.upload.onprogress = (event) => report.progress(event.loaded / event.total);
			request.onload = () => resolve(JSON.parse(request.responseText).url);
			request.onerror = reject;
			request.send(file);
		})
});

Pasting markdown

Plain text with no HTML, from a text editor, a terminal or an AI chat, is read as markdown when one of its lines holds block markdown, as in Notion: a heading (# to ###### , deeper ones as level 3), a bulleted (- , * , + ), numbered (1. ) or to-do item (- [ ] , - [x] ), a quote (> ), a fence (```) or a divider (---). The text then becomes the blocks it reads as (textToBlocks): list items nested by their indentation (two spaces a level), the consecutive lines of a paragraph joined by a space, and inline **bold**, *italic* or _italic_, `code` and [text](url) links as marks. It is placed like any pasted lines (above), as one undo step.

  • Text with no block markdown pastes as before, each line a block and every character kept: a *b* c stays as typed.
  • Inside a code block, the lines are code.
  • A kind the view does not register (a code block without the code plugin) becomes paragraphs of its text; a divider without a divider kind is left out.
  • Shift+paste keeps the characters.

HTML import

External HTML, from a web page, Google Docs or a word processor, is parsed by the browser’s DOMParser. Parsing is inert: no script runs and nothing loads. The import walks the result and maps elements onto the registered definitions.

Blocks. An element becomes a block kind when:

  • a kind’s parse(element) hook returns data for it (checked first), or
  • its tag is the one a kind exports or renders for one of its presets. A void kind that has a parse hook (the image and the media kinds) is found by its hook only: its tag alone carries no source.

A void block takes only the text of its element’s figcaption as its caption: an iframe’s fallback text, a video’s source list or a bookmark’s link text never become content.

With the rich text plugin, that maps h1–h3 to headings, h4–h6 to h3 headings, blockquote to quotes, li to bulleted items, li inside ol to numbered items, hr to dividers, details to toggles and pre to code blocks (one line per text line, with the code plugin). The image plugin maps a figure holding an img with a safe src, and a bare img with one, to an image block (its alt and width attribute come along). When you list them, the embed plugin maps an iframe an allowlisted provider plays to an embed block, and the video and audio plugins map a video or audio with a safe source (its src, or a source child’s) to their blocks; each also takes its element inside a figure, with the figcaption as the caption. Without them those elements are dropped.

Images inside text. An element of a void kind (an img) met inside a line, even wrapped in inline markup such as Google Docs’ <p><span><img></span></p>, ends the line there: the image becomes a block of its own, and the text after it a new line of the same kind. <p>before <img src="…"> after</p> gives before, the image, then after. A line left with no text around the image is not kept.

Emoji and icons drawn as images stay in the text as their alt: an img whose alt is emoji only (<img alt="😂" src="…">, as X and Gmail write emoji), whose class names an emoji or that has data-emoji (Slack, WordPress), or whose width and height are 32 px or less (an icon, an email’s tracking pixel, which has no alt and so adds nothing). <p>So funny <img alt="😂" src="…"> right</p> pastes as one line, So funny 😂 right.

Inline atoms. An element inside a line becomes an inline atom when an atom kind’s parse(element) returns data for it; its contents are then not read as text. With the equation plugin, KaTeX’s markup or a <math> with a TeX annotation becomes an inline equation (a display="block" one, a block equation).

Marks. Text takes a mark when:

  • the mark’s parse(element) returns a value (checked first), or
  • the element’s tag equals the mark’s tag, for marks without a value.

The rich text plugin maps strong/b, em/i, u, s/strike/del, code, sup and sub, links (a with a safe href), text colors, backgrounds and mark highlights, and the bold, italic, underline and strikethrough styles Google Docs writes on spans.

Everything else:

  • Unknown elements become paragraphs (block-level) or plain text (inline).
  • Whitespace collapses the way the browser renders it; <br> is a line break inside the block.
  • script, style, template, media no plugin claims (an img, iframe, video or audio), form controls and other non-text elements are skipped.
  • HTML that yields nothing (only a comment or empty elements) falls through to text/plain.

Your own kinds and marks take part in the import the same way. A value-less mark with a tag is matched by that tag; a mark with a value needs a parse hook:

import type { Plugin } from 'edytor';

export const inlineExtrasPlugin: Plugin = () => ({
	marks: {
		// Rendered as <kbd>, exported as <kbd>, and pasted <kbd> elements take it.
		kbd: { tag: 'kbd' },
		// Rendered and exported as <abbr title="…">; pasted <abbr> keeps its title.
		abbr: {
			tag: 'abbr',
			attributes: (title) => ({ title: typeof title === 'string' ? title : undefined }),
			parse: (el) => (el.localName === 'abbr' ? (el.getAttribute('title') ?? '') : undefined)
		}
	}
});

A block kind’s parse(element) works the same way and returns the new block’s data. Definitions are first-wins, so add hooks to kinds you define rather than redefining a bundled one. See Custom blocks.

Dragging text

Selected text dragged to another place in the editor moves there, as in Notion: press inside the selection, hold, drag, release where the caret shows. The move is one command, moveText, and one undo step that gives back both the text and its place:

  1. its content goes to the drop point, placed as a paste of the same content would place it (insertFlow): marks, inline atoms and lines come along, a range across blocks arrives as lines;
  2. the range is deleted as a replacement deletes it (replaceRange): a range across blocks joins them.

Both halves are prepared before anything is written, so a drop either half refuses (a drop point that takes no content, a range the document keeps) writes nothing: the text never leaves without landing.

The moved text is selected after the drop. Hold Alt (Option) at the drop to copy instead: the range stays and a copy lands at the drop point. A drop inside the dragged range changes nothing. A readonly view takes no drop, a kind’s own control (a field in a block) keeps its own drags and drops, and dragging during an IME composition does nothing. The drag carries the range as a copy carries it (the Edytor fragment, HTML and plain text), so dropping it in another Edytor or another app pastes it there, and the text stays where it was.

Hooks see moveText with its payload (from: the range’s start and end, to: the drop point, both in block offsets; copy) its effect, and the planned steps of both halves (the placement’s, then the deletion’s; a copy’s: the placement’s), all before any write; prevent() on the command or on any of its steps keeps everything. Block-handle drags are not text drags: they move whole blocks (see Block handles).

Plugin hooks

onCopy, onCut and onPaste run before Edytor handles the event. Call prevent() to take over; the browser’s default is prevented too. For instance (a media plugin’s upload does this for you, with a placeholder while the file uploads and one undo step):

import type { Plugin } from 'edytor';

export const imagePastePlugin: Plugin = (edytor) => ({
	onPaste: ({ e, prevent }) => {
		const file = e.clipboardData?.files[0];
		if (!file?.type.startsWith('image/')) return;
		prevent(async () => {
			const src = await upload(file); // your upload
			// Add an image block (the bundled image plugin) after the caret's block.
			const block = edytor.selection.caret?.block;
			const at = block && edytor.document.positionOf(block.id);
			if (at) edytor.insertBlocks({ ...at, index: at.index + 1 }, [{ type: 'image', data: { src } }]);
		});
	}
});

onPaste runs after the Edytor-fragment check, so it sees pastes from other apps, not copies between Edytor editors. It does not run for Shift+paste. The first plugin (in plugin order) that prevents wins. See Plugins.

With the embed or bookmark plugin listed, pasting one http(s) URL (surrounding whitespace aside) on a line that holds nothing writes it as a link, one undo step, and opens a menu under the line, as Notion does:

  • Link (highlighted) keeps the link. Enter right after the paste picks it, so it never converts by accident and splits nothing.
  • Embed, when an allowlisted provider plays the URL, turns the line into an embed of it.
  • Bookmark turns the line into a web bookmark of it, then asks your unfurl for its title.

↑/↓ move the highlight and Enter picks it. A conversion is one more undo step: undo gives the linked URL back. Escape, a press outside the menu, typing, any other edit or a caret that leaves the URL’s end close the menu and keep the link. The rows follow the plugin order. A line with text, a Shift+paste, a mailto: link, text that is not one URL, a code block or a void’s caption paste as before.

Was this page helpful?