Skip to content

Code

react-smart-copy/code is for the copy button on every code block and for fields people paste code into. It also catches code that reads differently from how it runs. No dependencies, about 7.4 kB (inspectCode alone is about 2.5 kB).

Copy a terminal session and get only the commands. Paste code from a chat or a document and get it back clean, with anything suspicious listed.
$ npm install react-smart-copy
added 1 package in 2s
$ npx vitest run --coverage
 Tests  1199 passed
$ git tag v1.12.0 && git push --tags

What the Copy button puts on the clipboard:

Press Copy to see it.

This snippet hides a Trojan Source comment, a Cyrillic letter and curly quotes.

Paste with Ctrl + V or ⌘ + V. Lines are indented to the cursor, and Ctrl + Z undoes the paste.

Nothing pasted yet.

    The code, not the page around it

    codePayload copies the commands of a session without prompts or output, leaves out line numbers and buttons, and adds monospaced HTML with the block's colours for Docs and Slack.

    pasteAsCode fixes curly quotes and invisible characters, indents to the cursor and keeps undo. It reports bidi overrides (Trojan Source), invisible identifiers and lookalike letters, so a paste never runs differently from how it reads.

    import { codePayload, pasteAsCode } from 'react-smart-copy/code';
    
    copy(() => codePayload(preRef.current));
    
    <textarea onPaste={(event) => pasteAsCode(event, {
      onPaste: (result) => !result.danger || confirm('Paste anyway?'),
    })} />
    import { useCopy } from "react-smart-copy";
    import { codePayload } from "react-smart-copy/code";
    const { copy, status } = useCopy();
    <pre ref={preRef}>…</pre>
    <button onClick={() => copy(() => codePayload(preRef.current!, { language: "tsx" }))}>Copy</button>

    What gets copied is the code the reader means to run:

    • A terminal or REPL session copies as its commands. $ npm test followed by its output copies as npm test. Prompts from bash/zsh ($, user@host:~$, (venv) $), PowerShell, cmd, Python, IPython and Node are recognised. Continued commands stay whole: a trailing \, a heredoc or an open quote. prompt: "auto" (the default) only acts when the first line starts with a prompt
    • A highlighted block copies without its chrome. Line-number gutters (Prism, highlight.js, Rouge, react-syntax-highlighter and others), user-select: none and aria-hidden parts, hidden parts, buttons and anything with data-copy-ignore are left out. ignore takes a CSS selector for more
    • It pastes well everywhere. Plain text for editors and terminals, plus monospaced HTML with the block’s syntax colours for Google Docs, Word, Slack, Teams and mail. Both flavours always hold the same code
    • Diffs, line numbers, indentation. diff: "after" (or "before") copies one side of a unified diff. lineNumbers: true removes typed line numbers when they count up on every line. Shared indentation, trailing whitespace and blank edges are removed, and line endings are normalised (lineEnding: "crlf" for Windows)

    For a code field, pasteAsCode is a ready paste handler:

    import { pasteAsCode } from "react-smart-copy/code";
    <textarea onPaste={pasteAsCode} />
    <textarea onPaste={(event) => pasteAsCode(event, { onPaste: (r) => !r.danger || confirm("Paste anyway?") })} />

    It fixes what chat apps and word processors do to code (curly quotes, — for --, no-break spaces, zero-width characters) and dedents the paste. Each line after the first is indented to the cursor line, as code editors do. The paste is one step on the browser’s undo stack. onPaste sees every finding first and can cancel. For CodeMirror, Monaco or usePaste, pasteToCode(result) returns the same { code, findings, fixed, remaining, danger }.

    Security: code that runs differently from how it reads. inspectCode reports, with line, column and a label such as U+202E RIGHT-TO-LEFT OVERRIDE:

    Kind Severity What it catches
    bidi-control danger Trojan Source (CVE-2021-42574): overrides and isolates that reorder how code is shown. Implicit marks are a warning
    invisible danger / warning Hangul fillers that make invisible identifiers, and tag characters that hide ASCII (including hidden instructions in prompts) are danger. Zero-width spaces, joiners outside words and emoji, and runs of variation selectors that smuggle data are warnings
    mixed-script danger / warning A Cyrillic or Greek letter inside a Latin word (аdmin with a Cyrillic а). A Latin lookalike is danger; another letter is a warning
    control warning Control characters other than tab, line feed, carriage return and form feed, and Unicode line separators
    unusual-space warning No-break, em, ideographic and similar spaces
    confusable-punctuation warning Curly quotes, dashes, …, the Greek question mark that looks like ;, full-width punctuation outside CJK text

    Joiners inside Arabic, Persian or Indic words and emoji, a single emoji variation selector, and full-width punctuation in CJK comments are left alone. cleanCode applies the safe replacement of every finding. It runs until nothing fixable is left, because removing a zero-width space can expose a mixed word. It never guesses a letter that has no Latin lookalike; those stay in remaining. Copying doesn’t clean by default (clean: true turns it on). Pasting does (clean: false turns it off).

    import { cleanCode, inspectCode, normalizeCode } from "react-smart-copy/code";
    inspectCode(source).danger; // true for Trojan Source, lookalikes, invisible identifiers
    cleanCode("const s = “hi”;").code; // 'const s = "hi";'
    normalizeCode("$ npm i\nadded 1 package"); // "npm i" (also works on the server)

    Pasted code is never cut: past maxLength (2,000,000 characters) pasteToCode throws a too-large error, and pasteAsCode leaves the paste to the browser. HTML is parsed inertly and only its text is used.

    Option Default Notes
    prompt "auto" copy, false paste a style ("shell", "powershell", "cmd", "python", "ipython", "node"), { command, continuation } regexes, or false
    diff false "after" or "before"
    lineNumbers false remove typed line numbers that count up
    dedent / trimTrailingWhitespace / trimBlankLines true
    lineEnding / finalNewline "lf" / false
    clean false copy, true paste true, false or a list of kinds
    html / language (copy) true / none add the HTML flavour; class="language-…" on <code>
    indentToCursor / onPaste (pasteAsCode) true / none