Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.
TypeScript claude-code-mod
Copy text from answer pictures
razorback16db43491e898c
diff --git a/README.md b/README.mdindex 401fff0..a1f7e6b 100644--- a/README.md+++ b/README.md@@ -75,6 +75,14 @@ To try it from a clone without installing: `claude --plugin-dir /path/to/claude-| `/md-preview size <80–200>` | Text size in percent. 100 is the same visual size as your terminal text. || `/md-preview theme` | Lists the themes, shows which one is in use, and shows the folder for your own themes || `/md-preview theme <name>` | Changes to that theme (kept for later sessions) |+| `/md-preview grab` | Copies the text under your last mouse selection of pictures |+| `/md-preview dump` | Shows the last clipboard text with picture cells and how the mod read it (for a bug report) |++### Copy text from a picture++Select the text in a picture (an answer or a plan) with the mouse, as you do with normal text. The selection puts picture cells on the clipboard. On macOS, the mod reads the clipboard every 0.3 s. When the clipboard has picture cells, the mod replaces them with the text under your selection, and a toast shows the number of characters. Wait approximately 0.3 s after you select, then paste. The mod does not change a clipboard that has no picture cells.++If the clipboard did not change, use `/md-preview grab`. It reads Claude Code's last mouse selection (fullscreen mode only) and copies its text. If the copied text is not correct, `/md-preview dump` shows the cells that the mod found and the page that it used. It also writes all of this to `copy-debug.json` in the cache folder.### Plan approval@@ -141,6 +149,7 @@ The `vscode` and `vscode-modern` values come from VS Code (MIT licence, Copyrigh5. If a compile fails (a bad Typst block or an unknown LaTeX command), the mod compiles once more in safe mode: Typst blocks and math show as code. A dim line under the picture names the error. If that also fails, the normal text shows.6. Pictures are kept in `${TMPDIR}/md-preview-<uid>/`. Folders older than 2 days are deleted at start.7. The plan: a `ui.render` hook on the ExitPlanMode `ToolUse` row draws the plan through the same steps. Claude Code shows that row above the approval question. The approved result row then shows only its header, so the plan does not show two times. A `tool.call` hook on ExitPlanMode asks the mod's question (`$.ui.ask`) before Claude Code asks for permission. Then a `classic.PermissionRequest` hook gives the answer to Claude Code at once, so the Claude Code dialog does not show. For an approval, the hook sends the plan (`updatedInput`) and the new permission mode (`setMode`). For the person's text, the `tool.call` hook refuses the call with that text.+8. Copy: after the PNGs, the mod runs `typst query` with `probe=1` on the same template. The probe gives the position of each word and each code line, and the mod keeps these positions in `positions.json` beside the pages. The PNGs do not change. On macOS, a timer reads the clipboard with `pbpaste`. A picture cell holds its row and its column (kitty placeholder U+10EEEE plus two combining marks). The mod finds the drawn page that has these rows, takes the words in the selected cells, and writes the text with `$.ui.copy`.### How `auto` is resolved@@ -161,7 +170,12 @@ md-preview checks every 3 s. After a change, each mode's pictures compile once.## Limitations-- **Copying text from a picture does not work.** A picture fills its cells with kitty placeholder characters (U+10EEEE plus combining marks). Claude Code's mouse selection copies those cells directly to the clipboard, and no mod hook runs before that copy. So a paste gives strange characters, not the text. Use Claude Code's `/copy` to copy the last answer as Markdown (`/copy 2` for the one before it; it shows a picker for the full answer or one code block, unless "Skip the /copy picker" is on in `/config`), or turn the mod off (`/md-preview off`) to select text. To stop the clipboard write on select, set `copyOnSelect` to `false` in `/config`.+- **Copying text from a picture** (see [Copy text from a picture](#copy-text-from-a-picture)) has these limits:+ - The automatic copy works only on macOS, and not over ssh (`pbpaste` reads the clipboard of the computer that runs Claude Code). On other systems, the clipboard keeps the picture cells. Use `/md-preview grab`, Claude Code's `/copy` (the last answer as Markdown, `/copy 2` for the one before it), or turn the mod off (`/md-preview off`) to select text.+ - The mod copies whole words. It copies a word when the selection covers the middle of the word. In a code block, it copies each character whose middle is in the selection.+ - The mod does not copy math or the text in an image.+ - The cells do not identify the answer. The mod uses the answer of the selected row if it knows it, else the newest answer whose pages fit the selection. A selection in one page of a long answer fits each page that is tall enough, and the mod uses the first one. Thus the text can come from a different page or an older answer of the same width. `/md-preview dump` shows the page that the mod used.+ - To stop the clipboard write on select, set `copyOnSelect` to `false` in `/config`.- **Search does not find text in a picture.**- **While Claude writes**, the block is hidden, and Claude Code's spinner shows the progress. When the block is final, its picture shows after the compile (0.15–0.6 s). A long answer shows only when it is done. If the picture is not ready 2 s after the block is final, the normal text shows until the picture is ready. If the compile fails, the normal text stays. An earlier answer that is not in the cache (for example, after a resume) is blank for up to 1 s, then shows as text until its picture is ready.- **Short summaries** between tool calls stay as text.@@ -186,7 +200,7 @@ claude plugin validate .`.claude-plugin/types/` is not in git. `tsconfig.json` extends the `tsconfig.json` in it, so run Claude Code with the folder once before `tsc`.-The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile) `draw.tsx` (the pages of an answer), `answer.ts` (one text through the compile and cache steps) and `plan.tsx` (the plan approval question and the plan rows). The values that change are in one object, `S`, in `state.ts`. The tests import from `hooks/register.tsx`, which exports the names that they use.+The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile) `draw.tsx` (the pages of an answer), `answer.ts` (one text through the compile and cache steps) `plan.tsx` (the plan approval question and the plan rows) and `copy.ts` (the text under a mouse selection of pictures). The values that change are in one object, `S`, in `state.ts`. The tests import from `hooks/register.tsx`, which exports the names that they use.## Licencediff --git a/hooks/lib/command.ts b/hooks/lib/command.tsindex 9ea11a9..5672dd6 100644--- a/hooks/lib/command.ts+++ b/hooks/lib/command.ts@@ -7,7 +7,7 @@ import { isThemeName, type ThemeInfo } from './themes'// `/md-preview` arguments: on, off, size <80-200>, or nothing (show state).export type Command =- | { kind: 'on' | 'off' | 'show' | 'probe' }+ | { kind: 'on' | 'off' | 'show' | 'probe' | 'grab' | 'dump' }| { kind: 'size'; percent: number }| { kind: 'theme'; name?: string }| { kind: 'setup'; remove: boolean }@@ -21,7 +21,7 @@ export function parseCommand(args: string): Command {if (typed.length === 2 && isThemeName(typed[1]!)) return { kind: 'theme', name: typed[1]! }return { kind: 'bad' }}- if (words.length === 1 && (words[0] === 'on' || words[0] === 'off' || words[0] === 'probe')) return { kind: words[0] }+ if (words.length === 1 && (words[0] === 'on' || words[0] === 'off' || words[0] === 'probe' || words[0] === 'grab' || words[0] === 'dump')) return { kind: words[0] }if (words[0] === 'setup' && words.length === 1) return { kind: 'setup', remove: false }if (words[0] === 'setup' && words.length === 2 && words[1] === 'remove') return { kind: 'setup', remove: true }if (words[0] === 'size' && words.length === 2 && /^\d+%?$/.test(words[1]!)) {@@ -38,6 +38,8 @@ const SUBCOMMANDS = [{ name: 'size', description: `text size, ${MIN_SIZE}-${MAX_SIZE}%` },{ name: 'theme', description: 'list the themes, or switch to one' },{ name: 'setup', description: 'iTerm2: add the shell line that turns pictures on' },+ { name: 'grab', description: 'copy the text of the pictures you last selected' },+ { name: 'dump', description: 'show what the clipboard held and how it was read' },] as constconst SIZES = [80, 90, 100, 110, 120, 125, 150, 175, 200]@@ -80,7 +82,7 @@ export function commandSuggestions(export async function registerCommand($: EngineInterface) {await $.command.register({name: 'md-preview',- description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), theme [name] (list or switch themes)",- argumentHint: '[on|off|size <percent>|theme [name]]',+ description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), theme [name] (list or switch themes), grab (copy the selected pictures' text), dump (copy diagnostics)",+ argumentHint: '[on|off|size <percent>|theme [name]|grab|dump]',}).catch(() => undefined)}diff --git a/hooks/lib/copy.ts b/hooks/lib/copy.tsnew file mode 100644index 0000000..d12d05c--- /dev/null+++ b/hooks/lib/copy.ts@@ -0,0 +1,330 @@+// Copy (pure): the text under a mouse selection of answer pictures.+//+// Claude Code draws an Image as kitty Unicode placeholders: each cell is+// U+10EEEE, then the diacritic of its row, then the diacritic of its column+// (indices into DIACRITICS; the image id is only in the cell's colour, so it+// never reaches the clipboard). A mouse copy puts those cells on the+// clipboard, one line per screen row. decodeSelection reads them back as+// runs of (row, columns) per picture; positionsOf turns the template's probe+// marks (render/md.typ, `<mdpos>`) into word boxes in PNG pixels; pickPages+// says which drawn page each run is; textOfRun reads the words under a run.+// The clipboard watcher and the commands are in register.tsx.++// kitty's rowcolumn-diacritics.txt: 297 combining marks; mark i means row or+// column i. (The same table is in Claude Code's binary.)+export const DIACRITICS: readonly number[] = [+ 0x0305, 0x030d, 0x030e, 0x0310, 0x0312, 0x033d, 0x033e, 0x033f, 0x0346, 0x034a, 0x034b, 0x034c,+ 0x0350, 0x0351, 0x0352, 0x0357, 0x035b, 0x0363, 0x0364, 0x0365, 0x0366, 0x0367, 0x0368, 0x0369,+ 0x036a, 0x036b, 0x036c, 0x036d, 0x036e, 0x036f, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487, 0x0592,+ 0x0593, 0x0594, 0x0595, 0x0597, 0x0598, 0x0599, 0x059c, 0x059d, 0x059e, 0x059f, 0x05a0, 0x05a1,+ 0x05a8, 0x05a9, 0x05ab, 0x05ac, 0x05af, 0x05c4, 0x0610, 0x0611, 0x0612, 0x0613, 0x0614, 0x0615,+ 0x0616, 0x0617, 0x0657, 0x0658, 0x0659, 0x065a, 0x065b, 0x065d, 0x065e, 0x06d6, 0x06d7, 0x06d8,+ 0x06d9, 0x06da, 0x06db, 0x06dc, 0x06df, 0x06e0, 0x06e1, 0x06e2, 0x06e4, 0x06e7, 0x06e8, 0x06eb,+ 0x06ec, 0x0730, 0x0732, 0x0733, 0x0735, 0x0736, 0x073a, 0x073d, 0x073f, 0x0740, 0x0741, 0x0743,+ 0x0745, 0x0747, 0x0749, 0x074a, 0x07eb, 0x07ec, 0x07ed, 0x07ee, 0x07ef, 0x07f0, 0x07f1, 0x07f3,+ 0x0816, 0x0817, 0x0818, 0x0819, 0x081b, 0x081c, 0x081d, 0x081e, 0x081f, 0x0820, 0x0821, 0x0822,+ 0x0823, 0x0825, 0x0826, 0x0827, 0x0829, 0x082a, 0x082b, 0x082c, 0x082d, 0x0951, 0x0953, 0x0954,+ 0x0f82, 0x0f83, 0x0f86, 0x0f87, 0x135d, 0x135e, 0x135f, 0x17dd, 0x193a, 0x1a17, 0x1a75, 0x1a76,+ 0x1a77, 0x1a78, 0x1a79, 0x1a7a, 0x1a7b, 0x1a7c, 0x1b6b, 0x1b6d, 0x1b6e, 0x1b6f, 0x1b70, 0x1b71,+ 0x1b72, 0x1b73, 0x1cd0, 0x1cd1, 0x1cd2, 0x1cda, 0x1cdb, 0x1ce0, 0x1dc0, 0x1dc1, 0x1dc3, 0x1dc4,+ 0x1dc5, 0x1dc6, 0x1dc7, 0x1dc8, 0x1dc9, 0x1dcb, 0x1dcc, 0x1dd1, 0x1dd2, 0x1dd3, 0x1dd4, 0x1dd5,+ 0x1dd6, 0x1dd7, 0x1dd8, 0x1dd9, 0x1dda, 0x1ddb, 0x1ddc, 0x1ddd, 0x1dde, 0x1ddf, 0x1de0, 0x1de1,+ 0x1de2, 0x1de3, 0x1de4, 0x1de5, 0x1de6, 0x1dfe, 0x20d0, 0x20d1, 0x20d4, 0x20d5, 0x20d6, 0x20d7,+ 0x20db, 0x20dc, 0x20e1, 0x20e7, 0x20e9, 0x20f0, 0x2cef, 0x2cf0, 0x2cf1, 0x2de0, 0x2de1, 0x2de2,+ 0x2de3, 0x2de4, 0x2de5, 0x2de6, 0x2de7, 0x2de8, 0x2de9, 0x2dea, 0x2deb, 0x2dec, 0x2ded, 0x2dee,+ 0x2def, 0x2df0, 0x2df1, 0x2df2, 0x2df3, 0x2df4, 0x2df5, 0x2df6, 0x2df7, 0x2df8, 0x2df9, 0x2dfa,+ 0x2dfb, 0x2dfc, 0x2dfd, 0x2dfe, 0x2dff, 0xa66f, 0xa67c, 0xa67d, 0xa6f0, 0xa6f1, 0xa8e0, 0xa8e1,+ 0xa8e2, 0xa8e3, 0xa8e4, 0xa8e5, 0xa8e6, 0xa8e7, 0xa8e8, 0xa8e9, 0xa8ea, 0xa8eb, 0xa8ec, 0xa8ed,+ 0xa8ee, 0xa8ef, 0xa8f0, 0xa8f1, 0xaab0, 0xaab2, 0xaab3, 0xaab7, 0xaab8, 0xaabe, 0xaabf, 0xaac1,+ 0xfe20, 0xfe21, 0xfe22, 0xfe23, 0xfe24, 0xfe25, 0xfe26, 0x10a0f, 0x10a38, 0x1d185, 0x1d186, 0x1d187,+ 0x1d188, 0x1d189, 0x1d1aa, 0x1d1ab, 0x1d1ac, 0x1d1ad, 0x1d242, 0x1d243, 0x1d244,+]+export const PLACEHOLDER = 0x10eeee+const INDEX = new Map(DIACRITICS.map((cp, i) => [cp, i]))++// The cell string Claude Code draws at (row, col): for the tests.+export const placeholderCell = (row: number, col: number) =>+ String.fromCodePoint(PLACEHOLDER, DIACRITICS[row]!, DIACRITICS[col]!)++export const hasPlaceholders = (text: string) => text.includes(String.fromCodePoint(PLACEHOLDER))++// One screen row of a picture in the selection: its row in the picture and+// the first and last picture columns selected (inclusive).+export type RunLine = { row: number; colStart: number; colEnd: number }+// The selection in order: plain text lines, and runs of picture rows (one+// picture's rows, top to bottom).+export type Segment = { kind: 'text'; text: string } | { kind: 'image'; lines: RunLine[] }++// The reply bullet and the gutter's spaces left of a picture.+const GUTTER = /^[\s⏺●]*$/++// The selection's text as segments. A run ends where a row does not follow+// the one above (the next picture, or the next page of the same answer,+// starts again at row 0) or where a line has no placeholder.+export function decodeSelection(text: string): Segment[] {+ const out: Segment[] = []+ let run: RunLine[] | null = null+ const addText = (line: string) => {+ run = null+ const last = out[out.length - 1]+ if (last?.kind === 'text') last.text += `\n${line}`+ else out.push({ kind: 'text', text: line })+ }+ for (const line of text.split(/\r?\n/)) {+ const cps = Array.from(line, c => c.codePointAt(0)!)+ const cells: { row: number; col: number }[] = []+ let other = ''+ for (let i = 0; i < cps.length; i++) {+ if (cps[i] !== PLACEHOLDER) {+ other += String.fromCodePoint(cps[i]!)+ continue+ }+ const row = INDEX.get(cps[i + 1] ?? -1)+ const col = INDEX.get(cps[i + 2] ?? -1)+ if (row === undefined) continue+ i += col === undefined ? 1 : 2+ // No column mark: the cell after the one before (kitty's rule).+ const prev = cells[cells.length - 1]+ cells.push({ row, col: col ?? (prev && prev.row === row ? prev.col + 1 : 0) })+ }+ if (!cells.length) {+ addText(line)+ continue+ }+ if (!GUTTER.test(other)) addText(other.trim())+ const row = cells[0]!.row+ const cols = cells.filter(c => c.row === row).map(c => c.col)+ const at: RunLine = { row, colStart: Math.min(...cols), colEnd: Math.max(...cols) }+ const open = run as RunLine[] | null+ if (open && open[open.length - 1]!.row < row) open.push(at)+ else {+ run = [at]+ out.push({ kind: 'image', lines: run })+ }+ }+ // A selection's last line break gives an empty last line: not text.+ const last = out[out.length - 1]+ if (last?.kind === 'text') {+ last.text = last.text.replace(/\n+$/, '')+ if (!last.text) out.pop()+ }+ return out+}++// ---- Where the words are ---------------------------------------------------++// A probe mark as `typst query <mdpos> --field value` gives it (pt).+export type Mark = {+ k: 'w' | 'c' | 'b'+ p: number+ x: number+ y: number+ s?: number+ t?: string+ w?: number+ h?: number+ n?: number+ a?: number+ d?: number+ kind?: string+ prefix?: string+ cx?: number+}+// A word, or a whole code line (`adv`: its character advance), in PNG+// pixels: its box, the block it is in, and its place in the document (`i`).+export type Item = { i: number; text: string; x0: number; y0: number; x1: number; y1: number; block: number; adv?: number }+// A block: paragraph, heading, code, quote, cell (`cx` its column), item+// (`prefix`); `first` its first item.+export type TextBlock = { kind: string; prefix: string; cx?: number; first: number }+// positions.json: by page (0-based: PNG page N+1).+export type Positions = { ppi: number; blocks: TextBlock[]; pages: Item[][] }++const round = (n: number) => Math.round(n * 100) / 100++// The probe's marks (document order) as boxes in pixels at `ppi`. A list's+// number ("1.") is drawn before its item's mark: it is dropped, the item's+// prefix says it. A block mark with no word since the last one (an item,+// then its paragraph) adds to that block.+export function positionsOf(marks: readonly Mark[], ppi: number): Positions {+ const k = ppi / 72+ const blocks: TextBlock[] = []+ const pages: Item[][] = []+ let hasItems = false+ let count = 0+ marks.forEach((m, j) => {+ if (m.k === 'b') {+ const cur = blocks[blocks.length - 1]+ if (cur && !hasItems) {+ cur.prefix ||= m.prefix ?? ''+ if (m.kind === 'cell') Object.assign(cur, { kind: 'cell', cx: m.cx ?? 0 })+ else if (cur.kind !== 'item' && cur.kind !== 'cell') cur.kind = m.kind ?? cur.kind+ } else {+ blocks.push({ kind: m.kind ?? 'par', prefix: m.prefix ?? '', ...(m.kind === 'cell' ? { cx: m.cx ?? 0 } : {}), first: -1 })+ hasItems = false+ }+ return+ }+ const next = marks[j + 1]+ if (m.k === 'w' && next?.k === 'b' && next.kind === 'item' && next.prefix?.trim() === m.t) return+ if (!blocks.length) blocks.push({ kind: 'par', prefix: '', first: -1 })+ const block = blocks.length - 1+ const item: Item =+ m.k === 'c'+ ? {+ i: count, text: m.t ?? '', block, x0: round(m.x * k), x1: round((m.x + (m.w ?? 0)) * k),+ y0: round((m.y - (m.a ?? 0.8 * (m.s ?? 11))) * k), y1: round((m.y + (m.d ?? 0.25 * (m.s ?? 11))) * k),+ adv: m.n ? ((m.w ?? 0) * k) / m.n : 0,+ }+ : { i: count, text: m.t ?? '', block, x0: round(m.x * k), x1: round((m.x + (m.w ?? 0)) * k), y0: round(m.y * k), y1: round((m.y + (m.h ?? m.s ?? 11)) * k) }+ if (!item.text) return+ count+++ if (!hasItems) blocks[block]!.first = item.i+ hasItems = true+ const page = Math.max(0, m.p - 1)+ while (pages.length <= page) pages.push([])+ pages[page]!.push(item)+ })+ return { ppi, blocks, pages }+}++// ---- Which page a run is ---------------------------------------------------++// A page drawn this session: its PNG size and the rows its Image takes.+export type DrawnPage = { file: string; width: number; height: number; rows: number }+// An answer drawn this session (`seq` grows with each new one).+export type Drawn = { id: string; seq: number; columns: number; dir: string; pages: DrawnPage[] }+export type Pick = { id: string; page: number } | null++// For each segment, the drawn page its run is (null: text, or none fits).+// Runs next to each other (no text between) are one picture after the other,+// so consecutive pages of one answer: a run that goes on in the next must+// end on its page's last row, and the next start at row 0. A chain is+// matched to the answer `requestId` names (the selection's transcript row)+// when it fits, else to the newest answer it fits. Ambiguous by nature: a+// run inside one page of a many-page answer fits every page tall enough,+// and the first such page is taken; an older answer drawn at the same width+// fits as well as the newest.+export function pickPages(segments: readonly Segment[], drawn: readonly Drawn[], requestId?: string): Pick[] {+ const picks: Pick[] = segments.map(() => null)+ const order = [...drawn].sort((a, b) => (a.id === requestId ? -1 : b.id === requestId ? 1 : b.seq - a.seq))+ let i = 0+ while (i < segments.length) {+ if (segments[i]!.kind !== 'image') {+ i+++ continue+ }+ let j = i+ while (j < segments.length && segments[j]!.kind === 'image') j+++ const runs = segments.slice(i, j) as { kind: 'image'; lines: RunLine[] }[]+ const fits = (d: Drawn, start: number) =>+ runs.every((run, n) => {+ const page = d.pages[start + n]+ if (!page) return false+ const rows = run.lines.map(l => l.row)+ const maxRow = Math.max(...rows)+ const maxCol = Math.max(...run.lines.map(l => l.colEnd))+ if (maxRow >= page.rows || maxCol >= d.columns) return false+ if (n > 0 && Math.min(...rows) !== 0) return false+ return n === runs.length - 1 || maxRow === page.rows - 1+ })+ found: for (const d of order) {+ for (let start = 0; start + runs.length <= d.pages.length; start++) {+ if (!fits(d, start)) continue+ runs.forEach((_, n) => (picks[i + n] = { id: d.id, page: start + n }))+ break found+ }+ }+ i = j+ }+ return picks+}++// ---- The text under a run --------------------------------------------------++// The words of one page under a run, in reading order. The picture fills+// `columns` x `rows` cells, so a cell is width / columns by height / rows+// PNG pixels. A word is under the run when its box's centre is in a selected+// cell (its row by the vertical centre, its column by the horizontal one):+// half a word selected copies the word when the selection covers its middle.+// A code line is cut by characters, each by its own centre.+export function textOfRun(lines: readonly RunLine[], items: readonly Item[], blocks: readonly TextBlock[], page: { width: number; height: number; rows: number }, columns: number): string {+ const colW = page.width / columns+ const rowH = page.height / page.rows+ const sel = new Map(lines.map(l => [l.row, l]))+ const picked: { item: Item; text: string }[] = []+ for (const item of items) {+ const line = sel.get(Math.floor((item.y0 + item.y1) / 2 / rowH))+ if (!line) continue+ const inside = (x: number) => {+ const col = Math.floor(x / colW)+ return col >= line.colStart && col <= line.colEnd+ }+ if (item.adv) {+ const chars = Array.from(item.text)+ const kept = chars.filter((_, c) => inside(item.x0 + (c + 0.5) * item.adv!))+ if (!kept.length) continue+ const first = chars.findIndex((_, c) => inside(item.x0 + (c + 0.5) * item.adv!))+ picked.push({ item, text: chars.slice(first, first + kept.length).join('') })+ } else if (inside((item.x0 + item.x1) / 2)) picked.push({ item, text: item.text })+ }+ return joinItems(picked, blocks)+}++// Joins picked words: a new line between blocks (a tab between the cells of+// a table row), a block's prefix when its first word is in, a new line+// between code lines; inside a block a space between words, none between+// the pieces of one word (boxes on one line closer than a fifth of the line+// height: a space is wider, the padding beside inline code narrower), none after a - or /+// that ends a line.+export function joinItems(picked: readonly { item: Item; text: string }[], blocks: readonly TextBlock[]): string {+ let out = ''+ let prev: { item: Item; text: string } | null = null+ const prefixOf = (item: Item) => {+ const b = blocks[item.block]+ return b?.prefix && b.first === item.i ? b.prefix : ''+ }+ for (const p of picked) {+ if (!prev) out += prefixOf(p.item)+ else if (p.item.block !== prev.item.block) {+ const b = blocks[p.item.block]+ const before = blocks[prev.item.block]+ out += b?.kind === 'cell' && (b.cx ?? 0) > 0 && before?.kind === 'cell' ? '\t' : '\n'+ out += prefixOf(p.item)+ } else if (p.item.adv !== undefined || prev.item.adv !== undefined) out += '\n'+ else {+ const height = p.item.y1 - p.item.y0+ const sameLine = Math.abs((p.item.y0 + p.item.y1) / 2 - (prev.item.y0 + prev.item.y1) / 2) < height / 2+ if (sameLine) out += p.item.x0 - prev.item.x1 > height * 0.2 ? ' ' : ''+ else out += /[-/]$/.test(prev.text) ? '' : ' '+ }+ out += p.text+ prev = p+ }+ return out+}++// The copy: text segments as they are, each run as its page's text (a run+// with no page, or no words, gives nothing), joined by new lines.+export function joinSegments(segments: readonly Segment[], texts: readonly (string | null)[]): string {+ return segments+ .map((s, i) => (s.kind === 'text' ? s.text : texts[i] ?? ''))+ .filter((t, i) => t !== '' || segments[i]!.kind === 'text')+ .join('\n')+}++// For /md-preview dump: the first `max` cells or characters of the+// text, a placeholder cell as `[r,c]`, other characters as U+XXXX.+export function codePointsOf(text: string, max = 40): string {+ const cps = Array.from(text, c => c.codePointAt(0)!)+ const out: string[] = []+ for (let i = 0; i < cps.length && out.length < max; i++) {+ const cp = cps[i]!+ if (cp === PLACEHOLDER) {+ const row = INDEX.get(cps[i + 1] ?? -1)+ const col = INDEX.get(cps[i + 2] ?? -1)+ out.push(`U+10EEEE[${row ?? '?'},${col ?? '?'}]`)+ i += (row === undefined ? 0 : 1) + (col === undefined ? 0 : 1)+ } else out.push(`U+${cp.toString(16).toUpperCase().padStart(4, '0')}`)+ }+ return out.join(' ')+}diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.tsindex 7c73a33..cbb3494 100644--- a/hooks/lib/settings.ts+++ b/hooks/lib/settings.ts@@ -51,6 +51,9 @@ export const NO_NETWORK = 'http://127.0.0.1:9'// how long one read may take.export const HOST_POLL_MS = 3000export const HOST_CHECK_MS = 2000+// How often the clipboard is read (macOS pbpaste) for a mouse copy of+// answer pictures.+export const CLIP_POLL_MS = 300// The base every theme merges over (its theme.json and syntax files).export const BASE_THEME = 'vscode'// The theme used when none is chosen, or when the chosen one is not usable.diff --git a/hooks/lib/state.ts b/hooks/lib/state.tsindex b126b99..6650326 100644--- a/hooks/lib/state.ts+++ b/hooks/lib/state.ts@@ -7,6 +7,7 @@ import type { MdPreviewTheme } from '../../types'import type { ThemeInfo } from './themes'import type { HostMode, ThemeSetting } from './mode'import type { PlanVerdict } from './plan'+import type { Drawn, Positions } from './copy'import { DEFAULT_SIZE } from './settings'// The `done` atom (see types/index.d.ts) for refresh. The state scan of@@ -156,3 +157,23 @@ export const writesLive = new Map<string, number>()export function refresh($: EngineInterface) {void update($, done, n => n + 1).catch(() => $.ui.invalidate('ui.render'))}++// Copy: the answers drawn this session by their requestId (a plan by+// `plan:<tool_use_id>`; oldest first, at most DRAWN_KEPT), each answer+// folder's word positions once read, and the clipboard watcher's state: its+// timer and when it last ran, the clipboard text last seen and last written+// (so a write is never read back as new), the last text with placeholders+// and how it was read (for dump).+export const drawnAnswers = new Map<string, Drawn>()+export const DRAWN_KEPT = 64+export const positionsByDir = new Map<string, Positions>()+export const clip = {+ watch: null as { cancel: () => void } | null,+ ticked: 0,+ busy: false,+ seen: '',+ wrote: '',+ raw: '',+ seq: 0,+ last: null as unknown,+}diff --git a/hooks/lib/typst.ts b/hooks/lib/typst.tsindex 584e1a9..948d6a8 100644--- a/hooks/lib/typst.ts+++ b/hooks/lib/typst.ts@@ -8,6 +8,7 @@ import { firstLine, imagePathOf, localImages, plainOf, splitSegments } from './mimport { inlineBudget } from './terminal'import { alignFirstLine, firstLineOf, fontFit, sizing } from './draw'import { HEADERS_SH } from './host'+import { positionsOf, type Mark, type Positions } from './copy'// The typst command and its environment. Network off (see NO_NETWORK) and a// package cache of our own, so only the vendored packages load.@@ -140,26 +141,33 @@ export async function existingImages($: EngineInterface, segments: readonly strireturn found}-export async function runTypst($: EngineInterface, job: Job, segments: readonly string[], dir: string, tag: string, isSafe: boolean) {+// The template's inputs for a job (the PNG compile and the probe share them).+export function typstInputs(job: Job, segments: readonly string[], dir: string, isSafe: boolean) {const fit = fontFit(job.env.metrics, job.size)const { widthPt, ppi, rowPt } = sizing(job.columns, job.cell, fit.columnPt)const { topPt } = alignFirstLine(firstLineOf(segments[0] ?? ''), rowPt)+ const inputs: Record<string, string | number> = {+ theme: job.theme,+ width: widthPt,+ top: topPt,+ row: Math.round(rowPt * 10000) / 10000,+ code: fit.code,+ ...(job.env.termFont ? { 'term-font': job.env.termFont } : {}),+ 'theme-dir': job.themeDir,+ doc: `${dir}/doc.json`,+ ...(isSafe ? { safe: 1 } : {}),+ }+ return { inputs, ppi }+}++export async function runTypst($: EngineInterface, job: Job, segments: readonly string[], dir: string, tag: string, isSafe: boolean) {+ const { inputs, ppi } = typstInputs(job, segments, dir, isSafe)const { argv, env: vars } = typstCall({typst: job.env.typst!,root: job.env.root,cache: job.env.cache,ppi,- inputs: {- theme: job.theme,- width: widthPt,- top: topPt,- row: Math.round(rowPt * 10000) / 10000,- code: fit.code,- ...(job.env.termFont ? { 'term-font': job.env.termFont } : {}),- 'theme-dir': job.themeDir,- doc: `${dir}/doc.json`,- ...(isSafe ? { safe: 1 } : {}),- },+ inputs,out: `${dir}/${tag}-{0p}.png`,})return $.process@@ -167,6 +175,41 @@ export async function runTypst($: EngineInterface, job: Job, segments: readonly.catch((err: unknown) => ({ exitCode: 1, stdout: '', stderr: `typst did not run: ${String(err)}` }))}+// ---- The probe: where the words are ---------------------------------------++// `typst query` of the template's <mdpos> marks with probe=1: the PNG+// compile's own inputs, root, package path and env (no ppi, format or out).+export function probeCall(o: { typst: string; root: string; cache: string; inputs: Readonly<Record<string, string | number>> }): { argv: string[]; env: Record<string, string> } {+ const argv = [+ o.typst, 'query',+ '--root', '/',+ '--package-path', `${o.root}/render/packages`,+ '--diagnostic-format', 'short',+ ...Object.entries({ ...o.inputs, probe: 1 }).flatMap(([k, v]) => ['--input', `${k}=${v}`]),+ `${o.root}/render/md.typ`,+ '<mdpos>',+ '--field', 'value',+ ]+ return { argv, env: noNetworkEnv(o.cache) }+}++// What a page set's probe needs, kept as probe.json beside pages.json, so+// positions.json can be made later (a key compiled in an earlier session).+export type ProbeJob = { argv: string[]; env: Record<string, string>; ppi: number }++// Runs the probe and writes positions.json; the positions, or null.+export async function runProbe($: EngineInterface, dir: string, probe: ProbeJob): Promise<Positions | null> {+ const got = await $.process.run(probe.argv, { timeoutMs: COMPILE_TIMEOUT_MS, env: probe.env }).catch(() => null)+ if (!got || got.exitCode !== 0 || got.isStdoutTruncated) return null+ try {+ const positions = positionsOf(JSON.parse(got.stdout) as Mark[], probe.ppi)+ await $.fs.write(`${dir}/positions.json`, JSON.stringify(positions))+ return positions+ } catch {+ return null+ }+}+export async function compile($: EngineInterface, job: Job): Promise<Result | 'failed'> {const dir = `${job.env.cache}/${job.key}`const kept = await $.fs.read(`${dir}/pages.json`).catch(() => null)@@ -205,6 +248,10 @@ export async function compile($: EngineInterface, job: Job): Promise<Result | 'freturn 'failed'}const pages = files.map((file, i) => ({ file, ...sizes[i]!, alt: plainOf(segments[i] ?? job.text) }))+ // The probe after the PNGs, not awaited: the pictures never wait for it.+ const { inputs, ppi } = typstInputs(job, segments, dir, tag === 'b')+ const probe: ProbeJob = { ...probeCall({ typst: job.env.typst!, root: job.env.root, cache: job.env.cache, inputs }), ppi }+ void $.fs.write(`${dir}/probe.json`, JSON.stringify(probe)).then(() => runProbe($, dir, probe)).catch(() => undefined)const { rowPt } = sizing(job.columns, job.cell, fontFit(job.env.metrics, job.size).columnPt)const { bulletRow } = alignFirstLine(firstLineOf(segments[0] ?? ''), rowPt)const result: Result = { pages, columns: job.columns, bulletRow, ...(note ? { note } : {}) }diff --git a/hooks/register.tsx b/hooks/register.tsxindex 2633027..6478053 100644--- a/hooks/register.tsx+++ b/hooks/register.tsx@@ -13,21 +13,25 @@// The work is in ./lib, one topic per module: settings, state (the shared// mutable state `S`), markdown, terminal, terminals, mode, themes, command,// setup, host, typst, draw, stream, answer (one text through the pipeline),-// env, images, pictures and plan (the plan approval flow). This file joins-// them to the hooks, and gives the tests the names they import.+// env, images, pictures, plan (the plan approval flow) and copy (the text+// under a mouse copy of the pictures). This file joins them to the hooks,+// and gives the tests the names they import.import { atom, read, update } from 'claude-code'import type { EngineInterface, Register, RenderElement, RenderViewport } from 'claude-code'-import { DEFAULT_THEME, MAX_SIZE, MIN_SIZE, TYPST_PROMPT } from './lib/settings'-import { editedPlans, refresh, S, subagentPlans, writesLive, type Env } from './lib/state'+import { CLIP_POLL_MS, DEFAULT_THEME, MAX_SIZE, MIN_SIZE, TYPST_PROMPT } from './lib/settings'+import {+ clip, DRAWN_KEPT, drawnAnswers, editedPlans, positionsByDir, refresh, S, subagentPlans, writesLive, type Cell, type Env, type Result,+} from './lib/state'import { columnsFor } from './lib/terminal'import { escapeControls, luminanceOf, modeLine, modeOfLuminance, parseOsc11, settingOf } from './lib/mode'import { applyTheme, themeListing, userThemesOf } from './lib/themes'import { commandSuggestions, parseCommand, registerCommand } from './lib/command'import { runSetup } from './lib/setup'import { pollHost, PROBE_RUNS, probeOsc11, showMode, USE_OSC11, watchHost } from './lib/host'-import { measureFonts } from './lib/typst'-import { drawPages } from './lib/draw'+import { measureFonts, runProbe, type ProbeJob } from './lib/typst'+import { drawPages, rowsFor } from './lib/draw'+import { codePointsOf, decodeSelection, hasPlaceholders, joinSegments, pickPages, textOfRun, type Pick, type Positions, type Segment } from './lib/copy'import { finalizeAll } from './lib/stream'import { pagesOf } from './lib/answer'import { noteViewport, setUp } from './lib/env'@@ -56,9 +60,10 @@ export {export { commandSuggestions, parseCommand, type Command, type Suggestion } from './lib/command'export { hasSetup, SETUP_END, SETUP_START, setupBlock, shellRcOf, withoutSetup, withSetup, type ShellRc } from './lib/setup'export { OSC11_PL } from './lib/host'-export { convertCall, measureCall, noNetworkEnv, parseOd, pngSize, shouldRetrySafe, typstCall } from './lib/typst'+export { convertCall, measureCall, noNetworkEnv, parseOd, pngSize, probeCall, shouldRetrySafe, typstCall } from './lib/typst'export { alignFirstLine, firstLineOf, fontFit, hashOf, renderKey, rowsFor, sizing, type FirstLine } from './lib/draw'export * from './lib/images'+export * from './lib/copy'export {choiceOf, decisionOf, editorArgv, feedbackOf, isPlanQuestion, normalPath, PLAN_ASK_LINE, PLAN_AUTO, PLAN_CLEAR, PLAN_DRAWING, PLAN_EDIT,PLAN_FEEDBACK, PLAN_HEADER, PLAN_IMPLEMENT, PLAN_MANUAL, PLAN_QUESTION, PLAN_QUESTION_EDITED, PLAN_REJECTED, planFileOf, planInputOf,@@ -107,12 +112,173 @@ async function planEnv($: EngineInterface): Promise<Env | null> {return ready?.typst && ready.canDraw ? ready : null}+// ---- Copy -----------------------------------------------------------------+// A mouse copy over a picture puts kitty placeholder cells on the clipboard,+// and no hook sees that copy, so the clipboard is read afterwards (pbpaste,+// every CLIP_POLL_MS on macOS) and, when it holds placeholders, written+// again with the words under them (see lib/copy.ts).++// An answer's pages as drawn: kept by requestId, newest last. A redraw with+// the same pages keeps its place, so `seq` is when it was first drawn so.+function noteDrawn(id: string, result: Result, columns: number, px: Cell) {+ const pages = result.pages.map(p => ({ file: p.file, width: p.width, height: p.height, rows: rowsFor(p, columns, px) }))+ const dir = result.pages[0]?.file.replace(/\/[^/]*$/, '') ?? ''+ const was = drawnAnswers.get(id)+ if (was && was.dir === dir && was.columns === columns && was.pages.every((p, i) => p.rows === pages[i]?.rows)) return+ drawnAnswers.delete(id)+ drawnAnswers.set(id, { id, seq: ++clip.seq, columns, dir, pages })+ for (const old of drawnAnswers.keys()) {+ if (drawnAnswers.size <= DRAWN_KEPT) break+ drawnAnswers.delete(old)+ }+}++// An answer folder's word positions: positions.json, else the probe run now+// (from probe.json: a key compiled before this load, or a probe not done yet).+async function positionsFor($: EngineInterface, dir: string): Promise<Positions | null> {+ const known = positionsByDir.get(dir)+ if (known) return known+ let got: Positions | null = null+ const kept = await $.fs.read(`${dir}/positions.json`).catch(() => null)+ try {+ if (kept) got = JSON.parse(kept) as Positions+ } catch {}+ if (!got) {+ const probe = await $.fs.read(`${dir}/probe.json`).catch(() => null)+ try {+ if (probe) got = await runProbe($, dir, JSON.parse(probe) as ProbeJob)+ } catch {}+ }+ if (got) positionsByDir.set(dir, got)+ return got+}++type CopyRead = { text: string; segments: Segment[]; picks: Pick[]; runs: number; resolved: number }++// The text for a clipboard (or selection) text with placeholders.+async function readCopy($: EngineInterface, raw: string, requestId?: string): Promise<CopyRead> {+ const segments = decodeSelection(raw)+ const picks = pickPages(segments, [...drawnAnswers.values()], requestId)+ const texts: (string | null)[] = []+ let resolved = 0+ for (const [i, seg] of segments.entries()) {+ const pick = picks[i]+ const d = pick ? drawnAnswers.get(pick.id) : undefined+ const page = pick && d ? d.pages[pick.page] : undefined+ if (seg.kind !== 'image' || !pick || !d || !page) {+ texts.push(null)+ continue+ }+ const positions = await positionsFor($, d.dir)+ const text = positions ? textOfRun(seg.lines, positions.pages[pick.page] ?? [], positions.blocks, page, d.columns) : ''+ if (text) resolved+++ texts.push(text || null)+ }+ const runs = segments.filter(seg => seg.kind === 'image').length+ const read = { text: joinSegments(segments, texts), segments, picks, runs, resolved }+ clip.last = { requestId: requestId ?? null, ...read, drawn: [...drawnAnswers.values()].map(d => ({ id: d.id, seq: d.seq, columns: d.columns, dir: d.dir, pages: d.pages.map(p => ({ rows: p.rows, width: p.width, height: p.height })) })) }+ return read+}++// One clipboard read: placeholders that are not our own write are read and+// written back as text. Never touches a clipboard with no placeholders.+async function clipTick($: EngineInterface) {+ if (clip.busy) return+ clip.busy = true+ try {+ const got = await $.process.run(['pbpaste'], { timeoutMs: 2000, env: { LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' } }).catch(() => null)+ if (!got || got.exitCode !== 0) return+ const text = got.stdout+ if (text === clip.seen) return+ clip.seen = text+ if (text === clip.wrote || !hasPlaceholders(text)) return+ clip.raw = text+ const selected = await $.ui.selection().catch(() => undefined)+ const read = await readCopy($, text, selected && hasPlaceholders(selected.text) ? selected.requestId : undefined)+ if (!read.resolved) {+ $.ui.toast('md-preview: could not read the selected picture (/md-preview dump says why)')+ return+ }+ clip.wrote = read.text+ clip.seen = read.text+ await $.ui.copy({ text: read.text })+ $.ui.toast(`md-preview: copied ${read.text.length} chars of text`)+ } finally {+ clip.busy = false+ }+}++// The watcher: on macOS, on this computer (over ssh pbpaste reads the remote+// one's clipboard). One per load: a hot reload drops the old load's timers.+// A timer whose period was refused stops; one silent for 10 periods is+// started again (`ticked` is when it last ran).+function watchClipboard($: EngineInterface) {+ if (!S.env?.isMac || S.isRemote) return+ if (clip.watch && Date.now() - clip.ticked < 10 * CLIP_POLL_MS) return+ clip.watch?.cancel()+ clip.ticked = Date.now()+ try {+ clip.watch = $.clock.every(CLIP_POLL_MS, () => {+ clip.ticked = Date.now()+ void clipTick($).catch(() => undefined)+ })+ } catch {+ clip.watch = null+ }+}++// /md-preview grab: the last mouse selection, read and copied.+async function grab($: EngineInterface): Promise<string> {+ const selected = await $.ui.selection().catch(() => undefined)+ if (!selected) return 'md-preview: no mouse selection (it needs fullscreen mode; select over a picture first).'+ if (!hasPlaceholders(selected.text)) return `md-preview: the selection has no picture cells; it is ${selected.text.length} chars of text already.`+ clip.raw = selected.text+ const read = await readCopy($, selected.text, selected.requestId)+ if (!read.resolved) return `md-preview: found ${read.runs} picture run(s) but could not read them (see /md-preview dump).`+ clip.wrote = read.text+ clip.seen = read.text+ const copied = await $.ui.copy({ text: read.text })+ return copied.isCopied+ ? `md-preview: copied ${read.text.length} chars (${read.resolved} of ${read.runs} picture runs read${selected.requestId ? `, row ${selected.requestId}` : ''}).`+ : `md-preview: the copy failed: ${'reason' in copied ? String(copied.reason) : 'unknown'}.`+}++// /md-preview dump: the last placeholder text seen, as code points, how+// it was read, and the same in full in <cache>/copy-debug.json.+async function dump($: EngineInterface): Promise<string> {+ if (!clip.raw) return `md-preview: no clipboard text with picture cells seen yet (watcher ${clip.watch ? 'on' : 'off'}; ${drawnAnswers.size} answers drawn).`+ const read = await readCopy($, clip.raw)+ const runs = read.segments+ .map((seg, i) => {+ if (seg.kind === 'text') return `text: ${JSON.stringify(seg.text.slice(0, 60))}`+ const rows = seg.lines.map(l => `${l.row}:${l.colStart}-${l.colEnd}`).join(' ')+ const pick = read.picks[i]+ return `run rows ${rows} -> ${pick ? `answer ${pick.id} page ${pick.page}` : 'no page fits'}`+ })+ .join('\n')+ const cache = S.env?.cache ?? ''+ if (cache) await $.fs.write(`${cache}/copy-debug.json`, JSON.stringify({ raw: clip.raw, codePoints: codePointsOf(clip.raw, 100000), ...(clip.last as object) }, null, 1)).catch(() => undefined)+ return [+ `md-preview: last clipboard with picture cells (${Array.from(clip.raw).length} code points; watcher ${clip.watch ? 'on' : 'off'}):`,+ codePointsOf(clip.raw, 40),+ runs,+ `Read as ${read.text.length} chars: ${JSON.stringify(read.text.slice(0, 200))}`,+ cache ? `Full dump: ${cache}/copy-debug.json` : '',+ ].filter(Boolean).join('\n')+}+// ---- Hooks ----------------------------------------------------------------export const register: Register = on => {on('session.start', async ($, e, next) => {await registerCommand($)- void setUp($).catch(() => undefined)+ void setUp($).then(() => watchClipboard($)).catch(() => undefined)+ return next(e)+ })++ on('session.end', async ($, e, next) => {+ clip.watch?.cancel()+ clip.watch = nullreturn next(e)})@@ -127,6 +293,8 @@ export const register: Register = on => {on('command.run', { command: 'md-preview' }, async ($, e) => {const asked = parseCommand(e.args)+ if (asked.kind === 'grab') return { text: await grab($) }+ if (asked.kind === 'dump') return { text: await dump($) }if (asked.kind === 'on' || asked.kind === 'off') {await update($, isOn, () => asked.kind === 'on')await $.store.set('enabled', asked.kind === 'on')@@ -266,7 +434,13 @@ export const register: Register = on => {if (!ready) return next(e)const columns = columnsFor(e.viewport?.columns)const drawing = await pagesOf($, { id: e.requestId, text: e.props.text, columns, env: ready, canStream: true })- if (drawing.kind === 'pages') return drawPages($, e, drawing.result, columns, drawing.px, drawing.bytes, { bullet: !!e.props.isFirstOfReply })+ if (drawing.kind === 'pages') {+ try {+ noteDrawn(e.requestId, drawing.result, columns, drawing.px)+ watchClipboard($)+ } catch {}+ return drawPages($, e, drawing.result, columns, drawing.px, drawing.bytes, { bullet: !!e.props.isFirstOfReply })+ }if (drawing.kind === 'text') return next(e)const { Box } = $.ui.resolve(e)return <Box />@@ -325,6 +499,7 @@ export const register: Register = on => {// The main loop's running turn, which "clear context" ends.on('turn.start', async ($, e, next) => {if (e.agentId === undefined) S.mainTurnId = e.turnId+ watchClipboard($)return next(e)}).catch(($, e, next) => next(e))@@ -341,6 +516,14 @@ export const register: Register = on => {if (!ready) return rowconst columns = columnsFor(e.viewport?.columns)const drawing = await pagesOf($, { id: `plan:${e.props.tool_use_id}`, text: plan, columns, env: ready, canStream: false })+ // Its pages can be copied as an answer's: kept by the call's id, as the+ // row's requestId can be an answer's own.+ if (drawing.kind === 'pages') {+ try {+ noteDrawn(`plan:${e.props.tool_use_id}`, drawing.result, columns, drawing.px)+ watchClipboard($)+ } catch {}+ }return drawPlanUse($, e, row, drawing, columns)} catch {return rowdiff --git a/render/md.typ b/render/md.typindex 46bdc08..6fb22cf 100644--- a/render/md.typ+++ b/render/md.typ@@ -208,6 +208,75 @@// running off the page.#show regex("\S{30,}"): it => it.text.clusters().join(sym.zws)+// ---------- probe: where the text lies ----------+// probe=1 is given only to `typst query <md.typ> "<mdpos>" --field value`+// (same inputs as the PNG compile), never to the PNG compile itself: the+// word rule below splits text into separately shaped runs, which moves+// glyphs by a fraction of a pixel (a PNG with probe=1 differs from one+// without in anti-aliasing, max 64/255 on a channel, but no word moves and+// no line breaks elsewhere). Its marks are `metadata` labelled <mdpos>, in+// document order:+// w: a word (a run of non-space characters, cut after - and /), boxed;+// x, y the top-left of its box: y is the top of its line box (text+// top-edge "ascender"), w its advance width and h its ascender-to-+// descender height. Its ink lies inside the box (1-4 px side bearings+// at 2.75 px/pt), its centre is y + h/2.+// c: a block code line: x its start, y its baseline, a and d the code+// font's ascender and descender, w its width, n its characters.+// b: a block starts: paragraph, heading, code block, quote, table cell+// (column `cx`), list item (`prefix`: "- ", "1. ", "- [x] ").+// Each mark has its page `p` (1-based, = the PNG's {0p}) and the text size+// `s`; all lengths in pt from the page's top-left. A bare (unboxed) mark at+// the start of a wrapped line is placed at the end of the line above, and+// one at a paragraph's end on the next line; hence the boxes.+#let probe = inp.at("probe", default: "0") not in ("", "0", "false", "no", "off")+#let mark(kind, ..extra) = context {+ let at = here().position()+ [#metadata((k: kind, p: at.page, x: at.x / 1pt, y: at.y / 1pt, s: text.size.to-absolute() / 1pt, ..extra.named()))<mdpos>]+}+// Block code sets this (an unused cost) so the word rule leaves its text to+// the line marks.+#let in-code(costs) = costs.runt == 101%+#let cjk = regex("[\\p{Han}\\p{Hiragana}\\p{Katakana}\\p{Hangul}]")+#let probe-rules(body) = {+ // A word is cut after a hyphen or a slash, where a line may break; a+ // token of 30+ characters is one word (it breaks anywhere, see above).+ show regex("\\S{30,}|[^\\s/-]*[/-]+|[^\\s/-]+"): it => context if in-code(text.costs) { it } else {+ let size = measure(it)+ let t = it.text+ if t.clusters().len() >= 30 or t.match(cjk) != none {+ // A long word (zws break chances, above) or CJK text (breaks+ // anywhere) keeps its breaks: only a mark where it starts.+ mark("w", t: t, w: size.width / 1pt, h: size.height / 1pt)+ it+ } else {+ // Boxed, so the mark is where the word is drawn (a bare mark at the+ // start of a wrapped line stays at the end of the line above).+ box({ mark("w", t: t, w: size.width / 1pt, h: size.height / 1pt); it })+ }+ }+ // A code line: a zero-size box at its start (its y is the baseline). An+ // empty line has none: a box would give it a height.+ show raw.line: it => context if not in-code(text.costs) or it.text == "" { it } else {+ let asc = measure(text(top-edge: "ascender", bottom-edge: "baseline", "x")).height+ let desc = measure(text(top-edge: "baseline", bottom-edge: "descender", "x")).height+ box(mark("c", t: it.text, w: measure(it.body).width / 1pt, n: it.text.clusters().len(), a: asc / 1pt, d: desc / 1pt))+ it+ }+ show raw.where(block: true): it => {+ mark("b", kind: "code")+ set text(costs: (runt: 101%))+ it+ }+ show par: it => { mark("b", kind: "par"); it }+ show heading: it => { mark("b", kind: "heading"); it }+ show quote.where(block: true): it => { mark("b", kind: "quote"); it }+ show table.cell: it => { mark("b", kind: "cell", cx: it.x); it }+ body+}+#show: body => if probe { probe-rules(body) } else { body }+#let item-mark(prefix, body) = if not probe { body } else { mark("b", kind: "item", prefix: prefix); body }+// ---------- helpers ----------#let alt-box(alt, why: none) = box(stroke: px + C.muted, inset: (x: 4pt, y: 1.5pt), outset: (y: 1pt), radius: 3pt,@@ -433,7 +502,11 @@#let md-list(..args) = {let items = args.pos()let tasks = items.map(task-split)- if tasks.all(t => t == none) { return list(..args) }+ if probe {+ items = items.zip(tasks).map(((it, t)) => item-mark(if t == none { "- " } else if t.at(0) { "- [x] " } else { "- [ ] " }, it))+ tasks = tasks.zip(items).map(((t, it)) => if t == none { none } else { (t.at(0), item-mark(if t.at(0) { "- [x] " } else { "- [ ] " }, t.at(1))) })+ }+ if tasks.all(t => t == none) { return list(..args.named(), ..items) }if tasks.all(t => t != none) {// GitHub-style: no bullet, the checkbox sits where the bullet would.let rows = tasks.map(t => (@@ -453,9 +526,12 @@// "1. [x] done": keep the number, put the checkbox after it.#let md-enum(..args) = {- let items = args.pos().map(it => {+ let start = args.named().at("start", default: 1)+ let start = if type(start) == int { start } else { 1 }+ let items = args.pos().enumerate().map(((i, it)) => {let t = task-split(it)- if t == none { it } else { [#checkbox(t.at(0)) #t.at(1)] }+ let it = if t == none { it } else { [#checkbox(t.at(0)) #t.at(1)] }+ item-mark(str(start + i) + ". ", it)})enum(..args.named(), ..items)}diff --git a/tests/copy-fixture.ts b/tests/copy-fixture.tsnew file mode 100644index 0000000..5e94a98--- /dev/null+++ b/tests/copy-fixture.ts@@ -0,0 +1,47 @@+// A real probe: `typst query render/md.typ "<mdpos>" --field value` with+// probe=1, for the Markdown below at 98 columns of a 16 x 32 px cell (the+// default metrics: width 570.02 pt, ppi 198.0562, top 4.36 pt). Its PNG is+// 1568 x 512 px, 16 rows.+export const SMALL_MD = "## Copy test\n\nThe quick brown fox jumps over the lazy dog, then keeps running across the wide green field until the well-known path ends.\n\n- first item\n- second item\n\n```sh\necho hello world\nls -la\n```\n"++export const SMALL_PPI = 198.0562+export const SMALL_PAGE = { width: 1568, height: 512, rows: 16 }++export const SMALL_MARKS = [+ {"k": "b", "p": 1, "x": 0.0, "y": 4.36, "s": 13.2, "kind": "heading"},+ {"k": "w", "p": 1, "x": 0.0, "y": 4.36, "s": 19.8, "t": "Copy", "w": 50.12841796875, "h": 23.628515625000002},+ {"k": "w", "p": 1, "x": 55.3974609375, "y": 4.36, "s": 19.8, "t": "test", "w": 38.04345703125, "h": 23.628515625000002},+ {"k": "b", "p": 1, "x": 0.0, "y": 44.928515625, "s": 11.0, "kind": "par"},+ {"k": "w", "p": 1, "x": 0.0, "y": 44.928515625, "s": 11.0, "t": "The", "w": 19.72802734375, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 22.82177734375, "y": 44.928515625, "s": 11.0, "t": "quick", "w": 27.96728515625, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 53.8828125, "y": 44.928515625, "s": 11.0, "t": "brown", "w": 32.00634765625, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 88.98291015625, "y": 44.928515625, "s": 11.0, "t": "fox", "w": 15.7373046875, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 107.81396484375, "y": 44.928515625, "s": 11.0, "t": "jumps", "w": 31.173828125, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 142.08154296875, "y": 44.928515625, "s": 11.0, "t": "over", "w": 22.5048828125, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 167.68017578125, "y": 44.928515625, "s": 11.0, "t": "the", "w": 16.75244140625, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 187.5263671875, "y": 44.928515625, "s": 11.0, "t": "lazy", "w": 20.75390625, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 211.3740234375, "y": 44.928515625, "s": 11.0, "t": "dog,", "w": 23.224609375, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 237.6923828125, "y": 44.928515625, "s": 11.0, "t": "then", "w": 23.1708984375, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 263.95703125, "y": 44.928515625, "s": 11.0, "t": "keeps", "w": 30.744140625, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 297.794921875, "y": 44.928515625, "s": 11.0, "t": "running", "w": 39.2841796875, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 340.1728515625, "y": 44.928515625, "s": 11.0, "t": "across", "w": 34.16015625, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 377.4267578125, "y": 44.928515625, "s": 11.0, "t": "the", "w": 16.75244140625, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 397.27294921875, "y": 44.928515625, "s": 11.0, "t": "wide", "w": 24.27734375, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 424.64404296875, "y": 44.928515625, "s": 11.0, "t": "green", "w": 29.71826171875, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 457.4560546875, "y": 44.928515625, "s": 11.0, "t": "field", "w": 22.52099609375, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 483.07080078125, "y": 44.928515625, "s": 11.0, "t": "until", "w": 22.3330078125, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 508.49755859375, "y": 44.928515625, "s": 11.0, "t": "the", "w": 16.75244140625, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 528.34375, "y": 44.928515625, "s": 11.0, "t": "well-", "w": 25.3408203125, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 0.0, "y": 62.23546875, "s": 11.0, "t": "known", "w": 33.6123046875, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 36.7060546875, "y": 62.23546875, "s": 11.0, "t": "path", "w": 23.25146484375, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 63.05126953125, "y": 62.23546875, "s": 11.0, "t": "ends.", "w": 28.48291015625, "h": 13.126953125},+ {"k": "b", "p": 1, "x": 30.799999999999997, "y": 88.562421875, "s": 11.0, "kind": "item", "prefix": "- "},+ {"k": "w", "p": 1, "x": 30.799999999999997, "y": 88.562421875, "s": 11.0, "t": "first", "w": 20.47998046875, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 54.37373046875, "y": 88.562421875, "s": 11.0, "t": "item", "w": 22.48876953125, "h": 13.126953125},+ {"k": "b", "p": 1, "x": 30.799999999999997, "y": 105.869375, "s": 11.0, "kind": "item", "prefix": "- "},+ {"k": "w", "p": 1, "x": 30.799999999999997, "y": 105.869375, "s": 11.0, "t": "second", "w": 37.87158203125, "h": 13.126953125},+ {"k": "w", "p": 1, "x": 71.76533203124998, "y": 105.869375, "s": 11.0, "t": "item", "w": 22.48876953125, "h": 13.126953125},+ {"k": "b", "p": 1, "x": 0.0, "y": 132.196328125, "s": 11.0, "kind": "code"},+ {"k": "c", "p": 1, "x": 12.571428571428573, "y": 153.1251785714286, "s": 11.0, "t": "echo hello world", "w": 105.9609375, "n": 16, "a": 8.357421875, "d": 2.642578125},+ {"k": "c", "p": 1, "x": 12.571428571428573, "y": 168.05217857142858, "s": 11.0, "t": "ls -la", "w": 39.7353515625, "n": 6, "a": 8.357421875, "d": 2.642578125},+] as constdiff --git a/tests/copy.test.ts b/tests/copy.test.tsnew file mode 100644index 0000000..1367a67--- /dev/null+++ b/tests/copy.test.ts@@ -0,0 +1,256 @@+import { expect, mock, test } from 'claude-code/testing'++import {+ codePointsOf, decodeSelection, DIACRITICS, hasPlaceholders, joinSegments, parseCommand, pickPages, placeholderCell, positionsOf, textOfRun,+ type Drawn, type TextBlock, type Item, type Mark,+} from '../hooks/register'+import { SMALL_MARKS, SMALL_MD, SMALL_PAGE, SMALL_PPI } from './copy-fixture'++// One screen row of a picture as Claude Code draws it: `lead` (the gutter),+// then the cells of `row` from `from` to `to`.+const cells = (row: number, from: number, to: number, lead = ' ') =>+ lead + Array.from({ length: to - from + 1 }, (_, i) => placeholderCell(row, from + i)).join('')++// ---- The diacritics ---------------------------------------------------------++test("the row/column marks are kitty's 297, in its order", () => {+ expect(DIACRITICS.length).toBe(297)+ expect(new Set(DIACRITICS).size).toBe(297)+ expect(DIACRITICS.slice(0, 18)).toEqual([0x0305, 0x030d, 0x030e, 0x0310, 0x0312, 0x033d, 0x033e, 0x033f, 0x0346, 0x034a, 0x034b, 0x034c, 0x0350, 0x0351, 0x0352, 0x0357, 0x035b, 0x0363])+ expect(DIACRITICS.slice(0, 19)).toEqual([773, 781, 782, 784, 786, 829, 830, 831, 838, 842, 843, 844, 848, 849, 850, 855, 859, 867, 868])+ expect(DIACRITICS[296]).toBe(0x1d244)+ expect(placeholderCell(2, 5)).toBe('\u{10EEEE}̎̽')+ expect(hasPlaceholders(`a${placeholderCell(0, 0)}`)).toBe(true)+ expect(hasPlaceholders('plain text')).toBe(false)+})++// ---- Decoding a clipboard ---------------------------------------------------++test('a selection over one picture is one run; the gutter and its bullet are dropped', () => {+ const text = [cells(3, 10, 20, '⏺ '), cells(4, 0, 40), cells(5, 0, 7)].join('\n')+ expect(decodeSelection(text)).toEqual([+ { kind: 'image', lines: [{ row: 3, colStart: 10, colEnd: 20 }, { row: 4, colStart: 0, colEnd: 40 }, { row: 5, colStart: 0, colEnd: 7 }] },+ ])+})++test('text between pictures stays, in order; a row that starts again starts a new run', () => {+ const text = ['> my prompt', '', cells(0, 0, 3), cells(1, 0, 3), cells(0, 0, 2), 'after', ''].join('\n')+ expect(decodeSelection(text)).toEqual([+ { kind: 'text', text: '> my prompt\n' },+ { kind: 'image', lines: [{ row: 0, colStart: 0, colEnd: 3 }, { row: 1, colStart: 0, colEnd: 3 }] },+ { kind: 'image', lines: [{ row: 0, colStart: 0, colEnd: 2 }] },+ { kind: 'text', text: 'after' },+ ])+})++test('a cell with no column mark is the one after the cell before it', () => {+ const bare = '\u{10EEEE}' + String.fromCodePoint(DIACRITICS[6]!)+ expect(decodeSelection(placeholderCell(6, 9) + bare + bare)).toEqual([{ kind: 'image', lines: [{ row: 6, colStart: 9, colEnd: 11 }] }])+})++test('dump shows cells as [row,col] and other characters as code points', () => {+ expect(codePointsOf(`⏺ ${placeholderCell(1, 2)}x`)).toBe('U+23FA U+0020 U+10EEEE[1,2] U+0078')+ expect(codePointsOf(cells(0, 0, 50, ''), 3).split(' ').length).toBe(3)+})++// ---- Positions --------------------------------------------------------------++test('probe marks become pixel boxes; a list number is dropped and an item takes its paragraph', () => {+ const marks: Mark[] = [+ { k: 'b', p: 1, x: 0, y: 0, kind: 'par' },+ { k: 'w', p: 1, x: 0, y: 0, t: 'Hi', w: 10, h: 12 },+ { k: 'w', p: 1, x: 20, y: 30, t: '1.', w: 6, h: 12 },+ { k: 'b', p: 1, x: 30, y: 30, kind: 'item', prefix: '1. ' },+ { k: 'b', p: 1, x: 30, y: 30, kind: 'par' },+ { k: 'w', p: 2, x: 30, y: 30, t: 'one', w: 15, h: 12 },+ { k: 'c', p: 2, x: 10, y: 60, t: 'ab', w: 12, n: 2, a: 8, d: 2 },+ ]+ const got = positionsOf(marks, 144)+ expect(got.blocks).toEqual([{ kind: 'par', prefix: '', first: 0 }, { kind: 'item', prefix: '1. ', first: 1 }])+ expect(got.pages[0]).toEqual([{ i: 0, text: 'Hi', block: 0, x0: 0, x1: 20, y0: 0, y1: 24 }])+ expect(got.pages[1]).toEqual([+ { i: 1, text: 'one', block: 1, x0: 60, x1: 90, y0: 60, y1: 84 },+ { i: 2, text: 'ab', block: 1, x0: 20, x1: 44, y0: 104, y1: 124, adv: 12 },+ ])+})++// A hand-made page: 10 columns of 10 px, 4 rows of 20 px.+const PAGE = { width: 100, height: 80, rows: 4 }+const word = (i: number, text: string, x0: number, row: number, block: number): Item => ({ i, text, x0, x1: x0 + text.length * 6, y0: row * 20 + 2, y1: row * 20 + 18, block })+const BLOCKS: TextBlock[] = [+ { kind: 'par', prefix: '', first: 0 },+ { kind: 'item', prefix: '- ', first: 4 },+ { kind: 'code', prefix: '', first: 5 },+ { kind: 'cell', prefix: '', cx: 0, first: 7 },+ { kind: 'cell', prefix: '', cx: 1, first: 8 },+]+const ITEMS: Item[] = [+ word(0, 'alpha', 0, 0, 0), word(1, 'beta', 40, 0, 0), word(2, 'well-', 70, 0, 0), word(3, 'known', 0, 1, 0),+ word(4, 'item', 40, 1, 1),+ { i: 5, text: 'let x = 1', x0: 0, x1: 90, y0: 42, y1: 58, block: 2, adv: 10 },+ { i: 6, text: 'x++', x0: 0, x1: 30, y0: 52, y1: 58, block: 2, adv: 10 },+ word(7, 'k', 0, 3, 3), word(8, 'v', 50, 3, 4),+]++test('a word is in when its centre is in a selected cell; the first line from its column, the last to its column', () => {+ // "beta" spans x 40-64: centre 52, column 5.+ expect(textOfRun([{ row: 0, colStart: 5, colEnd: 9 }], ITEMS, BLOCKS, PAGE, 10)).toBe('beta well-')+ expect(textOfRun([{ row: 0, colStart: 6, colEnd: 9 }], ITEMS, BLOCKS, PAGE, 10)).toBe('well-')+ // A line broken after a hyphen joins with no space; a new block is a new line with its prefix.+ expect(textOfRun([{ row: 0, colStart: 0, colEnd: 9 }, { row: 1, colStart: 0, colEnd: 9 }], ITEMS, BLOCKS, PAGE, 10)).toBe('alpha beta well-known\n- item')+})++test('code lines are cut by characters; table cells join with a tab', () => {+ expect(textOfRun([{ row: 2, colStart: 4, colEnd: 9 }], ITEMS, BLOCKS, PAGE, 10)).toBe('x = 1')+ expect(textOfRun([{ row: 2, colStart: 0, colEnd: 9 }, { row: 3, colStart: 0, colEnd: 9 }], ITEMS, BLOCKS, PAGE, 10)).toBe('let x = 1\nx++\nk\tv')+ // The two code lines lie in one row (y centres 50 and 55): both, one per line.+ expect(textOfRun([{ row: 2, colStart: 0, colEnd: 1 }], ITEMS, BLOCKS, PAGE, 10)).toBe('le\nx+')+})++// ---- Which page -------------------------------------------------------------++const drawn = (id: string, seq: number, rows: number[], columns = 80): Drawn => ({+ id, seq, columns, dir: `/c/${id}`, pages: rows.map((r, i) => ({ file: `/c/${id}/a-${i + 1}.png`, width: columns * 16, height: r * 32, rows: r })),+})++test('a run goes to the answer the selection names, else to the newest it fits', () => {+ const runs = decodeSelection([cells(2, 0, 50), cells(3, 0, 50)].join('\n'))+ const answers = [drawn('old', 1, [10]), drawn('new', 2, [10]), drawn('short', 3, [3])]+ expect(pickPages(runs, answers)).toEqual([{ id: 'new', page: 0 }])+ expect(pickPages(runs, answers, 'old')).toEqual([{ id: 'old', page: 0 }])+ // Too wide for an answer drawn at 40 columns.+ expect(pickPages(runs, [drawn('narrow', 9, [10], 40)])).toEqual([null])+})++test('runs one after another are consecutive pages of one answer', () => {+ const text = [cells(8, 0, 9), cells(9, 0, 9), cells(0, 0, 9), cells(1, 0, 9)].join('\n')+ const segments = decodeSelection(text)+ expect(segments.length).toBe(2)+ // Page 0 has 10 rows, so the first run ends on its last row.+ expect(pickPages(segments, [drawn('two', 1, [10, 5]), drawn('one', 2, [20])])).toEqual([{ id: 'two', page: 0 }, { id: 'two', page: 1 }])+ expect(joinSegments([{ kind: 'text', text: 'a' }, ...segments], [null, 'x', 'y'])).toBe('a\nx\ny')+})++// ---- A real probe -----------------------------------------------------------++const REAL = positionsOf(SMALL_MARKS as unknown as Mark[], SMALL_PPI)+const ALL_COLUMNS = (row: number) => ({ row, colStart: 0, colEnd: 97 })++test("a real probe: the whole picture copies as the answer's text", () => {+ const all = Array.from({ length: SMALL_PAGE.rows }, (_, row) => ALL_COLUMNS(row))+ expect(textOfRun(all, REAL.pages[0]!, REAL.blocks, SMALL_PAGE, 98)).toBe(+ 'Copy test\nThe quick brown fox jumps over the lazy dog, then keeps running across the wide green field until the well-known path ends.\n- first item\n- second item\necho hello world\nls -la',+ )+})++test('a real probe: a selection from mid-paragraph into the code block', () => {+ // Rows: heading 1, paragraph 4 and 5, items 8 and 9, code 12 and 14.+ const lines = [{ row: 4, colStart: 30, colEnd: 97 }, ...[5, 6, 7, 8, 9, 10, 11].map(ALL_COLUMNS), { row: 12, colStart: 0, colEnd: 14 }]+ expect(textOfRun(lines, REAL.pages[0]!, REAL.blocks, SMALL_PAGE, 98)).toBe(+ 'the lazy dog, then keeps running across the wide green field until the well-known path ends.\n- first item\n- second item\necho hello ',+ )+ // Part of the second item: no prefix.+ expect(textOfRun([{ row: 9, colStart: 10, colEnd: 97 }], REAL.pages[0]!, REAL.blocks, SMALL_PAGE, 98)).toBe('item')+})++test('a real probe through the clipboard: decode, pick, read', () => {+ // "jumps" is columns 18-23, its centre in column 21.+ const clipboard = [cells(1, 0, 97, '⏺ '), '', cells(4, 0, 21)].join('\n')+ const segments = decodeSelection(clipboard)+ const answer = { id: 'r1', seq: 1, columns: 98, dir: '/c/k', pages: [{ file: '/c/k/a-1.png', ...SMALL_PAGE }] }+ const picks = pickPages(segments, [answer])+ expect(picks).toEqual([{ id: 'r1', page: 0 }, null, { id: 'r1', page: 0 }])+ const texts = segments.map((s, i) => (s.kind === 'image' && picks[i] ? textOfRun(s.lines, REAL.pages[0]!, REAL.blocks, SMALL_PAGE, 98) : null))+ expect(joinSegments(segments, texts)).toBe('Copy test\n\nThe quick brown fox jumps')+})++// ---- The command ------------------------------------------------------------++test('/md-preview grab and dump are commands; dump with nothing seen says so', async $ => {+ expect(parseCommand('grab')).toEqual({ kind: 'grab' })+ expect(parseCommand('dump')).toEqual({ kind: 'dump' })+ const ran = await $.command.run({ command: 'md-preview', args: 'dump' } as any)+ expect(ran.text).toContain('no clipboard text with picture cells seen yet')+})++// ---- The clipboard watcher --------------------------------------------------++const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } })+// The first 24 bytes of a 1568 x 512 PNG (the fixture's page), as `od` prints them.+const HEAD = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 06 20 00 00 02 00'++test('a mouse copy of a drawn answer is read from the clipboard and written back as text, once', async ($, on) => {+ mock.store(on)+ const clock = mock.clock(on)+ mock.env(on, { HOME: '/h', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' })+ const files = new Map<string, string>()+ let clipboard = 'nothing yet'+ let pastes = 0+ const copies: string[] = []+ const toasts: string[] = []+ on('process.run', async ($: any, e: any) => {+ const argv: string[] = e.argv+ const cmd = argv.join(' ')+ if (/md-preview-/.test(cmd)) return ok('/c\nDarwin\n')+ if (cmd.includes('command -v typst')) return ok('/usr/bin/typst\n')+ if (argv[0] === '/usr/bin/typst' && argv[1] === 'eval') return ok('{}')+ if (argv[0] === '/usr/bin/typst' && argv[1] === 'compile') return ok('')+ if (argv[0] === '/usr/bin/typst' && argv[1] === 'query') {+ expect(argv).toContain('probe=1')+ expect(argv.slice(-3)).toEqual(['<mdpos>', '--field', 'value'])+ return ok(JSON.stringify(SMALL_MARKS))+ }+ if (cmd.includes('od -An')) return ok(`${HEAD}\n@\n`)+ if (argv[0] === 'pbpaste') {+ pastes+++ return ok(clipboard)+ }+ return ok('', 1)+ })+ on('fs.write', async ($: any, e: any) => {+ files.set(e.path, e.text)+ return { value: undefined }+ })+ on('fs.read', async ($: any, e: any, next: any) => (files.has(e.path) ? { value: files.get(e.path) } : e.path.startsWith('/c/') ? { deny: 'ENOENT' } : next(e)))+ on('fs.list', async ($: any, e: any, next: any) => (e.path.startsWith('/c/') ? { value: [{ name: 'a-1.png', kind: 'file', size: 1, mtimeMs: 1, isLink: false }] } : next(e)))+ on('ui.copy', async ($: any, e: any) => {+ copies.push(e.text)+ clipboard = e.text+ return { value: { isCopied: true } }+ })+ on('ui.selection', async () => ({ value: undefined }))+ on('ui.toast', async ($: any, e: any) => {+ toasts.push(String(e.text ?? e.message ?? JSON.stringify(e)))+ return { value: undefined }+ })+ on('ui.render', () => ({ type: 'Text', props: {}, children: ['engine drawing'] }) as any)+ await $.command.run({ command: 'md-preview', args: '' } as any)+ const props = { text: SMALL_MD, isFirstOfReply: true }+ const ui = await $.ui.mount({ plugin: 'md-preview', surface: 'terminal', component: 'AssistantMessage', requestId: 'ans-1', props, viewport: { columns: 100, rows: 40 } } as any)+ await clock.settle()+ await ui.redraw(props as any)+ await clock.settle()+ // The probe ran after the PNGs, by itself.+ expect([...files.keys()].some(k => k.endsWith('/positions.json'))).toBe(true)+ expect([...files.keys()].some(k => k.endsWith('/probe.json'))).toBe(true)++ // A clipboard with no placeholders is never written.+ await clock.advance(300)+ expect(pastes).toBeGreaterThan(0)+ expect(copies).toEqual([])++ // The heading row and the start of the paragraph, as a mouse copy takes them.+ clipboard = [cells(1, 0, 97, '⏺ '), cells(2, 0, 97), cells(3, 0, 97), cells(4, 0, 21)].join('\n')+ await clock.advance(300)+ await clock.settle()+ expect(copies).toEqual(['Copy test\nThe quick brown fox jumps'])+ expect(toasts).toContain('md-preview: copied 35 chars of text')+ // Our own write is not read again.+ await clock.advance(900)+ expect(copies.length).toBe(1)++ const dumped = await $.command.run({ command: 'md-preview', args: 'dump' } as any)+ expect(dumped.text).toContain('U+10EEEE[1,0]')+ expect(dumped.text).toContain('-> answer ans-1 page 0')+ expect(files.has('/c/copy-debug.json')).toBe(true)+})