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

Copy: pick the page on screen; count a Typst block as its room rows

razorback16d4b1e72fa6f1
diff --git a/hooks/lib/copy.ts b/hooks/lib/copy.ts
index 626547d..18d54eb 100644
--- a/hooks/lib/copy.ts
+++ b/hooks/lib/copy.ts
@@ -216,12 +216,48 @@ export function positionsOf(marks: readonly Mark[], ppi: number): Positions {
// drawn (fitBox: an old page in an open epoch draws smaller than it was
// compiled for). The placeholders count the cells of that box.
export type DrawnPage = { file: string; width: number; height: number; columns: number; rows: number }
+// The rows of a drawing's transcript message on screen at its last draw
+// (e.props.onScreen on the terminal): rows `first` to `last` of its `of`,
+// from the first row of the tree the hook drew.
+export type OnScreen = { first: number; last: number; of: number }
+// Where a drawing's pages sit in their message: `below` the rows under the
+// last page (a Typst error line, a sent file's pictures after it); `top` the
+// rows the layout puts above the first page (an answer's top margin), absent
+// when the engine's row of its own height is above (a plan, a sent file).
+export type Place = { top?: number; below: number }
// An answer drawn this session (`seq` grows with each new one); `dir` its
// key folder. A plan is `plan:<tool_use_id>`, a Markdown file Claude sent
-// `file:<tool_use_id>:<path>`.
-export type Drawn = { id: string; seq: number; dir: string; pages: DrawnPage[] }
+// `file:<tool_use_id>:<path>`. `onScreen` its message's rows on screen
+// (null: drawn outside the viewport; absent: not known), `place` where its
+// pages are in them.
+export type Drawn = { id: string; seq: number; dir: string; pages: DrawnPage[]; place?: Place; onScreen?: OnScreen | null }
export type Pick = { id: string; page: number } | null
+// e.props.onScreen as an OnScreen: null when drawn outside the viewport,
+// undefined when the surface does not say (or it is not one).
+export function screenOf(v: unknown): OnScreen | null | undefined {
+ if (v === null) return null
+ const o = v as Partial<OnScreen> | undefined
+ return o && typeof o.first === 'number' && typeof o.last === 'number' && typeof o.of === 'number' ? { first: o.first, last: o.last, of: o.of } : undefined
+}
+
+// The row of its message each page of `d` starts at, by its last onScreen.
+// The pages are the last rows of the tree but `below`, at their drawn rows
+// (DrawnPage.rows, as drawPages draws them), so the first page's top is
+// `of - below - (their rows)`: exact for the layout `of` was counted on,
+// with no row of tolerance needed. That top is under 0, or over place.top
+// (an answer's top margin; 0 is taken too, as the root Box's margin may be
+// outside the rows the engine counts), when `of` is of another layout (the
+// row drawn as text before, a page drawn at another size): not known then.
+// Undefined: not known; null: drawn outside the viewport.
+export function pageTopsOf(d: Drawn): number[] | null | undefined {
+ if (d.onScreen === null) return null
+ if (!d.onScreen || !d.place) return undefined
+ let at = d.onScreen.of - d.place.below - d.pages.reduce((sum, p) => sum + p.rows, 0)
+ if (at < 0 || (d.place.top !== undefined && at > d.place.top)) return undefined
+ return d.pages.map(p => (at += p.rows) - p.rows)
+}
+
// Whether a drawing is the one of the transcript row `requestId` (a
// selection's row): an answer by its own id, a plan or a sent file by the
// call's tool_use_id.
@@ -231,16 +267,29 @@ export const isDrawnIn = (id: string, requestId: string) =>
// 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 drawing of `requestId` (the selection's transcript row,
-// isDrawnIn) when it fits, else to the newest drawing 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.
+// end on its page's last row, and the next start at row 0.
+//
+// The clipboard has only the row and column of each cell, not the page: a
+// run inside one page of a many-page answer fits every page tall enough.
+// A mouse selection is on screen when it is copied, so a placement is kept
+// only when one of its runs' rows (its page's top, pageTopsOf, plus the
+// run's rows) is in its message's rows on screen; a drawing outside the
+// viewport has none. A drawing with no known rows on screen keeps all its
+// placements, as before. A chain goes to the drawing of `requestId` (the
+// selection's transcript row, isDrawnIn) when it fits there: its first
+// placement on screen, else its first (the row is surer than rows on
+// screen that can be out of date). Else to the newest drawing with a
+// placement on screen, else to the newest it fits, as before. Two
+// placements on screen at once are only possible with a page shorter than
+// the viewport (or two drawings at the same width on screen): the first by
+// that order (in a drawing, the first page) is taken.
export function pickPages(segments: readonly Segment[], drawn: readonly Drawn[], requestId?: string): Pick[] {
const picks: Pick[] = segments.map(() => null)
- const mine = (d: Drawn) => (requestId !== undefined && isDrawnIn(d.id, requestId) ? 1 : 0)
- const order = [...drawn].sort((a, b) => mine(b) - mine(a) || b.seq - a.seq)
+ const mine = (d: Drawn) => requestId !== undefined && isDrawnIn(d.id, requestId)
+ const newest = [...drawn].sort((a, b) => b.seq - a.seq)
+ const mineFirst = newest.filter(mine)
+ const others = newest.filter(d => !mine(d))
+ const tops = new Map(drawn.map(d => [d.id, pageTopsOf(d)]))
let i = 0
while (i < segments.length) {
if (segments[i]!.kind !== 'image') {
@@ -261,13 +310,27 @@ export function pickPages(segments: readonly Segment[], drawn: readonly Drawn[],
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
+ const onScreen = (d: Drawn, start: number) => {
+ const at = tops.get(d.id)
+ if (at === undefined) return true
+ const view = d.onScreen
+ if (!at || !view) return false
+ return runs.some((run, n) => {
+ const rows = run.lines.map(l => at[start + n]! + l.row)
+ return Math.min(...rows) <= view.last && Math.max(...rows) >= view.first
+ })
+ }
+ const place = (order: readonly Drawn[], seen: boolean) => {
+ for (const d of order) {
+ for (let start = 0; start + runs.length <= d.pages.length; start++) {
+ if (!fits(d, start) || (seen && !onScreen(d, start))) continue
+ runs.forEach((_, n) => (picks[i + n] = { id: d.id, page: start + n }))
+ return true
+ }
}
+ return false
}
+ if (!place(mineFirst, true) && !place(mineFirst, false) && !place(others, true)) place(others, false)
i = j
}
return picks
diff --git a/hooks/lib/markdown.ts b/hooks/lib/markdown.ts
index f7a8904..c7da41b 100644
--- a/hooks/lib/markdown.ts
+++ b/hooks/lib/markdown.ts
@@ -1,6 +1,6 @@
// Markdown as the mod reads it: blocks, fences, the segments an answer is
// cut into, the images it names, and a plain text of it for an Image's alt.
-import { ALT_CHARS, SEGMENT_ROWS } from './settings'
+import { ALT_CHARS, DRAWING_ROWS, SEGMENT_ROWS } from './settings'
export const FENCE = /^( {0,3})(`{3,}|~{3,})\s*([^\s`]*)/
export const isTypstInfo = (info: string) => /^(typst|typ)$/i.test(info)
@@ -60,17 +60,19 @@ export function blocksOf(md: string): Block[] {
// A rough count of the rows a block takes once drawn `columns` wide, its
// text at `size` percent (/iui size): fewer characters a row, and
-// taller lines.
-export function rowsOfBlock(block: Block, columns: number, size = 100): number {
+// taller lines. A typst fence is its drawing, not its source: `roomRows`
+// (the room height in terminal rows; it does not follow `size`) and its
+// margins (1.2em above and below: about 2 rows, at `size`).
+export function rowsOfBlock(block: Block, columns: number, size = 100, roomRows = DRAWING_ROWS): number {
const isCode = !!block.fence
const scale = size / 100
+ if (block.fence && isTypstInfo(block.fence.info)) return roomRows + 2 * scale
const perRow = (columns / scale) * (isCode ? 1.0 : 1.15)
let rows = 1
for (const line of block.lines) {
rows += Math.ceil(Math.max(1, line.length) / perRow) * (isCode ? 1.1 : 1.3) * scale
if (/^#{1,2}\s/.test(line)) rows += 1.5 * scale
}
- if (block.fence && isTypstInfo(block.fence.info)) rows += 20
return rows
}
@@ -82,8 +84,9 @@ const FOOTNOTE_DEF = /^ {0,3}\[\^[^\]]+\]:/
// fences of the same language; a typst fence always stays whole. A block that
// starts indented (a list item's continuation) never starts a segment. Text
// with footnotes stays one segment; link definitions go into every segment.
-// `size`: the text size percent the rows are counted at.
-export function splitSegments(md: string, columns: number, budget = SEGMENT_ROWS, size = 100): string[] {
+// `size`: the text size percent the rows are counted at; `roomRows`: the
+// room height of a drawing in terminal rows.
+export function splitSegments(md: string, columns: number, budget = SEGMENT_ROWS, size = 100, roomRows = DRAWING_ROWS): string[] {
const blocks = blocksOf(md)
if (!blocks.length) return []
const outside = blocks.filter(b => !b.fence).flatMap(b => b.lines)
@@ -105,7 +108,7 @@ export function splitSegments(md: string, columns: number, budget = SEGMENT_ROWS
const segments: Block[][] = [[]]
let used = 0
for (const piece of pieces) {
- const need = rowsOfBlock(piece, columns, size)
+ const need = rowsOfBlock(piece, columns, size, roomRows)
const canCut = !/^\s/.test(piece.lines[0] ?? '')
if (used + need > budget && segments.at(-1)!.length && canCut) {
segments.push([])
@@ -121,9 +124,9 @@ export function splitSegments(md: string, columns: number, budget = SEGMENT_ROWS
// A segment whose page came out taller than an Image can be, cut in two by
// the same rules (at half its rows); one piece when it can not be cut.
-export function splitInTwo(md: string, columns: number, size = 100): string[] {
- const rows = blocksOf(md).reduce((n, block) => n + rowsOfBlock(block, columns, size), 0)
- return splitSegments(md, columns, Math.max(1, Math.ceil(rows / 2)), size)
+export function splitInTwo(md: string, columns: number, size = 100, roomRows = DRAWING_ROWS): string[] {
+ const rows = blocksOf(md).reduce((n, block) => n + rowsOfBlock(block, columns, size, roomRows), 0)
+ return splitSegments(md, columns, Math.max(1, Math.ceil(rows / 2)), size, roomRows)
}
// Whether a text needs the room height (it is then in its key): it has a
diff --git a/hooks/lib/pictures.tsx b/hooks/lib/pictures.tsx
index c95c09d..8aac1ed 100644
--- a/hooks/lib/pictures.tsx
+++ b/hooks/lib/pictures.tsx
@@ -250,6 +250,18 @@ export async function sentOf(
const boxOf = (frame: Frame, inline: boolean, height: Height): PixelBox =>
convertBox(pictureColumns(frame, inline), pictureRowsFor(frame.rows, height), frame.cell)
+// The rows underRow draws after `under[i]`: a picture its rows, a Markdown
+// file its pages at their drawn box (fitBox in `room`, as drawPages) and a
+// Typst error line, a blank none.
+export function rowsAfter(under: readonly Under[], i: number, room: number): number {
+ return under.slice(i + 1).reduce((sum, u) => {
+ if ('source' in u) return sum + u.rows
+ if (u.drawing.kind !== 'pages') return sum
+ const { pages, note } = u.drawing.result
+ return sum + pages.reduce((n, p) => n + fitBox(p, room).rows, 0) + (note ? 1 : 0)
+ }, 0)
+}
+
// The engine's row, then the pictures under it.
export function underRow($: EngineInterface, e: RowInput, row: RenderElement, under: readonly Under[]) {
const { Box, Image } = $.ui.resolve(e)
diff --git a/hooks/lib/probe.ts b/hooks/lib/probe.ts
index 1c6415a..a4ee416 100644
--- a/hooks/lib/probe.ts
+++ b/hooks/lib/probe.ts
@@ -10,13 +10,15 @@ 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 type { Drawn, DrawnPage, Item, TextBlock } from './copy'
+import { screenOf, type Drawn, type DrawnPage, type Item, type TextBlock } from './copy'
// Notes the pages of `id` as drawn now, each at fitBox(page, room), as
// drawPages draws it, with the Job of the key the row drew last (lastKey:
// the result drawn is that key's). A redraw with the same pages at the same
-// boxes keeps its place, so `seq` is when it was first drawn so.
-export function noteDrawn(id: string, result: Result, room: number) {
+// boxes keeps its place, so `seq` is when it was first drawn so. `at`: the
+// rows above the pages in their message when the layout says (`top`), and
+// the rows drawn under them besides a Typst error line (`after`); see Place.
+export function noteDrawn(id: string, result: Result, room: number, at: { top?: number; after?: number } = {}) {
const pages: DrawnPage[] = result.pages.map(p => ({ file: p.file, width: p.width, height: p.height, ...fitBox(p, room) }))
const dir = result.pages[0]?.file.replace(/\/[^/]*$/, '') ?? ''
const was = drawnAnswers.get(id)
@@ -24,18 +26,29 @@ export function noteDrawn(id: string, result: Result, room: number) {
const now = pages[i]
return !!now && p.file === now.file && p.columns === now.columns && p.rows === now.rows
}
- if (was && was.dir === dir && was.pages.length === pages.length && was.pages.every(same)) return
+ const place = { ...(at.top !== undefined ? { top: at.top } : {}), below: (result.note ? 1 : 0) + (at.after ?? 0) }
+ if (was && was.dir === dir && was.pages.length === pages.length && was.pages.every(same)) {
+ was.place = place
+ return
+ }
const last = lastKey.get(id)
const job = last && `${last.job.env.cache}/${last.key}` === dir ? last.job : undefined
- keep(drawnAnswers, id, { id, seq: ++clip.seq, dir, pages, ...(job ? { job } : {}) }, DRAWN_KEPT)
+ keep(drawnAnswers, id, { id, seq: ++clip.seq, dir, pages, place, ...(job ? { job } : {}) }, DRAWN_KEPT)
}
// A memo hit (the same drawing as before): noted again only when it went
// past DRAWN_KEPT, from the result the row last drew (lastKey).
-export function noteDrawnAgain(id: string, room: number) {
+export function noteDrawnAgain(id: string, room: number, at: { top?: number; after?: number } = {}) {
if (drawnAnswers.has(id)) return
const result = results.get(lastKey.get(id)?.key ?? '')
- if (result && result !== 'failed') noteDrawn(id, result, room)
+ if (result && result !== 'failed') noteDrawn(id, result, room, at)
+}
+
+// The rows of its message on screen (e.props.onScreen) of a drawing noted,
+// at each draw of its row: no redraw, nothing kept changes.
+export function noteOnScreen(id: string, onScreen: unknown) {
+ const d = drawnAnswers.get(id)
+ if (d) d.onScreen = screenOf(onScreen)
}
// ---- Positions ----------------------------------------------------------------
diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.ts
index 75f4abe..434fee2 100644
--- a/hooks/lib/settings.ts
+++ b/hooks/lib/settings.ts
@@ -41,6 +41,9 @@ export const BLANK_RESUMED_MS = 1000
export const MAX_RUNNING = 2
// A segment is cut to be about this many rows; an Image is 255 rows at most.
export const SEGMENT_ROWS = 160
+// The rows a live Typst block is counted as when its room is not known: the
+// largest room of the default height (PICTURE_MAX_ROWS).
+export const DRAWING_ROWS = 24
export const MAX_IMAGE_ROWS = 255
// The cell in device pixels when the tty reports none (tmux, a relay): an
// 8 x 16 point cell at Retina scale 2. A reported cell outside 4 to 64 px
diff --git a/hooks/lib/typst.ts b/hooks/lib/typst.ts
index fb8b854..5c595b2 100644
--- a/hooks/lib/typst.ts
+++ b/hooks/lib/typst.ts
@@ -388,7 +388,11 @@ export async function compile($: EngineInterface, job: Job, signal?: AbortSignal
}
if (signal?.aborted) return 'cancelled'
- let segments = splitSegments(job.text, job.columns, job.env.inline ? inlineBudget(job.cell) : SEGMENT_ROWS, job.size)
+ const { rowPt } = sizing(job.columns, job.cell, fontFit(job.env.metrics, job.size).columnPt)
+ // The room height of a drawing in rows (less the pt rounding); unknown
+ // without a room (the default applies).
+ const roomRows = job.room ? Math.ceil(job.room.heightPt / rowPt - 0.01) : undefined
+ let segments = splitSegments(job.text, job.columns, job.env.inline ? inlineBudget(job.cell) : SEGMENT_ROWS, job.size, roomRows)
const base = job.base ?? job.env.cwd
const images = await existingImages($, segments, base)
await $.fs.write(`${dir}/doc.json`, JSON.stringify({ base, segments, images }))
@@ -419,7 +423,7 @@ export async function compile($: EngineInterface, job: Job, signal?: AbortSignal
// segment is cut in two and the whole text compiled once more. If that
// fails, the first pages stay (drawn at most MAX_IMAGE_ROWS tall).
if (pages.some(p => p.rows > MAX_IMAGE_ROWS)) {
- const cut = segments.flatMap((seg, i) => (pages![i]!.rows > MAX_IMAGE_ROWS ? splitInTwo(seg, job.columns, job.size) : [seg]))
+ const cut = segments.flatMap((seg, i) => (pages![i]!.rows > MAX_IMAGE_ROWS ? splitInTwo(seg, job.columns, job.size, roomRows) : [seg]))
if (cut.length > segments.length) {
if (signal?.aborted) return 'cancelled'
await $.fs.write(`${dir}/doc.json`, JSON.stringify({ base, segments: cut, images }))
@@ -433,7 +437,6 @@ export async function compile($: EngineInterface, job: Job, signal?: AbortSignal
}
pages = pages.map(p => ({ ...p, rows: Math.min(MAX_IMAGE_ROWS, p.rows) }))
}
- 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, bulletRow, ...(note ? { note } : {}) }
await $.fs.write(`${dir}/pages.json`, JSON.stringify(result))
diff --git a/hooks/register.tsx b/hooks/register.tsx
index 3797238..bc4e9ac 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -21,7 +21,8 @@ import { atom, read, update } from 'claude-code'
import type { EngineInterface, Register, RenderElement, RenderViewport } from 'claude-code'
import {
- DEFAULT_THEME, heightText, IMAGE_MAX_COLUMNS, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, READING_TOAST_MS, RESULTS_KEPT, TYPST_PROMPT, widthText,
+ DEFAULT_THEME, heightText, IMAGE_MAX_COLUMNS, MARGIN_TOP, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, READING_TOAST_MS, RESULTS_KEPT, TYPST_PROMPT,
+ widthText,
} from './lib/settings'
import { clip, drawnAnswers, editedPlans, keep, queue, refresh, running, S, subagentPlans, writesLive, type Env } from './lib/state'
import { beginEpoch } from './lib/epoch'
@@ -33,14 +34,14 @@ import { pollHost, PROBE_RUNS, probeOsc11, showMode, USE_OSC11, watchHost } from
import { measureFonts } from './lib/typst'
import { drawPages } from './lib/draw'
import { finalizeAll } from './lib/stream'
-import { isProbed, noteDrawn, noteDrawnAgain, wordsOf } from './lib/probe'
-import { codePointsOf, decodeSelection, hasPlaceholders, joinSegments, pickPages, textOfRun, type Pick, type Segment } from './lib/copy'
+import { isProbed, noteDrawn, noteDrawnAgain, noteOnScreen, wordsOf } from './lib/probe'
+import { codePointsOf, decodeSelection, hasPlaceholders, joinSegments, pageTopsOf, pickPages, textOfRun, type Pick, type Segment } from './lib/copy'
import { pagesOf, type Drawing } from './lib/answer'
import { setUp } from './lib/env'
import { frameFor, noteView, stopWatch, watchFrame, watchState } from './lib/frame'
import { roomColumns } from './lib/terminal'
import { onScreenOf, pastedImagePath, pastedNumbers, sentFiles } from './lib/images'
-import { pasteDir, sentOf, shownOf, underRow, type Shown, type Under } from './lib/pictures'
+import { pasteDir, rowsAfter, sentOf, shownOf, underRow, type Shown, type Under } from './lib/pictures'
import {
currentPlan, decidePlan, decisionOf, drawAskLine, drawPlanResult, drawPlanUse, isPlanQuestion, planFileOf, planInputOf, planOf,
planShownOf, scheduleClear, type PlanVerdict,
@@ -368,6 +369,17 @@ async function grab($: EngineInterface): Promise<string> {
: `Intelligent UI: the copy failed: ${copied.reason}.`
}
+// For dump: the rows of a pick's message on screen and its page's top row
+// there (pageTopsOf), which chose the page.
+function screenText(pick: { id: string; page: number }): string {
+ const d = drawnAnswers.get(pick.id)
+ if (!d || d.onScreen === undefined) return ' (rows on screen not known)'
+ if (d.onScreen === null) return ' (off screen)'
+ const tops = pageTopsOf(d)
+ const top = tops ? `page top ${tops[pick.page]}` : 'page tops not known'
+ return ` (rows ${d.onScreen.first}-${d.onScreen.last} of ${d.onScreen.of} on screen, ${top})`
+}
+
// /iui dump: the last placeholder text seen, as code points, how it was
// read, and the same in full in <cache>/copy-debug.json. `on`: Intelligent
// UI is on.
@@ -380,7 +392,7 @@ async function dump($: EngineInterface, on: boolean): Promise<string> {
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'}`
+ return `run rows ${rows} -> ${pick ? `answer ${pick.id} page ${pick.page}${screenText(pick)}` : 'no page fits'}`
})
.join('\n')
const cache = S.env?.cache ?? ''
@@ -620,15 +632,24 @@ export const register: Register = on => {
const onScreen = onScreenOf(e.props.onScreen)
const k = { text: e.props.text, extra: bullet ? 'bullet' : '', stamp: stampOf(ready, e.viewport), onScreen }
const kept = memoOf(answers, e.requestId, k)
+ // Its pages are under the top margin (drawPages); the rows on screen at
+ // each draw, a memo hit too.
+ const at = { top: MARGIN_TOP }
if (kept) {
- noteCopy($, () => noteDrawnAgain(e.requestId, roomColumns(e.viewport)))
+ noteCopy($, () => {
+ noteDrawnAgain(e.requestId, roomColumns(e.viewport), at)
+ noteOnScreen(e.requestId, e.props.onScreen)
+ })
return kept
}
const drawing = await pagesOf($, { id: e.requestId, text: e.props.text, frame: frameFor(e.viewport), env: ready.env, canStream: true, onScreen })
if (drawing.kind === 'pages') {
const tree = drawPages($, e, drawing.result, drawing.bytes, { bullet })
const { result } = drawing
- noteCopy($, () => noteDrawn(e.requestId, result, roomColumns(e.viewport)))
+ noteCopy($, () => {
+ noteDrawn(e.requestId, result, roomColumns(e.viewport), at)
+ noteOnScreen(e.requestId, e.props.onScreen)
+ })
memoSet(answers, e.requestId, k, tree)
return tree
}
@@ -656,18 +677,31 @@ export const register: Register = on => {
const k = { text: files.map(f => `${f.kind}:${f.path}`).join('\n'), extra: '', stamp: stampOf(ready, e.viewport), onScreen }
// Its jobs: one per Markdown file (pagesOf's id `file:<id>:<path>`).
const kept = memoOf(unders, id, k, requestId => requestId.startsWith(`file:${id}:`))
+ // Each Markdown file's pages with the rows drawn after them (rowsAfter)
+ // and the row's rows on screen, at each draw.
+ const room = roomColumns(e.viewport)
if (kept) {
under = kept
- for (const u of under) if ('drawing' in u) noteCopy($, () => noteDrawnAgain(u.id, roomColumns(e.viewport)))
+ kept.forEach((u, i) => {
+ if (!('drawing' in u)) return
+ noteCopy($, () => {
+ noteDrawnAgain(u.id, room, { after: rowsAfter(kept, i, room) })
+ noteOnScreen(u.id, e.props.onScreen)
+ })
+ })
} else {
under = await sentOf($, e, { ready: ready.env, markdown, files, id, at: { done: ready.done, row: e.requestId } })
if (under.length && under.every(u => !('drawing' in u) || u.drawing.kind === 'pages')) memoSet(unders, id, k, under)
else unders.delete(id)
- for (const u of under) {
- if (!('drawing' in u) || u.drawing.kind !== 'pages') continue
+ const drawn = under
+ drawn.forEach((u, i) => {
+ if (!('drawing' in u) || u.drawing.kind !== 'pages') return
const { result } = u.drawing
- noteCopy($, () => noteDrawn(u.id, result, roomColumns(e.viewport)))
- }
+ noteCopy($, () => {
+ noteDrawn(u.id, result, room, { after: rowsAfter(drawn, i, room) })
+ noteOnScreen(u.id, e.props.onScreen)
+ })
+ })
}
}
} catch {
@@ -735,10 +769,15 @@ export const register: Register = on => {
if (!ready) return row
const drawing = await planDrawing($, e, e.props.tool_use_id, plan, ready)
// Its pages can be copied as an answer's, by the call's id (the row's
- // requestId can be an answer's own).
+ // requestId can be an answer's own). The engine's row is above them:
+ // their place is read from the bottom (pageTopsOf).
if (drawing.kind === 'pages') {
const { result } = drawing
- noteCopy($, () => noteDrawn(`plan:${e.props.tool_use_id}`, result, roomColumns(e.viewport)))
+ const id = `plan:${e.props.tool_use_id}`
+ noteCopy($, () => {
+ noteDrawn(id, result, roomColumns(e.viewport))
+ noteOnScreen(id, e.props.onScreen)
+ })
}
return drawPlanUse($, e, row, drawing)
} catch {
diff --git a/tests/copy.test.ts b/tests/copy.test.ts
index 344cae4..30dc5dd 100644
--- a/tests/copy.test.ts
+++ b/tests/copy.test.ts
@@ -1,10 +1,12 @@
import { expect, mock, test } from 'claude-code/testing'
import {
- codePointsOf, commandSuggestions, decodeSelection, DIACRITICS, hasPlaceholders, isDrawnIn, joinSegments, parseCommand, pickPages, placeholderCell,
- isSafePage, positionsOf, textOfRun, WATCH_PL, type Drawn, type TextBlock, type Item, type Mark,
+ codePointsOf, commandSuggestions, decodeSelection, DIACRITICS, hasPlaceholders, isDrawnIn, joinSegments, pageTopsOf, parseCommand, pickPages,
+ placeholderCell, isSafePage, positionsOf, screenOf, textOfRun, WATCH_PL, type Drawn, type TextBlock, type Item, type Mark, type OnScreen,
+ type Place,
} from '../hooks/register'
import { WATCH_RESTART_MS } from '../hooks/lib/frame'
+import { rowsAfter, type Under } from '../hooks/lib/pictures'
import { READING_TOAST_MS } from '../hooks/lib/settings'
import { LONG_MARKS, LONG_MD, LONG_PAGE, SMALL_MARKS, SMALL_MD, SMALL_PAGE, SMALL_PPI } from './copy-fixture'
@@ -147,6 +149,89 @@ test('a page drawn smaller than it was compiled for fits by its drawn box', () =
expect(pickPages(decodeSelection(cells(9, 0, 10)), [small])).toEqual([null])
})
+// ---- Which page: the rows on screen ----------------------------------------------
+
+// An answer under its top margin (1 row), with its message's rows on screen.
+const seen = (d: Drawn, onScreen: OnScreen | null | undefined, place: Place = { top: 1, below: 0 }): Drawn => ({ ...d, place, onScreen })
+// The answer of the bug: 2 pages of 40 and 42 rows at 212 columns (83 rows
+// with the margin); rows 5 and 6 fit both pages.
+const BUG = drawn('ans', 1, [40, 42], 212)
+const ROWS_5_6 = decodeSelection([cells(5, 0, 50), cells(6, 0, 50)].join('\n'))
+
+test('the rows on screen say which page a run is: the one of the two that is on screen', () => {
+ expect(pageTopsOf(seen(BUG, { first: 41, last: 82, of: 83 }))).toEqual([1, 41])
+ // Page 2 on screen (its rows 5 and 6 are message rows 46 and 47).
+ expect(pickPages(ROWS_5_6, [seen(BUG, { first: 41, last: 82, of: 83 })])).toEqual([{ id: 'ans', page: 1 }])
+ expect(pickPages(ROWS_5_6, [seen(BUG, { first: 30, last: 70, of: 83 })])).toEqual([{ id: 'ans', page: 1 }])
+ // Page 1 on screen.
+ expect(pickPages(ROWS_5_6, [seen(BUG, { first: 0, last: 40, of: 83 })])).toEqual([{ id: 'ans', page: 0 }])
+ // One selected row on screen is enough.
+ expect(pickPages(ROWS_5_6, [seen(BUG, { first: 47, last: 82, of: 83 })])).toEqual([{ id: 'ans', page: 1 }])
+ // The root's margin outside the rows counted: the pages from row 0.
+ expect(pageTopsOf(seen(BUG, { first: 40, last: 81, of: 82 }))).toEqual([0, 40])
+ expect(pickPages(ROWS_5_6, [seen(BUG, { first: 40, last: 81, of: 82 })])).toEqual([{ id: 'ans', page: 1 }])
+ // A Typst error line under the pages, and a plan or a sent file with the
+ // engine's row above (no top): the top from the bottom.
+ expect(pageTopsOf(seen(BUG, { first: 0, last: 9, of: 84 }, { top: 1, below: 1 }))).toEqual([1, 41])
+ expect(pageTopsOf(seen(BUG, { first: 0, last: 9, of: 90 }, { below: 0 }))).toEqual([8, 48])
+})
+
+test('with no rows on screen known, or of another layout, a run goes to the first page that fits, as before', () => {
+ expect(pickPages(ROWS_5_6, [BUG])).toEqual([{ id: 'ans', page: 0 }])
+ expect(pickPages(ROWS_5_6, [seen(BUG, undefined)])).toEqual([{ id: 'ans', page: 0 }])
+ // `of` of the row drawn as text before (too short or too tall for these pages).
+ for (const onScreen of [{ first: 10, last: 19, of: 20 }, { first: 41, last: 89, of: 90 }]) {
+ expect(pageTopsOf(seen(BUG, onScreen))).toBeUndefined()
+ expect(pickPages(ROWS_5_6, [seen(BUG, onScreen)])).toEqual([{ id: 'ans', page: 0 }])
+ }
+ // Rows on screen out of date (no page on screen fits): as before.
+ expect(pickPages(decodeSelection(cells(41, 0, 50)), [seen(BUG, { first: 0, last: 20, of: 83 })])).toEqual([{ id: 'ans', page: 1 }])
+ expect(pickPages(ROWS_5_6, [seen(BUG, null)])).toEqual([{ id: 'ans', page: 0 }])
+ expect(screenOf({ first: 1, last: 2, of: 3 })).toEqual({ first: 1, last: 2, of: 3 })
+ expect(screenOf(null)).toBeNull()
+ expect(screenOf(undefined)).toBeUndefined()
+ expect(screenOf({ first: 1 })).toBeUndefined()
+})
+
+test('a chain over the page break still goes to the two pages, with either part on screen', () => {
+ const chain = decodeSelection([cells(38, 0, 50), cells(39, 0, 50), cells(0, 0, 50), cells(1, 0, 50)].join('\n'))
+ const pages = [{ id: 'ans', page: 0 }, { id: 'ans', page: 1 }]
+ expect(pickPages(chain, [seen(BUG, { first: 20, last: 60, of: 83 })])).toEqual(pages)
+ expect(pickPages(chain, [seen(BUG, { first: 41, last: 82, of: 83 })])).toEqual(pages)
+ expect(pickPages(chain, [seen(BUG, { first: 0, last: 39, of: 83 })])).toEqual(pages)
+})
+
+test('two placements on screen (pages shorter than the viewport): the first is taken', () => {
+ const short = drawn('ans', 1, [10, 12])
+ expect(pickPages(decodeSelection([cells(2, 0, 50), cells(3, 0, 50)].join('\n')), [seen(short, { first: 0, last: 22, of: 23 })])).toEqual([
+ { id: 'ans', page: 0 },
+ ])
+})
+
+test('among placements on screen, the selection row first, then the newest', () => {
+ const page2 = { first: 41, last: 82, of: 83 }
+ const old = seen(drawn('old', 1, [40, 42], 212), page2)
+ const now = seen(drawn('new', 2, [40, 42], 212), page2)
+ expect(pickPages(ROWS_5_6, [old, now])).toEqual([{ id: 'new', page: 1 }])
+ expect(pickPages(ROWS_5_6, [old, now], 'old')).toEqual([{ id: 'old', page: 1 }])
+ // The newest off screen: the older one on screen.
+ expect(pickPages(ROWS_5_6, [old, seen(now, null)])).toEqual([{ id: 'old', page: 1 }])
+ // The newest with no rows on screen known keeps its first page, as before.
+ expect(pickPages(ROWS_5_6, [old, seen(now, undefined)])).toEqual([{ id: 'new', page: 0 }])
+ // The selection's row wins even off screen (its rows on screen out of date).
+ expect(pickPages(ROWS_5_6, [old, seen(now, null)], 'new')).toEqual([{ id: 'new', page: 0 }])
+})
+
+test("a sent file's pages have the rows of the pictures and files after it under them", () => {
+ const picture = { source: { file: '/p.png' }, columns: 20, rows: 7, alt: '' } as Under
+ const result = { pages: [{ file: '/a-1.png', width: 1600, height: 640, alt: '', columns: 100, rows: 20 }], bulletRow: 0, note: 'boom' }
+ const pages = { id: 'file:t:a.md', drawing: { kind: 'pages', result } } as Under
+ const blank = { id: 'file:t:b.md', drawing: { kind: 'blank' } } as Under
+ // At 50 columns the page draws 10 rows, and its error line 1.
+ expect(rowsAfter([pages, picture, blank, pages], 0, 50)).toBe(7 + 10 + 1)
+ expect(rowsAfter([pages, picture], 1, 50)).toBe(0)
+})
+
// ---- A real probe -----------------------------------------------------------
const REAL = positionsOf(SMALL_MARKS as unknown as Mark[], SMALL_PPI)
@@ -429,6 +514,35 @@ test('a copy over two pages of a long answer probes those two pages only', async
expect(w.copies[0]).toContain('Copy test')
})
+test('a copy goes to the page on screen: the rows on screen of the last draw (a memo hit) reach the pick and dump', async ($, on) => {
+ const w = world(on)
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const long = Array.from({ length: 240 }, (_, i) => `Paragraph ${i} with a few words in it.`).join('\n\n')
+ const ui = await drawAnswer($, w, 'ans-1', long)
+ const pages = (JSON.parse(w.files.get([...w.files.keys()].find(k => k.endsWith('/doc.json'))!)!) as { segments: string[] }).segments.length
+ expect(pages).toBeGreaterThan(2)
+ // 16 rows a page under the top margin: page 2 is rows 17 to 32.
+ const of = 1 + 16 * pages
+ const compiles = w.compiles.length
+ await ui.redraw({ ...props(long), onScreen: { first: 17, last: 32, of } })
+ await w.clock.settle()
+ expect(w.compiles.length).toBe(compiles)
+ const rows = [cells(2, 0, 97), cells(3, 0, 97)].join('\n')
+ w.copy(rows)
+ await w.clock.settle()
+ expect(w.queries.map(q => q.page)).toEqual(['2'])
+ expect(w.copies.length).toBe(1)
+ const dumped = await $.command.run({ command: 'iui', args: 'dump' } as any)
+ expect(dumped.text).toContain(`-> answer ans-1 page 1 (rows 17-32 of ${of} on screen, page top 17)`)
+ // Scrolled up to page 1: the same rows are page 1's.
+ await ui.redraw({ ...props(long), onScreen: { first: 0, last: 16, of } })
+ await w.clock.settle()
+ w.copy(rows)
+ await w.clock.settle()
+ expect(w.queries.map(q => q.page)).toEqual(['2', '1'])
+ expect(w.copies.length).toBe(2)
+})
+
test('positions are kept in memory: copies of the same page share one probe run, and a later copy runs none', async ($, on) => {
const w = world(on)
await $.command.run({ command: 'iui', args: '' } as any)
diff --git a/tests/pure.test.ts b/tests/pure.test.ts
index 5b12344..b1424d8 100644
--- a/tests/pure.test.ts
+++ b/tests/pure.test.ts
@@ -8,9 +8,10 @@ import {
GHOSTTY_DEFAULT_BG, ghosttyBackgroundOf, ghosttyThemePaths, ghosttyThemesOf, ghosttyValueOf, hexColorOf,
modeLine, modeOfColorFgBg, modeOfGnome, modeOfMacAppearance, resolveMode, settingOf,
BASE_THEME, DEFAULT_THEME, chooseTheme, isSyntaxPath, isThemeName, measureCall, pickThemes, renderKey, themeEntry, themeFiles, themeListing,
- needsRoom, nextJob, pageRowsOf, resultOf, roomInputs, splitInTwo,
+ needsRoom, nextJob, pageRowsOf, resultOf, roomInputs, rowsOfBlock, splitInTwo,
composeFrame, fitBox, pictureColumns, roomColumns, scaledBulletRow,
} from '../hooks/register'
+import { DRAWING_ROWS } from '../hooks/lib/settings'
import { wrapPid } from '../hooks/lib/typst'
const para = (i: number) => `Paragraph ${i} ${'word '.repeat(40)}`.trim()
@@ -70,6 +71,32 @@ test('a typst fence with blank lines inside stays whole', () => {
expect(segments.some(s => s.includes(body))).toBe(true)
})
+test('a typst fence counts as its room rows, not its source lines', () => {
+ const md = `Before\n\n${fence('typst', 200)}\n\nAfter`
+ expect(splitSegments(md, 80, undefined, 100, 24)).toEqual([md])
+ // Four drawings with text between them: one page, as they are drawn.
+ const four = Array.from({ length: 4 }, (_, i) => `${para(i)}\n\n${fence('typst', 60)}`).join('\n\n')
+ expect(splitSegments(four, 80, undefined, 100, 24)).toEqual([four])
+})
+
+test('the room rows given are used for a typst fence', () => {
+ const block = blocksOf(fence('typst', 200))[0]!
+ expect(rowsOfBlock(block, 80, 100, 40)).toBe(42)
+ // The margins follow the text size; the drawing does not.
+ expect(rowsOfBlock(block, 80, 200, 40)).toBe(44)
+ const md = `${fence('typst', 5)}\n\n${fence('typst', 5)}`
+ expect(splitSegments(md, 80, undefined, 100, 100).length).toBe(2)
+ expect(splitSegments(md, 80, undefined, 100, 24).length).toBe(1)
+})
+
+test('a typst fence without a room counts as DRAWING_ROWS', () => {
+ const block = blocksOf(fence('typst', 200))[0]!
+ expect(rowsOfBlock(block, 80)).toBe(DRAWING_ROWS + 2)
+ const md = `Before\n\n${fence('typst', 200)}\n\nAfter`
+ expect(splitSegments(md, 80)).toEqual(splitSegments(md, 80, undefined, 100, DRAWING_ROWS))
+ expect(splitInTwo(md, 80)).toEqual(splitInTwo(md, 80, 100, DRAWING_ROWS))
+})
+
test('an indented continuation never starts a segment', () => {
const md = Array.from({ length: 80 }, (_, i) => `- item ${i} ${'word '.repeat(30)}\n\n more of item ${i}`).join('\n\n')
for (const s of splitSegments(md, 80)) expect(/^\s/.test(s)).toBe(false)