Skip to content

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

Code blocks: fit width, language label and a copy button; a click on it copies the code

razorback1625769c60d2ae
diff --git a/docs/development.md b/docs/development.md
index fada61d..56048d5 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -13,6 +13,7 @@ claude plugin test . # tests
sh tests/cache-sh-test.sh # the cache folder sweep (CACHE_SH) in sh, dash and bash --posix
sh tests/fonts-sh-test.sh # the copy of a font out of a terminal's program (PROGRAM_FONTS_SH and _PL) with perl
sh tests/bold-sh-test.sh # the fake bold of md.typ (term-bold=0) with the real Typst and Monaco (skips with no Monaco)
+sh tests/code-sh-test.sh # code blocks of md.typ (width, header, copy button mark, row grid) with the real Typst (skips with no typst)
claude plugin validate .
```
@@ -30,7 +31,7 @@ Picture select writes trace lines that start with `select:`:
- `select: words <id> page <n> <k> words in <ms> (background)`: the background probe of a page's words (`none` when it found no words).
- `select: copy <n> chars <ms>ms after the up (text <ms>ms, words cached | words probed for page <n>); native selection seen (...) | no native selection`: the copy at `up`, and whether Claude Code has a selection of its own with picture cells.
- `select: native copy seen: ...`: picture cells on the clipboard, or a `$.ui.copy` with picture cells.
-- `select: hover <id> page <n> target <i> (<kind>) rows <row>:<x0>-<x1>,...` (or `select: hover none`): the target under the pointer changed (`web`, `file` or `command`, and its cells).
+- `select: hover <id> page <n> target <i> (<kind>) rows <row>:<x0>-<x1>,...` (or `select: hover none`): the target under the pointer changed (`web`, `file`, `command` or `code`, and its cells; `code` is the copy button of a code block).
- `select: click <id> page <n> at <x>,<y> target <kind>|none`: one line for each click (a `clear`), with the target that it copies.
## Module layout
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index f111899..617ffda 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -30,7 +30,7 @@ The selection of Claude Code copies picture cells as kitty placeholder character
4. The hooks runtime has no zlib, so `hooks/lib/png.ts` decodes the page in JavaScript (inflate and unfilter). For each row of cells, the mod makes a deflate piece one time (fixed Huffman codes, matches of one pixel to the left or one pixel up, ended on a byte). A row that is selected whole has a tinted piece, also made one time (in the background, or by a frame: 6 ms of them at most per frame; a row that is not made yet shows plain in that frame, and the next frame continues). A frame makes new pieces only for the first and last selected rows (partly selected), and joins the pieces into one PNG (up to approximately 3 MB for a tall page). The first highlight frame of a ready page takes approximately 2–3 ms to make. The hooks can write only text, so `perl` writes the frame (base64 on its stdin) to `<cache>/select-<id>/f-<n>.png`. The terminal reads the file after the blit. The mod deletes a frame file when 4 newer frames are written and it is 2 s old. The 2-day cleanup of the cache folder deletes the rest.
5. A new frame starts at most once in 16 ms, and only after the last one is blitted. The posts between fold into one frame of the newest selection. If Claude Code refuses a blit, the mod writes the reason one time to the debug log and shows no highlight on that page until the next `down`. The copy still works.
6. At `up`, the mod reads the words under the selected cells the same way as for a copy of these cells (`textOfRun` on the words of the probe), and copies them with `$.ui.copy`. A toast shows "copied N chars of text".
-7. Links, file paths and commands (the click targets, `hooks/lib/targets.ts`): the probe also tags the words of a Markdown link (its URL), and the words of inline code (its text). When the words of a page are known, the mod finds its targets (web links, bare URLs, file paths that exist, and inline code, which is a command when it is not a file that exists; a code block is not a target) and the cells of each, one time for each page and size. With no button down, the `Client` posts `hover` when the pointer goes to a new cell and `leave` when it goes out. The mod then shows the target under the pointer with the same blits as a selection (step 3), and the page's own PNG when the pointer is off the targets. There is no hover highlight while a selection shows, and a `down` removes it. A `clear` (a click) on a target copies it with `$.ui.copy` (a web link's URL, a file's full path, the text of inline code). A later post of one frame replaces an earlier one, so a `hover` or a `leave` also carries the last `up` or `clear` of its `Client`, and the mod reads that one first (by its order, one time).
+7. Links, file paths, commands and copy buttons (the click targets, `hooks/lib/targets.ts`): the probe also tags the words of a Markdown link (its URL), and the words of inline code (its text). For each code block, it also gives the box of the copy button in the block's header, with the full code and the language (a tag that is not a word, so the copy of a selection does not change). When the words of a page are known, the mod finds its targets (web links, bare URLs, file paths that exist, inline code, which is a command when it is not a file that exists, and the copy button of each code block; the text of a code block is not a target) and the cells of each, one time for each page and size. The cells of a copy button are the cells whose centres are in its box (at least the cell of its centre). An older probe gives no copy buttons, and then a code block has no target. With no button down, the `Client` posts `hover` when the pointer goes to a new cell and `leave` when it goes out. The mod then shows the target under the pointer with the same blits as a selection (step 3), and the page's own PNG when the pointer is off the targets. There is no hover highlight while a selection shows, and a `down` removes it. A `clear` (a click) on a target copies it with `$.ui.copy` (a web link's URL, a file's full path, the text of inline code, the full code of a code block). A later post of one frame replaces an earlier one, so a `hover` or a `leave` also carries the last `up` or `clear` of its `Client`, and the mod reads that one first (by its order, one time).
The `Client` is in the flow, not in an absolute `Box`. Claude Code (2.1.306) moves an absolute `Box` whose top is above the screen down to row 0, with its children. Then the pointer `y` of a `Client` in such a `Box` counts from row 0 of the screen, not from the top of the page, so the selection was too high by the rows that were scrolled away. Also, the `Client` took the pointer under the page. A `Box` in the flow has its true position, also when its top is above the screen.
diff --git a/docs/usage.md b/docs/usage.md
index 7b5c8e3..3932041 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -106,13 +106,13 @@ A selection can go on into the next page of the same answer.
#### Click a link, a file or a command
-With picture select, the web links, file paths and commands in a picture are live. The dim link rows do not show under the picture.
+With picture select, the web links, file paths, commands and the copy buttons of code blocks in a picture are live. The dim link rows do not show under the picture.
-- Move the pointer over a link, a file path or a command (no button). Its cells show on the blue background. Move the pointer off it, and the background goes. While a selection shows, there is no such highlight.
-- Click it (push and release the button on the same cell). The mod copies it and shows a toast: a web link copies its URL ("copied the link"), a file path copies its full path ("copied the path"), and a command copies the full command ("copied the command").
+- Move the pointer over a link, a file path, a command or a copy button (no button). Its cells show on the blue background. Move the pointer off it, and the background goes. While a selection shows, there is no such highlight.
+- Click it (push and release the button on the same cell). The mod copies it and shows a toast: a web link copies its URL ("copied the link"), a file path copies its full path ("copied the path"), a command copies the full command ("copied the command"), and the copy button of a code block (at the top right of the block) copies all the code of the block ("copied the code").
- A drag that starts on a link, a file path or a command selects text, as on other text.
-A web link is a Markdown link to an `http:`, `https:` or `mailto:` URL, or a URL in the text. A file path is in the text or in inline code, and the file must exist (a relative path starts from the session's folder). A command is any inline code that is not a file that exists, for example `` `git status` `` (a click copies its text; for `` `! cmd` `` it copies only `cmd`). A code block is not a target (to copy it, select its text). A link to a heading in the same text is not a link for this.
+A web link is a Markdown link to an `http:`, `https:` or `mailto:` URL, or a URL in the text. A file path is in the text or in inline code, and the file must exist (a relative path starts from the session's folder). A command is any inline code that is not a file that exists, for example `` `git status` `` (a click copies its text; for `` `! cmd` `` it copies only `cmd`). The text of a code block is not a target: to copy all of it, click its copy button, or select its text. A link to a heading in the same text is not a link for this.
When a page is drawn or comes on the screen, the mod gets the page ready for the highlight in the background. It also finds the position of each word on the page. Thus the first highlight and the copy are fast. If you push the button on a page that is not ready, the mod gets that page ready first, and the first highlight shows a short time later. If the words of the page are not ready when you release the button, the copy waits for them: approximately 0.05 s for plain text (only ASCII characters, no math, no Typst block and no image), 0.15–0.5 s for other text, and more (2–3 s) for a page with a large Typst drawing. No toast shows while the mod does this. Only the toast of the copy shows. The mod keeps the positions in memory, so the next copy from the same page is fast.
diff --git a/hooks/lib/copy.ts b/hooks/lib/copy.ts
index 8f71c37..9d6b94e 100644
--- a/hooks/lib/copy.ts
+++ b/hooks/lib/copy.ts
@@ -6,7 +6,8 @@
// 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
+// marks (render/md.typ, `<mdpos>`) into word boxes (and the boxes of code
+// blocks' copy buttons) in PNG pixels; pickPages
// says which drawn page each run is; textOfRun reads the words under a run.
// The drawn pages and the probe of a page are in probe.ts; the clipboard
// watcher (its change counts) and the commands are in register.tsx.
@@ -115,8 +116,10 @@ export function decodeSelection(text: string): Segment[] {
// ---- Where the words are ---------------------------------------------------
// A probe mark as `typst query <mdpos> --field value` gives it (pt).
+// `t`: a tag that is no word (kind `copy`: a code block's copy button, its
+// box, the whole `code` and its `lang`).
export type Mark = {
- k: 'w' | 'c' | 'b'
+ k: 'w' | 'c' | 'b' | 't'
p: number
x: number
y: number
@@ -134,6 +137,7 @@ export type Mark = {
pad?: number
href?: string
code?: string
+ lang?: string
}
// 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`).
@@ -149,8 +153,11 @@ export type Item = {
// (`prefix`, and `mx` the x of its marker's centre in pixels, on its first
// word's line); `first` its first item.
export type TextBlock = { kind: string; prefix: string; cx?: number; mx?: number; first: number }
-// A probe's words by page (0-based: PNG page N+1), and its blocks.
-export type Positions = { ppi: number; blocks: TextBlock[]; pages: Item[][] }
+// A code block's copy button in PNG pixels: its box, its code and language.
+export type Button = { x0: number; y0: number; x1: number; y1: number; code: string; lang?: string }
+// A probe's words by page (0-based: PNG page N+1), its blocks, and its
+// copy buttons by page.
+export type Positions = { ppi: number; blocks: TextBlock[]; pages: Item[][]; buttons: Button[][] }
const round = (n: number) => Math.round(n * 100) / 100
// The break chances the template adds (a zws in a long word), the strut
@@ -167,7 +174,7 @@ function isMarker(marks: readonly Mark[], j: number): boolean {
const next = marks[j + 1]
if (m.k !== 'w' || next?.k !== 'b' || next.kind !== 'item') return false
if (next.prefix?.trim().split(' ')[0] === m.t) return true
- const body = marks.slice(j + 2).find(x => x.k !== 'b')
+ const body = marks.slice(j + 2).find(x => x.k !== 'b' && x.k !== 't')
return !!body && body.p === m.p && body.x > m.x && Math.abs(body.y - m.y) < (m.h ?? m.s ?? 11) / 2
}
@@ -176,14 +183,26 @@ function isMarker(marks: readonly Mark[], j: number): boolean {
// checkbox drawn as a shape: 0.8 of the text size left of the item). A block mark with no word since the last one
// (an item, then its paragraph) adds to that block. A word of only
// invisible characters is dropped. A link's URL and an inline code's text go
-// to its words.
+// to its words. A copy tag is a button, not a word (no block, no text); its
+// code less one line break at its end (a paste does not run it at once).
export function positionsOf(marks: readonly Mark[], ppi: number): Positions {
const k = ppi / 72
const blocks: TextBlock[] = []
const pages: Item[][] = []
+ const buttons: Button[][] = []
let hasItems = false
let count = 0
marks.forEach((m, j) => {
+ if (m.k === 't') {
+ if (m.kind !== 'copy' || typeof m.code !== 'string') return
+ const page = Math.max(0, m.p - 1)
+ while (buttons.length <= page) buttons.push([])
+ buttons[page]!.push({
+ x0: round(m.x * k), y0: round(m.y * k), x1: round((m.x + (m.w ?? 0)) * k), y1: round((m.y + (m.h ?? 0)) * k), code: m.code.replace(/\r?\n$/, ''),
+ ...(m.lang ? { lang: m.lang } : {}),
+ })
+ return
+ }
if (m.k === 'b') {
const cur = blocks[blocks.length - 1]
const before = marks[j - 1]
@@ -225,7 +244,7 @@ export function positionsOf(marks: readonly Mark[], ppi: number): Positions {
while (pages.length <= page) pages.push([])
pages[page]!.push(item)
})
- return { ppi, blocks, pages }
+ return { ppi, blocks, pages, buttons }
}
// ---- Which page a run is ---------------------------------------------------
diff --git a/hooks/lib/probe.ts b/hooks/lib/probe.ts
index ecc03d7..cda4824 100644
--- a/hooks/lib/probe.ts
+++ b/hooks/lib/probe.ts
@@ -10,7 +10,7 @@ import { PROBED_KEPT } from './settings'
import { clip, DRAWN_KEPT, drawnAnswers, keep, lastKey, results, type Job, type Result } from './state'
import { fitBox } from './terminal'
import { isSafePage, probePage } from './typst'
-import { screenOf, type Drawn, type DrawnPage, type Item, type TextBlock } from './copy'
+import { screenOf, type Button, type Drawn, type DrawnPage, type Item, type TextBlock } from './copy'
import { targetsOf, type PageTarget } from './targets'
import type { ShownLink } from './draw'
@@ -55,8 +55,8 @@ export function noteOnScreen(id: string, onScreen: unknown) {
// ---- Positions ----------------------------------------------------------------
-// The words of one page and the blocks they are in.
-export type PageWords = { items: Item[]; blocks: TextBlock[] }
+// The words of one page, the blocks they are in, and its code blocks' copy buttons.
+export type PageWords = { items: Item[]; blocks: TextBlock[]; buttons?: Button[] }
// The pages probed, by `<folder>#<page>` (the PROBED_KEPT read last), and
// the probes that run now (a copy of the same page waits for the same run).
@@ -83,7 +83,7 @@ export async function wordsOf($: EngineInterface, d: Drawn & { job?: Job }, page
const drawn = d.pages[page]
if (!d.job || !drawn) return null
const run = probePage($, d.job, d.dir, { page, pages: d.pages.length, isSafe: isSafePage(drawn.file) })
- .then(got => (got ? { items: got.pages[page] ?? [], blocks: got.blocks } : null))
+ .then(got => (got ? { items: got.pages[page] ?? [], blocks: got.blocks, buttons: got.buttons[page] ?? [] } : null))
.catch(() => null)
inflight.set(key, run)
const got = await run
diff --git a/hooks/lib/targets.ts b/hooks/lib/targets.ts
index 99aa04d..1589207 100644
--- a/hooks/lib/targets.ts
+++ b/hooks/lib/targets.ts
@@ -1,15 +1,17 @@
-// Click targets (pure): the web links, files and commands drawn on a page of
-// a picture, and the cells each takes, from the page's probed words (copy.ts:
-// a word's `href` and `code`) and the drawing's resolved links (only files
-// that exist, by their label). Code blocks are no targets: inline code is
-// (a command to copy).
-import { joinItems, type Item } from './copy'
+// Click targets (pure): the web links, files, commands and code blocks' copy
+// buttons drawn on a page of a picture, and the cells each takes, from the
+// page's probed words (copy.ts: a word's `href` and `code`), its buttons and
+// the drawing's resolved links (only files that exist, by their label). The
+// text of a code block is no target, only its copy button (its whole code);
+// inline code is (a command to copy).
+import { joinItems, type Button, type Item } from './copy'
import type { ShownLink } from './draw'
import { fileOf, trimUrl } from './links'
import type { PageWords } from './probe'
import type { SelRow } from './select'
-export type Target = { kind: 'web'; href: string } | { kind: 'file'; path: string } | { kind: 'command'; text: string }
+export type Target =
+ | { kind: 'web'; href: string } | { kind: 'file'; path: string } | { kind: 'command'; text: string } | { kind: 'code'; text: string; lang?: string }
// One target on one page: what it does, and its cells on that page (the cells whose centre test matches
// textOfRun's rule: a word is in a cell when its box centre is in it; a target covers, on each of its rows,
// the columns from its first word's left cell to its last word's right cell).
@@ -43,6 +45,25 @@ function rowsOf(items: readonly Item[], page: Page): SelRow[] {
return [...rows.values()].sort((a, b) => a.row - b.row)
}
+// The cells of a button's box, row by row: the cells whose centres are in
+// it (at least the one its centre is in).
+function boxRows(box: Button, page: Page): SelRow[] {
+ const colW = page.width / page.columns
+ const rowH = page.height / page.rows
+ // The first and last cells whose centres are in [a, b] (else the one of its centre), clamped to n.
+ const span = (a: number, b: number, size: number, n: number) => {
+ const mid = Math.floor((a + b) / 2 / size)
+ const lo = Math.min(mid, Math.ceil(a / size - 0.5))
+ const hi = Math.max(mid, Math.floor(b / size - 0.5))
+ return [Math.max(0, lo), Math.min(n - 1, hi)] as const
+ }
+ const [r0, r1] = span(box.y0, box.y1, rowH, page.rows)
+ const [x0, x1] = span(box.x0, box.x1, colW, page.columns)
+ const rows: SelRow[] = []
+ if (x0 <= x1) for (let row = r0; row <= r1; row++) rows.push({ row, x0, x1 })
+ return rows
+}
+
// A file's target: the ShownLink of kind file with that label (it exists).
function fileTarget(label: string, links: readonly ShownLink[]): Target | null {
const link = links.find(l => l.kind === 'file' && l.label === label)
@@ -62,7 +83,8 @@ function bareTarget(token: string, links: readonly ShownLink[]): Target | null {
// link URL are one web target (a URL only); the words of one inline code a
// file that exists, else a command (its text, less a `! ` before it); a code block none; a bare URL
// or file path one target over its words (pieces with no space between, as
-// the copy joins them).
+// the copy joins them). A copy button is a code target over its box, put
+// before the first target that starts below it (or right of it on its row).
export function targetsOf(words: PageWords, page: Page, links: readonly ShownLink[]): PageTarget[] {
const { items } = words
const out: PageTarget[] = []
@@ -95,6 +117,14 @@ export function targetsOf(words: PageWords, page: Page, links: readonly ShownLin
}
i = j
}
+ for (const button of words.buttons ?? []) {
+ const rows = boxRows(button, page)
+ if (!rows.length) continue
+ const top = rows[0]!
+ const at = out.findIndex(t => t.rows[0]!.row > top.row || (t.rows[0]!.row === top.row && t.rows[0]!.x0 > top.x0))
+ const target: Target = { kind: 'code', text: button.code, ...(button.lang ? { lang: button.lang } : {}) }
+ out.splice(at < 0 ? out.length : at, 0, { target, rows })
+ }
return out
}
diff --git a/hooks/register.tsx b/hooks/register.tsx
index 811ee3a..5db9794 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -514,7 +514,7 @@ function lightHover($: EngineInterface) {
}
// A click (a clear) on a target of the page copies its text (a link's URL,
-// a file's path, a command). The page's words are probed first when they
+// a file's path, a command, a code block's code). The page's words are probed first when they
// are not known.
async function clickAt($: EngineInterface, d: Drawn & { job?: Job }, post: SelectPost, surface: RenderSurface) {
const links = () => clickLinks.get(d.id) ?? NO_LINKS
@@ -531,7 +531,7 @@ async function clickAt($: EngineInterface, d: Drawn & { job?: Job }, post: Selec
// A target's text on the clipboard (clickAt), with its toast.
async function copyTarget($: EngineInterface, target: Target, surface: RenderSurface) {
const text = target.kind === 'web' ? target.href : target.kind === 'file' ? target.path : target.text
- const name = target.kind === 'web' ? 'link' : target.kind === 'file' ? 'path' : 'command'
+ const name = target.kind === 'web' ? 'link' : target.kind === 'file' ? 'path' : target.kind === 'code' ? 'code' : 'command'
// The clipboard change of this text is not read again.
clip.wrote = text
clip.seen = text
diff --git a/render/md.typ b/render/md.typ
index 3dfd00c..928143c 100644
--- a/render/md.typ
+++ b/render/md.typ
@@ -59,6 +59,17 @@
#let safe = inp.at("safe", default: "0") not in ("", "0", "false", "no", "off")
// One segment only (page=<n>, 1-based); 0 = all of them.
#let only = int(inp.at("page", default: "0"))
+// The probe (probe=1) and its marks: see the probe section below.
+#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 + calc.max(0, only - 1), x: at.x / 1pt, y: at.y / 1pt, s: text.size.to-absolute() / 1pt, ..extra.named()))<mdpos>]
+}
+// Block code sets this so the word rule leaves its text to the line marks;
+// math and live drawings set no-marks. The orphan cost changes nothing
+// here: a page is as tall as its text, so no paragraph breaks across pages.
+#let in-code(costs) = costs.orphan == 101%
+#let no-marks(costs) = costs.orphan == 102%
#let page-w = float(inp.at("width", default: "600")) * 1pt
// No left margin, so the text starts in the column normal replies start in.
#let margin-left = 0pt
@@ -401,36 +412,67 @@
h(pad-x)
}
// Code blocks: VS Code's `pre` (padding 16px, radius 3px, 1px border) with
-// `code { line-height: 1.357em }`. A block with no language has its own
-// colour, code-plain-fg, when the theme sets one (Typst gives unscoped code
-// the text colour, not the tmTheme's).
+// `code { line-height: 1.357em }`, only as wide as its code and header need
+// (at most the width here, where long lines wrap). A block with no language
+// has its own colour, code-plain-fg, when the theme sets one (Typst gives
+// unscoped code the text colour, not the tmTheme's).
+// The header row on top: the language as written (when the fence has one)
+// and a copy button, small and muted, with a rule under them. Its text has
+// no marks (no-marks); the probe marks the button (`t`, see the probe).
+// The copy icon: two pages, the back one seen over and right of the front.
+#let copy-icon = box(width: 0.85em, height: 0.85em, baseline: 0.12em, {
+ let line = (paint: C.muted, thickness: 0.07em, join: "round")
+ place(rect(width: 0.6em, height: 0.6em, radius: 0.12em, stroke: line), dy: 0.25em)
+ place(curve(stroke: line, curve.move((0.25em, 0.25em)), curve.line((0.25em, 0em)), curve.line((0.85em, 0em)), curve.line((0.85em, 0.6em)), curve.line((0.6em, 0.6em))))
+})
#show raw.where(block: true): it => context {
let fg = if it.lang == none { C.at("code-plain-fg", default: C.code-fg) } else { C.code-fg }
let CB = E.code-block
- if on-grid {
- // The grid: each code line exactly one row (the code is the terminal's
- // font at its size), padding of whole rows (16px is about one row), and
- // half a row more when its lines are not in the flow's phase (phase-pad).
- let g = grid-edges()
- let half = calc.even(g.rows)
- let pad = phase-pad(half)
- return {
- set text(top-edge: g.top, bottom-edge: g.bottom, costs: half-costs(half))
- set par(leading: 0pt, justify: false)
+ let pad = CB.pad-px * px
+ let line = CB.border-px * px + C.code-border
+ // The grid: each code line exactly one row (the code is the terminal's
+ // font at its size), the header one line of code, padding of whole rows
+ // (16px is about one row), and half a row more when its lines are not in
+ // the flow's phase (phase-pad).
+ let g = if on-grid { grid-edges() } else { (top: 0pt, bottom: 0pt, rows: 1) }
+ let half = calc.even(g.rows)
+ let phase = if on-grid { phase-pad(half) } else { 0pt }
+ let area = measure(text(top-edge: "ascender", bottom-edge: "descender", "x")).height
+ set text(top-edge: g.top, bottom-edge: g.bottom, costs: half-costs(half)) if on-grid
+ set par(leading: if on-grid { 0pt } else { calc.max(0pt, CB.line-height * text.size - area) }, justify: false)
+ let gap = if on-grid { row } else { 1.2em }
+ // In a live drawing (no-marks): the full width and no header, as the
+ // drawing is scaled (its button would not be where it is drawn).
+ if no-marks(text.costs) {
+ block(
+ width: 100%, fill: C.code-bg, stroke: line, radius: CB.radius-px * px, above: gap, below: gap,
+ inset: if on-grid { (x: pad, y: rows-near(pad) + phase) } else { pad }, text(fill: fg, it),
+ )
+ } else {
+ let small(body) = text(font: sans, size: 0.85em, fill: C.muted, body)
+ let lang = if it.lang != none { small(it.lang) }
+ let copy = small[#copy-icon#h(0.35em)Copy]
+ let bpad = pad / 2
+ let bw = measure(copy).width + 2 * bpad
+ let hh = if on-grid { g.rows * row } else { measure(small("X")).height + 0.6 * pad }
+ let header = block(width: 100%, height: hh, inset: (left: pad, right: pad - bpad), stroke: (bottom: line), {
+ set text(costs: (orphan: 102%))
+ if probe and in-code(text.costs) { place(top + right, box(width: bw, height: hh, mark("t", kind: "copy", w: bw / 1pt, h: hh / 1pt, code: it.text, ..if it.lang != none { (lang: it.lang) }))) }
+ grid(columns: (1fr, bw), rows: hh, align: (left + horizon, center + horizon), lang, copy)
+ })
+ let code = block(width: 100%, inset: if on-grid { (x: pad, y: rows-near(pad)) } else { pad }, text(fill: fg, it))
+ block(width: 100%, above: gap, below: gap, layout(size => {
+ // The width the code and the header need, at most the width here.
+ let need = calc.max(
+ measure(text(fill: fg, it)).width,
+ if lang == none { 0pt } else { measure(lang).width + pad } + bw - bpad,
+ ) + 2 * pad
block(
- width: 100%, fill: C.code-bg, stroke: CB.border-px * px + C.code-border,
- radius: CB.radius-px * px, inset: (x: CB.pad-px * px, y: rows-near(CB.pad-px * px) + pad), above: row, below: row,
- text(fill: fg, it),
+ width: calc.min(need, size.width), fill: C.code-bg, stroke: line,
+ radius: CB.radius-px * px, inset: (y: phase), stack(header, code),
)
- }
+ }))
}
- let area = measure(text(top-edge: "ascender", bottom-edge: "descender", "x")).height
- set par(leading: calc.max(0pt, CB.line-height * text.size - area), justify: false)
- block(
- width: 100%, fill: C.code-bg, stroke: CB.border-px * px + C.code-border,
- radius: CB.radius-px * px, inset: CB.pad-px * px, above: 1.2em, below: 1.2em,
- text(fill: fg, it),
- )
}
// ---------- block quotes ----------
@@ -530,6 +572,10 @@
// 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] ").
+// t: a click target: kind "copy", the copy button of a code block (after
+// its `b`, before its lines), boxed; x, y the top-left of its box, w
+// and h its size, `code` the block's whole text, `lang` its language
+// (when the fence has one).
// Math and live ```typst drawings have no marks (a drawing is scaled, so
// its marks would not be where it is drawn).
// With page=<n>, only that segment is laid out, as in the whole document
@@ -539,16 +585,6 @@
// `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 + calc.max(0, only - 1), x: at.x / 1pt, y: at.y / 1pt, s: text.size.to-absolute() / 1pt, ..extra.named()))<mdpos>]
-}
-// Block code sets this so the word rule leaves its text to the line marks;
-// math and live drawings set no-marks. The orphan cost changes nothing
-// here: a page is as tall as its text, so no paragraph breaks across pages.
-#let in-code(costs) = costs.orphan == 101%
-#let no-marks(costs) = costs.orphan == 102%
// Inline code sets this so its words carry the theme's padding beside it
// (`pad`: a copy takes it off the gap to the text next to it).
#let in-inline-code(costs) = costs.orphan == 104%
@@ -592,7 +628,7 @@
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 => {
+ show raw.where(block: true): it => context if no-marks(text.costs) { it } else {
mark("b", kind: "code")
set text(costs: (orphan: 101%))
it
@@ -933,7 +969,8 @@
let drawing = {
show colbreak: none
// The probe: no marks (see no-marks). The grid: no half-row phase.
- set text(costs: (orphan: 102%)) if probe or on-grid
+ // Code blocks: no header (see the code section).
+ set text(costs: (orphan: 102%))
// Off-grid text rules, so multi-line labels do not overlap.
set text(top-edge: "ascender", bottom-edge: "descender") if on-grid
set par(leading: E.text.leading-em * 1em, spacing: E.text.paragraph-em * 1em) if on-grid
diff --git a/render/themes/README.md b/render/themes/README.md
index 95a5ec4..9957860 100644
--- a/render/themes/README.md
+++ b/render/themes/README.md
@@ -56,7 +56,7 @@ Example: pink inline code, rounder boxes.
| `inline-code.size` | `1.0` | Code size (VS Code: same as body) |
| `inline-code.pad-x-px`, `pad-y-px`, `radius-px` | `3`, `1`, `4` | VS Code: `padding: 1px 3px; border-radius: 4px` |
| `code-block.size`, `line-height` | `1.0`, `1.357` | |
-| `code-block.pad-px`, `radius-px`, `border-px` | `16`, `3`, `1` | |
+| `code-block.pad-px`, `radius-px`, `border-px` | `16`, `3`, `1` | A code block is only as wide as its code needs (at most the width of the page). Its header row shows the language and a copy button in `muted`, with a rule in `code-border` under them. |
| `quote.bar-px`, `radius-px`, `pad-left-px`, `pad-right-px`, `pad-y-em` | `5`, `2`, `10`, `16`, `0.55` | |
| `table.style` | `"rules"` | `"rules"`: VS Code's preview (a rule under the header and between the rows). `"grid"`: Claude Code's own tables (a box and a rule between all rows and columns, all in `th-border`). Another value draws as `"rules"`. Each column, its header too, has the alignment of the Markdown (`:---` left, `:---:` centre, `---:` right, `---` left). |
| `table.pad-x-px`, `pad-y-px`, `border-px`, `header-weight` | `10`, `5`, `1`, `700` | |
@@ -65,6 +65,7 @@ Example: pink inline code, rounder boxes.
With `/iui grid on`, the lines of text lie on the terminal's rows. Then some keys change their effect:
- `text.leading-em`, `text.paragraph-em`, `heading.leading-em`, `heading.rule-pad-em`, `list.item-spacing-em` and `code-block.line-height` are not used. Each line is one row (a large heading is two or more rows; a line of an even number of rows is half a row down, with half a row more above and below its block). The gap between paragraphs and blocks is one row. The items of a tight list have no gap. The items of a loose list (a list with a blank line between its items or in an item) have a gap of one row.
+- The header row of a code block has the rows of one line of code.
- `heading.above-em` and `below-em`, `rule.gap-em`, `code-block.pad-px`, `quote.pad-y-em` and `table.pad-y-px` are rounded to the nearest whole number of rows. Gaps above and below headings and rules are one row or more.
- With `table.style` `"grid"`, `table.pad-y-px` is rounded to the nearest whole number of rows and a half (half a row or more), and the table has half a row more above and below its box. Each rule is then in the middle of a row.
diff --git a/tests/code-sh-test.sh b/tests/code-sh-test.sh
new file mode 100644
index 0000000..b609714
--- /dev/null
+++ b/tests/code-sh-test.sh
@@ -0,0 +1,92 @@
+#!/bin/sh
+# Renders code blocks with render/md.typ and the real Typst, and reads the
+# probe's marks: a block is only as wide as its code and header need (at
+# most the page), the header has the language and a copy button, the probe
+# marks the button (`t`, kind copy, with the code and the language), the
+# header text has no word or line marks, and on the row grid the header is
+# whole rows and the code lines stay on their rows. It keeps the PNGs in
+# $IUI_CODE_OUT when that is set, to look at.
+# Usage: sh tests/code-sh-test.sh (exit 0 when all pass; skips with no typst)
+set -u
+here=$(cd "$(dirname "$0")/.." && pwd)
+tmp=$(mktemp -d "${TMPDIR:-/tmp}/iui-code-test.XXXXXX")
+trap 'rm -rf "$tmp"' EXIT
+pass=0
+fail=0
+ok() { pass=$((pass + 1)); }
+bad() { fail=$((fail + 1)); echo "FAIL: $*"; }
+
+command -v typst >/dev/null 2>&1 || { echo "code-sh-test: skipped (no typst)"; exit 0; }
+
+# A doc JSON of one page of Markdown (stdin) at $tmp/<name>.json.
+doc() { perl -e 'local $/; my $m = <STDIN>; $m =~ s/(["\\])/\\$1/g; $m =~ s/\n/\\n/g; print "{\"base\": \"\", \"segments\": [\"$m\"]}"' > "$tmp/$1.json"; }
+# The inputs of doc $1 in theme $2 (dark), with grid row $3 (0: no grid).
+inputs() {
+ echo "--input theme=dark --input width=420 --input top=4 --input code=0.9 --input theme-dir=$here/render/themes/$2 --input doc=$tmp/$1.json"
+ [ "$3" = 0 ] || echo "--input row=$3 --input grid=1"
+}
+# The probe's marks of doc $1 (theme $2, row $3) at $tmp/$1-$2-$3.marks.
+probe() {
+ # shellcheck disable=SC2046
+ typst query --root / --package-path "$here/render/packages" $(inputs "$1" "$2" "$3") --input probe=1 "$here/render/md.typ" '<mdpos>' --field value \
+ > "$tmp/$1-$2-$3.marks" 2> "$tmp/err" && ok || bad "probe of $1 ($2, row $3): $(grep -A3 '^error' "$tmp/err" | head -4)"
+}
+# A check of the marks file $1 by the perl expression $2 (the marks are in
+# @m, the code blocks' `t` marks in @t, the `c` marks in @c, the `w` marks
+# in @w); it prints what is wrong, nothing when all is right.
+check() {
+ perl -MJSON::PP -e 'local $/; my @m = @{decode_json(<STDIN>)}; my @t = grep { $_->{k} eq "t" } @m; my @c = grep { $_->{k} eq "c" } @m; my @w = grep { $_->{k} eq "w" } @m; '"$2" < "$1"
+}
+is() { out=$(check "$1" "$2"); [ -z "$out" ] && ok || bad "$3: $out"; }
+
+printf 'Short:\n\n```python\nprint("hi")\nx = 1\n```\n\nNo language:\n\n```\nmake test\n```\n\nLong:\n\n```sh\necho aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n```\n\n- An item:\n\n ```js\n const a = 1\n ```\n\n> A quote:\n>\n> ```ts\n> let b = 2\n> ```\n\nAfter.\n' | doc code
+for theme in claude-code vscode; do
+ for row in 0 13.2 11.6331; do
+ probe code $theme $row
+ f="$tmp/code-$theme-$row.marks"
+ # One button for each block (measure places no marks), and one line mark
+ # for each code line.
+ is "$f" 'print "t: ", scalar @t, "\n" if @t != 5; print "c: ", scalar @c, "\n" if @c != 6' "$theme row $row: the marks of 5 blocks and 6 lines"
+ # The contract: kind copy, the whole code, the language when there is one, a size.
+ is "$f" 'my @want = (["python", "print(\"hi\")\nx = 1\n"], [undef, "make test\n"], ["sh", undef], ["js", "const a = 1\n"], ["ts", "let b = 2\n"]);
+ for my $i (0 .. 4) { my ($t, $l, $c) = ($t[$i], @{$want[$i]});
+ print "$i kind\n" if $t->{kind} ne "copy";
+ print "$i lang\n" if (defined $l ? ($t->{lang} // "") ne $l : exists $t->{lang});
+ print "$i code\n" if defined $c and $t->{code} ne $c;
+ print "$i size\n" if !($t->{w} > 0 and $t->{h} > 0) }' "$theme row $row: the t marks"
+ # Order: the block's b mark, its button, then its lines.
+ is "$f" 'my $s = join " ", map { $_->{k} eq "b" ? "b" . $_->{kind} : $_->{k} } grep { $_->{k} ne "w" } @m; my $n = () = $s =~ /bcode t c/g; print "$s\n" if $n != 5' "$theme row $row: b, then t, then c"
+ # No word marks from the header (the language, Copy).
+ is "$f" 'print join(" ", map { $_->{t} } grep { $_->{t} =~ /^(Copy|python|sh|js|ts)$/ } @w), "\n" if grep { $_->{t} =~ /^(Copy|python|sh|js|ts)$/ } @w' "$theme row $row: no word marks in the header"
+ # Short code: a narrow block (the button's right edge far from the page's);
+ # the long line: the block is as wide as the page.
+ is "$f" 'print "short ", $t[0]{x} + $t[0]{w}, "\n" if $t[0]{x} + $t[0]{w} > 200; print "long ", $t[2]{x} + $t[2]{w}, "\n" if $t[2]{x} + $t[2]{w} < 400' "$theme row $row: the block width"
+ if [ "$row" != 0 ]; then
+ # The grid: the button is whole rows from the page's top (half a row
+ # more in the half-row phase), as high as a code line's rows, and
+ # each code line is the same rows below its button.
+ is "$f" 'my $r = '"$row"'; my $top = $m[0]{y};
+ for my $t (@t) { my $k = ($t->{y} - $top) / $r * 2; print "y $t->{y}\n" if abs($k - sprintf("%.0f", $k)) > 0.001;
+ my $h = $t->{h} / $r; print "h $t->{h}\n" if abs($h - sprintf("%.0f", $h)) > 0.001 or $h < 1 }
+ my %d = map { sprintf("%.3f", ($c[$_]{y} - $t[$_ > 1 ? $_ - 1 : 0]{y}) / $r - int(($c[$_]{y} - $t[$_ > 1 ? $_ - 1 : 0]{y}) / $r)) => 1 } (0, 2 .. 5);
+ print "line phases: ", join(" ", keys %d), "\n" if keys %d != 1' "$theme row $row: the header and the lines on the grid"
+ fi
+ done
+done
+
+# A code block that a live drawing makes has no header: no button mark (and
+# no other code marks: a drawing is scaled).
+printf 'Text.\n\n```typst\n#raw("let a = 1", block: true, lang: "rust")\n```\n' | doc draw
+probe draw claude-code 0
+is "$tmp/draw-claude-code-0.marks" 'print join(" ", map { $_->{k} } grep { $_->{k} =~ /^[tc]$/ or ($_->{kind} // "") eq "code" } @m), "\n" if grep { $_->{k} =~ /^[tc]$/ or ($_->{kind} // "") eq "code" } @m' "no code marks in a drawing"
+
+# PNGs to look at.
+if [ -n "${IUI_CODE_OUT:-}" ]; then
+ mkdir -p "$IUI_CODE_OUT"
+ for row in 0 13.2; do
+ # shellcheck disable=SC2046
+ typst compile --root / --package-path "$here/render/packages" --format png --ppi 144 $(inputs code vscode "$row") "$here/render/md.typ" "$IUI_CODE_OUT/code-$row-{0p}.png" 2>/dev/null
+ done
+fi
+echo "code-sh-test: $pass passed, $fail failed"
+[ "$fail" = 0 ]
diff --git a/tests/copy-fixture.ts b/tests/copy-fixture.ts
index c5042bd..90a0c2a 100644
--- a/tests/copy-fixture.ts
+++ b/tests/copy-fixture.ts
@@ -2,7 +2,7 @@
// probe=1, for the Markdown below at 98 columns of a 16 x 32 px cell (the
// default metrics, the default theme claude-code, dark: width 570.02 pt,
// ppi 198.0562, top 4.36 pt, row 11.6331 pt, code 0.8784). Its PNG is
-// 1568 x 512 px, 16 rows. To make it again (after a template change), with
+// 1568 x 544 px, 17 rows. To make it again (after a template change), with
// doc.json {"base": "/tmp", "segments": [SMALL_MD], "images": []} and
// IN="--input theme=dark --input width=570.02 --input top=4.36
// --input row=11.6331 --input code=0.8784
@@ -15,7 +15,7 @@
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, columns: 98, rows: 16 }
+export const SMALL_PAGE = { width: 1568, height: 544, columns: 98, rows: 17 }
export const SMALL_MARKS = [
{"k": "b", "p": 1, "x": 0.0, "y": 4.36, "s": 13.2, "kind": "heading"},
@@ -54,8 +54,9 @@ export const SMALL_MARKS = [
{"k": "w", "p": 1, "x": 32.138476562499996, "y": 99.929375, "s": 11.0, "t": "second", "w": 37.87158203125, "h": 13.126953125},
{"k": "w", "p": 1, "x": 73.10380859375, "y": 99.929375, "s": 11.0, "t": "item", "w": 22.48876953125, "h": 13.126953125},
{"k": "b", "p": 1, "x": 0.0, "y": 126.256328125, "s": 11.0, "kind": "code"},
- {"k": "c", "p": 1, "x": 12.571428571428573, "y": 147.18517857142857, "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": 162.11217857142856, "s": 11.0, "t": "ls -la", "w": 39.7353515625, "n": 6, "a": 8.357421875, "d": 2.642578125},
+ {"k": "t", "p": 1, "x": 78.2086342075893, "y": 126.256328125, "s": 11.0, "kind": "copy", "w": 46.60944614955357, "h": 18.70076729910714, "code": "echo hello world\nls -la\n", "lang": "sh"},
+ {"k": "c", "p": 1, "x": 12.571428571428573, "y": 165.88594587053572, "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": 180.8129458705357, "s": 11.0, "t": "ls -la", "w": 39.7353515625, "n": 6, "a": 8.357421875, "d": 2.642578125},
] as const
// The same probe (same inputs) for a long path and a long URL (30+
@@ -320,10 +321,10 @@ export const LONG_MARKS = [
// The same probe (same inputs, page=1) for links, inline code, a bare URL
// and path, and a bash block: the words in a link have `href`, those of
// inline code `code`. Its PNG is 1568 x
-// 416 px, 13 rows.
+// 448 px, 14 rows.
export const TARGETS_MD = "## Targets\n\nSee [the docs](https://example.com) and https://typst.app/docs/reference. Run `! ls -la` here.\n\nOpen `src/a.ts` or the bare path hooks/lib/copy.ts now, and [top](#targets).\n\n```bash\necho hello\nls -la\n```\n"
-export const TARGETS_PAGE = { width: 1568, height: 416, columns: 98, rows: 13 }
+export const TARGETS_PAGE = { width: 1568, height: 448, columns: 98, rows: 14 }
export const TARGETS_MARKS = [
{"k": "b", "p": 1, "x": 0.0, "y": 4.36, "s": 13.2, "kind": "heading"},
@@ -367,7 +368,7 @@ export const TARGETS_MARKS = [
{"k": "w", "p": 1, "x": 254.8798828125, "y": 38.988515625000005, "s": 11.0, "t": "e", "w": 6.2841796875, "h": 13.126953125, "g": 1},
{"k": "w", "p": 1, "x": 261.1640625, "y": 38.988515625000005, "s": 11.0, "t": ".", "w": 3.265625, "h": 13.126953125, "g": 1},
{"k": "w", "p": 1, "x": 267.5234375, "y": 38.988515625000005, "s": 11.0, "t": "Run", "w": 20.0234375, "h": 13.126953125},
- {"k": "w", "p": 1, "x": 290.640625, "y": 38.988515625000005, "s": 11.0, "t": "\u200d", "w": 0.0, "h": 13.126953125, "code": "! ls -la"},
+ {"k": "w", "p": 1, "x": 290.640625, "y": 38.988515625000005, "s": 11.0, "t": "‍", "w": 0.0, "h": 13.126953125, "code": "! ls -la"},
{"k": "w", "p": 1, "x": 290.640625, "y": 41.104726562500005, "s": 11.0, "t": "!", "w": 6.62255859375, "h": 11.0, "code": "! ls -la"},
{"k": "w", "p": 1, "x": 303.8857421875, "y": 41.104726562500005, "s": 11.0, "t": "ls", "w": 13.2451171875, "h": 11.0, "code": "! ls -la"},
{"k": "w", "p": 1, "x": 323.75341796875, "y": 41.104726562500005, "s": 11.0, "t": "-", "w": 6.62255859375, "h": 11.0, "code": "! ls -la"},
@@ -375,7 +376,7 @@ export const TARGETS_MARKS = [
{"k": "w", "p": 1, "x": 346.71484375, "y": 38.988515625000005, "s": 11.0, "t": "here.", "w": 26.33447265625, "h": 13.126953125},
{"k": "b", "p": 1, "x": 0.0, "y": 65.31546875, "s": 11.0, "kind": "par"},
{"k": "w", "p": 1, "x": 0.0, "y": 65.31546875, "s": 11.0, "t": "Open", "w": 27.90283203125, "h": 13.126953125},
- {"k": "w", "p": 1, "x": 30.99658203125, "y": 65.31546875, "s": 11.0, "t": "\u200d", "w": 0.0, "h": 13.126953125, "code": "src/a.ts"},
+ {"k": "w", "p": 1, "x": 30.99658203125, "y": 65.31546875, "s": 11.0, "t": "‍", "w": 0.0, "h": 13.126953125, "code": "src/a.ts"},
{"k": "w", "p": 1, "x": 30.99658203125, "y": 67.4316796875, "s": 11.0, "t": "src/", "w": 26.490234375, "h": 11.0, "code": "src/a.ts"},
{"k": "w", "p": 1, "x": 57.48681640625, "y": 67.4316796875, "s": 11.0, "t": "a.ts", "w": 26.490234375, "h": 11.0, "code": "src/a.ts"},
{"k": "w", "p": 1, "x": 87.07080078125, "y": 65.31546875, "s": 11.0, "t": "or", "w": 10.6884765625, "h": 13.126953125},
@@ -390,6 +391,7 @@ export const TARGETS_MARKS = [
{"k": "w", "p": 1, "x": 312.447265625, "y": 65.31546875, "s": 11.0, "t": "top", "w": 17.12841796875, "h": 13.126953125},
{"k": "w", "p": 1, "x": 329.57568359375, "y": 65.31546875, "s": 11.0, "t": ".", "w": 3.265625, "h": 13.126953125},
{"k": "b", "p": 1, "x": 0.0, "y": 91.642421875, "s": 11.0, "kind": "code"},
- {"k": "c", "p": 1, "x": 12.571428571428573, "y": 112.57127232142858, "s": 11.0, "t": "echo hello", "w": 66.2255859375, "n": 10, "a": 8.357421875, "d": 2.642578125},
- {"k": "c", "p": 1, "x": 12.571428571428573, "y": 127.49827232142857, "s": 11.0, "t": "ls -la", "w": 39.7353515625, "n": 6, "a": 8.357421875, "d": 2.642578125},
+ {"k": "t", "p": 1, "x": 46.440586635044646, "y": 91.642421875, "s": 11.0, "kind": "copy", "w": 46.60944614955357, "h": 18.70076729910714, "code": "echo hello\nls -la\n", "lang": "bash"},
+ {"k": "c", "p": 1, "x": 12.571428571428573, "y": 131.2720396205357, "s": 11.0, "t": "echo hello", "w": 66.2255859375, "n": 10, "a": 8.357421875, "d": 2.642578125},
+ {"k": "c", "p": 1, "x": 12.571428571428573, "y": 146.19903962053573, "s": 11.0, "t": "ls -la", "w": 39.7353515625, "n": 6, "a": 8.357421875, "d": 2.642578125},
] as const
diff --git a/tests/copy.test.ts b/tests/copy.test.ts
index 85af40f..3eeb3af 100644
--- a/tests/copy.test.ts
+++ b/tests/copy.test.ts
@@ -16,7 +16,7 @@ import { clip, drawnAnswers, lastKey, results, type Job, type Result } from '../
import { forgetBlits, over, rgbOf, WRITE_PL } from '../hooks/lib/blit'
import { forgetRedraws } from '../hooks/lib/select'
import { chunk, concat, decodePng, deflatePiece, fromBase64, headOf, tailOf, toBase64 } from '../hooks/lib/png'
-import { LONG_MARKS, LONG_MD, LONG_PAGE, SMALL_MARKS, SMALL_MD, SMALL_PAGE, SMALL_PPI, TARGETS_MARKS, TARGETS_MD } from './copy-fixture'
+import { LONG_MARKS, LONG_MD, LONG_PAGE, SMALL_MARKS, SMALL_MD, SMALL_PAGE, SMALL_PPI, TARGETS_MARKS, TARGETS_MD, TARGETS_PAGE } 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`.
@@ -113,6 +113,43 @@ test("a word keeps its link's URL and its inline code's text", () => {
expect(got.pages[0]![1]).toEqual({ i: 1, text: 'a.ts', block: 0, x0: 20, x1: 30, y0: 0, y1: 12, pad: 1, code: 'a.ts' })
})
+test("a code block's copy tag is a button in pixels, on its page; no word, so the copy of the text does not change", () => {
+ const marks: Mark[] = [
+ { k: 'b', p: 1, x: 0, y: 0, kind: 'code' },
+ { k: 't', p: 2, x: 100, y: 4, s: 11, kind: 'copy', w: 30, h: 12, code: 'ls\npwd', lang: 'sh' },
+ { k: 'c', p: 2, x: 0, y: 30, t: 'ls', w: 12, n: 2, a: 8, d: 2 },
+ { k: 't', p: 2, x: 100, y: 50, kind: 'copy', w: 30, h: 12, code: 'x' },
+ // Another tag kind, or one with no code: dropped.
+ { k: 't', p: 2, x: 0, y: 0, kind: 'other', w: 1, h: 1, code: 'y' },
+ { k: 't', p: 2, x: 0, y: 0, kind: 'copy', w: 1, h: 1 },
+ ]
+ const got = positionsOf(marks, 144)
+ expect(got.buttons).toEqual([[], [{ x0: 200, y0: 8, x1: 260, y1: 32, code: 'ls\npwd', lang: 'sh' }, { x0: 200, y0: 100, x1: 260, y1: 124, code: 'x' }]])
+ expect(got.pages).toEqual([[], [{ i: 0, text: 'ls', block: 0, x0: 0, x1: 24, y0: 44, y1: 64, adv: 12 }]])
+ expect(got.blocks).toEqual([{ kind: 'code', prefix: '', first: 0 }])
+ // One line break at the end goes ("\n" or "\r\n"), not more, and no other space.
+ const code = (c: string) => positionsOf([{ k: 't', p: 1, x: 0, y: 0, kind: 'copy', w: 1, h: 1, code: c }], 72).buttons[0]![0]!.code
+ expect([code('ls\n'), code('ls\r\n'), code('ls\n\n'), code('ls \n'), code('\tls '), code('\n')]).toEqual(['ls', 'ls', 'ls\n', 'ls ', '\tls ', ''])
+ // An old probe (no tags): no buttons.
+ expect(positionsOf(marks.filter(m => m.k !== 't'), 144).buttons).toEqual([])
+ // The text of the fixture's page (its probe has a tag) is the same with no tag.
+ const all = Array.from({ length: TARGETS_PAGE.rows }, (_, row) => ({ row, colStart: 0, colEnd: 97 }))
+ const textOf = (ms: readonly object[]) => {
+ const p = positionsOf(ms as unknown as Mark[], SMALL_PPI)
+ return textOfRun(all, p.pages[0]!, p.blocks, TARGETS_PAGE)
+ }
+ expect(TARGETS_MARKS.some(m => m.k === 't')).toBe(true)
+ expect(textOf(TARGETS_MARKS)).toBe(textOf(TARGETS_MARKS.filter(m => m.k !== 't')))
+ // A list item whose first content is a code block: the tag is not its body (the marker test).
+ const item: Mark[] = [
+ { k: 'w', p: 1, x: 0, y: 0, t: '-', w: 4, h: 12 },
+ { k: 'b', p: 1, x: 10, y: 0, kind: 'item', prefix: '- ' },
+ { k: 't', p: 1, x: 200, y: 0, kind: 'copy', w: 30, h: 12, code: 'a' },
+ { k: 'c', p: 1, x: 10, y: 20, t: 'a', w: 6, n: 1, a: 8, d: 2 },
+ ]
+ expect(positionsOf(item, 72).pages[0]!.map(w => w.text)).toEqual(['a'])
+})
+
// A hand-made page: 10 columns of 10 px, 4 rows of 20 px.
const PAGE = { width: 100, height: 80, columns: 10, 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 })
@@ -291,8 +328,8 @@ test("a real probe: the whole picture copies as the answer's text", () => {
})
test('a real probe: a selection from mid-paragraph into the code block', () => {
- // Rows: heading 1, paragraph 3 and 5, items 7 and 9, code 12 and 13.
- const lines = [{ row: 3, colStart: 30, colEnd: 97 }, ...[4, 5, 6, 7, 8, 9, 10, 11].map(ALL_COLUMNS), { row: 12, colStart: 0, colEnd: 14 }]
+ // Rows: heading 1, paragraph 3 and 5, items 7 and 9, the code's header 11, code 14 and 15.
+ const lines = [{ row: 3, colStart: 30, colEnd: 97 }, ...[4, 5, 6, 7, 8, 9, 10, 11, 12, 13].map(ALL_COLUMNS), { row: 14, colStart: 0, colEnd: 14 }]
expect(textOfRun(lines, REAL.pages[0]!, REAL.blocks, SMALL_PAGE)).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 ',
)
@@ -1724,8 +1761,9 @@ test('picture select: with no perl the first frame write fails, is logged once a
// TARGETS_MD drawn as `ans-1` (its probe the fixture's TARGETS_MARKS), with
// src/a.ts a file in the session's folder /w. Its targets (targets.test.ts):
// the link "the docs" row 3 columns 4 to 11, the bare URL row 3 16 to 45,
-// `! ls -la` row 4 50 to 58, src/a.ts row 6 5 to 13 (the bash block rows 9 and 10: no target).
-async function drawTargets($: any, on: any, o: { env?: Record<string, string> } = {}, isFullscreen: boolean | null = true) {
+// `! ls -la` row 4 50 to 58, src/a.ts row 6 5 to 13, the bash block's copy
+// button row 8 8 to 15 (its code rows 11 and 12: no target).
+async function drawTargets($: any, on: any, o: { env?: Record<string, string>; marks?: readonly object[] } = {}, isFullscreen: boolean | null = true) {
const w = world(on, { tty: TTY, marks: TARGETS_MARKS, ...o })
on('session.cwd', async () => ({ value: '/w' }))
on('fs.exists', async ($: any, e: any) => ({ value: e.path === '/w/src/a.ts' }))
@@ -1829,6 +1867,28 @@ test('picture select: a click copies a link, a file\'s path or a command; a clic
expect(w.copies.length).toBe(4)
})
+test("picture select: a click on a code block's copy button copies its whole code; a hover tints the button", async ($, on) => {
+ const { w, ui } = await drawTargets($, on, { env: { HOME: '/h', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1', IUI_DEBUG: '1' } })
+ // The button: row 8, columns 8 to 15.
+ await hover(ui, 11, 8)
+ await settle(w)
+ expect(isFrame(w)).toBe(true)
+ const png = w.frames.at(-1)!.png
+ expect([cellOf(png, 8, 8), cellOf(png, 8, 15)]).toEqual(['selected', 'selected'])
+ expect([cellOf(png, 8, 7), cellOf(png, 8, 16), cellOf(png, 9, 11)]).toEqual(['page', 'page', 'page'])
+ await click(ui, 11, 8)
+ await settle(w)
+ expect(w.copies).toEqual(['echo hello\nls -la'])
+ expect(w.toasts).toContain('Intelligent UI: copied the code')
+ expect(w.traces.some(t => t.includes('select: hover ans-1 page 0 target 4 (code) rows 8:8-15'))).toBe(true)
+ expect(w.traces.some(t => t.includes('select: click ans-1 page 0 at 11,8 target code'))).toBe(true)
+ // The code's text is no target; the other targets copy as before.
+ await click(ui, 5, 11)
+ await click(ui, 52, 4)
+ await settle(w)
+ expect(w.copies).toEqual(['echo hello\nls -la', 'ls -la'])
+})
+
test('picture select: a ctrl+click copies as a plain click does; a right click is dropped', async ($, on) => {
const { w, ui } = await drawTargets($, on)
await click(ui, 6, 3, { button: 'right' })
diff --git a/tests/select.test.ts b/tests/select.test.ts
index e789720..b336047 100644
--- a/tests/select.test.ts
+++ b/tests/select.test.ts
@@ -207,7 +207,7 @@ test('a selection reads as a copy of the same cells: the same runs, the same tex
test('a selection over two pages is the text of each, one line apart; a page with no words read is no text', () => {
const pages = [SMALL_PAGE, SMALL_PAGE]
// Page 0 from "the lazy dog" (row 3, column 30) to its end, page 1 its heading.
- const runs = runsOf(selectedRows(sel(30, 3, 97, 17), pages))
+ const runs = runsOf(selectedRows(sel(30, 3, 97, 18), pages))
expect(runs.map(r => r.page)).toEqual([0, 1])
const words = () => ({ items: REAL.pages[0]!, blocks: REAL.blocks })
expect(textOfRuns(runs, words, pages)).toBe(
diff --git a/tests/targets.test.ts b/tests/targets.test.ts
index 268cd78..d49d3e1 100644
--- a/tests/targets.test.ts
+++ b/tests/targets.test.ts
@@ -1,6 +1,6 @@
import { expect, test } from 'claude-code/testing'
-import { positionsOf, targetAt, targetsOf, textOfRun, type Item, type Mark, type ShownLink, type TextBlock } from '../hooks/register'
+import { positionsOf, targetAt, targetsOf, textOfRun, type Button, type Item, type Mark, type ShownLink, type TextBlock } from '../hooks/register'
import { LONG_MARKS, LONG_MD, LONG_PAGE, SMALL_PPI, TARGETS_MARKS, TARGETS_PAGE } from './copy-fixture'
const file = (label: string, path: string): ShownLink => ({ kind: 'file', label, path, href: `file://${path}` })
@@ -12,7 +12,7 @@ const REAL = positionsOf(TARGETS_MARKS as unknown as Mark[], SMALL_PPI)
const WORDS = { items: REAL.pages[0]!, blocks: REAL.blocks }
test('a real probe: links, a bare URL, inline code, a bare path are targets; a bash block is none', () => {
- // Rows: paragraph 3 (its inline code 4), paragraph 6, code 9 and 10.
+ // Rows: paragraph 3 (its inline code 4), paragraph 6, the code's button 8, code 11 and 12.
expect(targetsOf(WORDS, TARGETS_PAGE, LINKS)).toEqual([
{ target: { kind: 'web', href: 'https://example.com' }, rows: [{ row: 3, x0: 4, x1: 11 }] },
{ target: { kind: 'web', href: 'https://typst.app/docs/reference' }, rows: [{ row: 3, x0: 16, x1: 45 }] },
@@ -35,6 +35,19 @@ test('a real probe: a bare file that does not exist (no ShownLink) is no target,
expect(got[3]).toEqual({ kind: 'command', text: 'src/a.ts' })
})
+test("a real probe with a code block's copy button: a code target over its box, in order; the words' targets as before", () => {
+ const got = positionsOf(TARGETS_MARKS as unknown as Mark[], SMALL_PPI)
+ const words = { items: got.pages[0]!, blocks: got.blocks, buttons: got.buttons[0]! }
+ expect(words.items).toEqual(WORDS.items)
+ const targets = targetsOf(words, TARGETS_PAGE, LINKS)
+ expect(targets.map(t => t.target.kind)).toEqual(['web', 'web', 'command', 'file', 'file', 'code'])
+ expect(targets[5]).toEqual({ target: { kind: 'code', text: 'echo hello\nls -la', lang: 'bash' }, rows: [{ row: 8, x0: 8, x1: 15 }] })
+ expect(targetAt(targets, 8, 8)).toBe(5)
+ expect(targetAt(targets, 15, 8)).toBe(5)
+ expect(targetAt(targets, 16, 8)).toBe(-1)
+ expect(targetAt(targets, 11, 9)).toBe(-1)
+})
+
test('a real probe: a long path and a long URL that wraps (a character a word)', () => {
const long = positionsOf(LONG_MARKS as unknown as Mark[], SMALL_PPI)
const path = '/Users/someone/Development/apps/very/long/path/to/file.ts'
@@ -101,11 +114,48 @@ test('a bare path takes the punctuation around it off; a bare word that is a nam
expect(of([word(0, 'a/', 0, 0), word(1, 'b.ts:12', 30, 0)], PAR, links)).toEqual([])
})
-test('a code block is no target, also a shell block', () => {
+test('the text of a code block is no target, also a shell block', () => {
const line = (i: number, text: string, row: number): Item => ({ i, text, x0: 10, x1: 10 + text.length * 5, y0: row * 20 + 4, y1: row * 20 + 16, block: 0, adv: 5 })
expect(of([line(0, '$ make build', 0), line(1, 'https://x.dev', 1)], [{ kind: 'code', prefix: '', first: 0 }])).toEqual([])
})
+// A button's box: x0..x1, y0..y1 in px.
+const button = (x0: number, y0: number, x1: number, y1: number, more: Partial<Button> = {}): Button => ({ x0, y0, x1, y1, code: 'make\nmake test', ...more })
+const withButtons = (items: Item[], buttons: Button[], blocks = PAR) => targetsOf({ items, blocks, buttons }, PAGE, [])
+
+test("a copy button is a code target: the cells whose centres are in its box, its code and language", () => {
+ // Centres of columns 6 to 8 (65, 75, 85) and row 0 (10) are in the box.
+ expect(withButtons([], [button(62, 2, 88, 18, { lang: 'sh' })])).toEqual([
+ { target: { kind: 'code', text: 'make\nmake test', lang: 'sh' }, rows: [{ row: 0, x0: 6, x1: 8 }] },
+ ])
+ // No language: none kept.
+ expect(withButtons([], [button(62, 2, 88, 18)])[0]!.target).toEqual({ kind: 'code', text: 'make\nmake test' })
+ // A box smaller than a cell, over no centre: the cell of its centre.
+ expect(withButtons([], [button(71, 21, 78, 28)])[0]!.rows).toEqual([{ row: 1, x0: 7, x1: 7 }])
+})
+
+test('a copy button that is taller than a row takes each row whose centre is in it; one off the page none', () => {
+ // Rows 1 and 2 (centres 30, 50); columns 7 to 9 (the last one clamped).
+ expect(withButtons([], [button(70, 22, 120, 58)])[0]!.rows).toEqual([{ row: 1, x0: 7, x1: 9 }, { row: 2, x0: 7, x1: 9 }])
+ expect(withButtons([], [button(10, 90, 30, 110)])).toEqual([])
+})
+
+test('copy buttons go in order with the other targets, by their first row and column', () => {
+ const href = 'https://x.dev'
+ const items = [word(0, 'see', 0, 0, { href }), word(1, 'npm', 0, 2, { code: 'npm' })]
+ const got = withButtons(items, [button(62, 22, 88, 38, { code: 'a' }), button(62, 62, 88, 78, { code: 'b' })])
+ expect(got.map(t => t.target)).toEqual([
+ { kind: 'web', href }, { kind: 'code', text: 'a' }, { kind: 'command', text: 'npm' }, { kind: 'code', text: 'b' },
+ ])
+ // On the row of a target, right of it: after it; left of it: before it.
+ expect(withButtons(items, [button(62, 2, 88, 18, { code: 'c' })]).map(t => t.target.kind)).toEqual(['web', 'code', 'command'])
+ const right = [word(0, 'see', 70, 0, { href })]
+ expect(withButtons(right, [button(2, 2, 28, 18, { code: 'c' })]).map(t => t.target.kind)).toEqual(['code', 'web'])
+ expect(targetAt(got, 7, 1)).toBe(1)
+ expect(targetAt(got, 0, 2)).toBe(2)
+ expect(targetAt(got, 8, 3)).toBe(3)
+})
+
test('the cells scale with the box the page is drawn at', () => {
const href = 'https://x.dev'
const items = [word(0, 'the', 30, 0, { href }), word(1, 'link', 60, 1, { href })]