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
Merge main into copy-from-picture: copy text from pictures on the new pipeline
razorback16c68865fe1b48
diff --cc README.mdindex a1f7e6b,41c3934..c5c76b1--- a/README.md+++ b/README.md@@@ -1,206 -1,89 +1,102 @@@- # md-preview+ <img alt="Introducing Intelligent UI" src="outcomes/samples/intelligent-ui.png" width="100%">- A Claude Code mod that draws Claude's answers as rendered Markdown pictures, with a look close to VS Code's Markdown preview. Claude can also put live Typst in an answer, for diagrams, charts and math.+ # Intelligent UI for Claude Code- Only the drawing changes. The saved answer stays Markdown.+ **Claude's answers, rendered.** Real Markdown, math, charts and diagrams, right in your terminal.- ## What it draws+ <sub>An independent, community-made mod for Claude Code. Not affiliated with Anthropic.</sub>- - Headings, lists, task lists, tables, block quotes, links, footnotes and horizontal rules- - Code blocks with syntax colours, in your terminal's font (found for iTerm2, Ghostty, kitty and Rio; else Menlo, SF Mono or DejaVu Sans Mono)- - Math (`$…$` and `$$…$$`, LaTeX syntax, through mitex)- - Images from ``. A relative path starts from the session's folder. Remote images show as an alt-text box.- - Live Typst: a fenced block with the language `typst` (or `typ`) is rendered, not shown as code. These packages are in the mod and work offline:+ Intelligent UI draws each answer from Claude as a typeset picture, with [Typst](https://typst.app). Tables line up, equations look like a paper, and Claude can draw a chart or a diagram when a picture explains more than words. Only the drawing changes. The saved answer stays Markdown.- ```- #import "@preview/cetz:0.5.2"- #import "@preview/cetz-plot:0.1.4": plot, chart- #import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge- ```+ - A `theme` dictionary (`theme.fg`, `theme.muted`, `theme.blue`, `theme.palette`, `theme.width`, …) is in scope, so drawings match the terminal's colours. The mod tells Claude about this in a short part of the system prompt.- - Files that Claude sends to you (the SendUserFile tool). The mod draws each file under the row that shows the files, in the same order:- - PNG, JPEG and WebP images. Typst changes a JPEG or WebP image into a PNG image in the cache folder. It does this one time for each version of the file. The long side of that PNG image is 4096 pixels or less.- - Markdown files (`.md` or `.markdown`, 256 KiB or less). The mod draws the file as rendered pictures, the same as an answer. A relative image path in the file starts from the folder of the file.+ ## Why- Other files stay as the normal row. JPEG images, WebP images and Markdown files need Typst.- - Images that you paste into the prompt (`[Image #N]`). The mod draws each image under your prompt.+ - **Rendered Markdown.** Headings, tables, task lists, block quotes and code with syntax colours, in your terminal's own font.+ - **LaTeX math.** Inline `$…$` and display `$$…$$` math, typeset.+ - **Live diagrams, charts and plots.** Claude writes Typst with CeTZ, cetz-plot and fletcher. The drawings use your theme's colours and work offline.+ - **Images and files.** Images in an answer, images that Claude sends, Markdown files that Claude sends, and images that you paste show in the transcript.+ - **Plans you can read.** In plan mode, the plan shows rendered, with an approve, edit or reject question under it.+ - **Themes that follow light and dark.** Claude Code's own colours by default, or VS Code's Markdown preview. You can make your own.- These pictures are not larger than the image. They are not wider than the transcript, and not taller than 24 rows or half the screen. The mod draws PNG, JPEG and WebP images only. Other image types (for example GIF and SVG) stay as the normal row.- - The plan in plan mode (the ExitPlanMode tool). The mod draws the plan as a picture in the transcript, the same as an answer. Then the mod asks you to approve the plan. Refer to [Plan approval](#plan-approval).+ ## See it- ## Requirements+ <table>+ <tr>+ <td width="50%">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="outcomes/out/6-diagrams-dark.png">+ <source media="(prefers-color-scheme: light)" srcset="outcomes/out/6-diagrams-light.png">+ <img alt="A flow chart of an agent loop and a commutative diagram of the First Isomorphism Theorem, drawn with fletcher in a Claude answer" src="outcomes/out/6-diagrams-light.png" width="100%">+ </picture>+ </td>+ <td width="50%">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="outcomes/out/2-math-dark.png">+ <source media="(prefers-color-scheme: light)" srcset="outcomes/out/2-math-light.png">+ <img alt="Typeset LaTeX math in Claude Code: the Gaussian integral, Maxwell's equations, a rotation matrix and a piecewise function" src="outcomes/out/2-math-light.png" width="100%">+ </picture>+ </td>+ </tr>+ </table>- - Claude Code 2.1.301 or later (tested on 2.1.301)- - [Typst](https://typst.app) 0.15 (tested on 0.15.1)- - macOS (tested). Linux can work, but it is not tested.- - A terminal where Claude Code draws pictures:- - **kitty (0.28 or later) and Ghostty:** pictures work with no setting.- - **iTerm2 3.6 or later (3.7.5 tested):** Claude Code needs `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` when it starts. A mod cannot set it early enough. The first time the mod runs in iTerm2, it asks to add one line to your shell's start file (`~/.zshrc`, `~/.bash_profile` or a fish `conf.d` file). The line sets the variable in iTerm2 only, not in tmux or screen. Then close the tab, open a new iTerm2 tab, and start Claude Code there. You can also run `/md-preview setup` (undo: `/md-preview setup remove`).- - **Rio 0.5.27 or later (not tested):** set `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` before you start Claude Code.- - Do not put the variable in the `env` of `~/.claude/settings.json`. It then applies in every terminal, also where pictures cannot show.- - **Not supported:** WezTerm, Warp and Konsole do not draw kitty pictures with Unicode placeholders, so they show no pictures, also with the variable set. Alacritty, Terminal.app, Windows Terminal, GNOME Terminal (and other VTE terminals), foot, VS Code, Tabby, Hyper and JetBrains terminals have no kitty pictures.- - **tmux and screen:** no pictures. Claude Code does not send pictures through tmux or screen, also with the variable set. Set `MD_PREVIEW_FORCE=1` to try anyway.- - **ssh:** pictures work when the terminal on your computer is kitty or Ghostty (`TERM` must come through ssh), or when you set `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` on the remote computer. The mod sends each picture as data, because the terminal cannot read files on the remote computer. A page larger than 4096 pixels on a side or 2 MiB shows as text. An image of that size does not show.- - Background sessions (agent view, forks, `claude attach`) cannot draw pictures.+ More in the [gallery](docs/gallery.md): plots, fractals and a tour of all the Markdown.- Where pictures cannot draw, the mod shows the normal text.+ ## Quick start- ## Install-You need Claude Code 2.1.301 or later, [Typst](https://typst.app) 0.15, macOS, and kitty, Ghostty or iTerm2 (iTerm2 needs a one-time `/iui setup`). Refer to [Install](docs/install.md) for all terminals.++You need Claude Code 2.1.301 or later, [Typst](https://typst.app) 0.15 and macOS. The pictures show only in some terminals:+- 1. Install Typst: `brew install typst` (or see [Typst's install page](https://github.com/typst/typst#installation)).- 2. At the prompt of a Claude Code session in the terminal, type:++| Terminal | Pictures | What to do |++|---|---|---|++| kitty 0.28+, Ghostty, cmux | Yes | Nothing |++| iTerm2 3.6+ | Yes | Run `/iui setup` one time |++| Rio 0.5.27+ | Yes (not tested) | Set `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` |++| ssh | Yes, from kitty or Ghostty | Refer to [Install](docs/install.md#terminals) |++| tmux, screen | No | — |++| WezTerm, Warp, Konsole, Terminal.app, Alacritty, VS Code, Windows Terminal, GNOME Terminal, others | No | — |+- ```- /plugin install md-preview --marketplace razorback16/claude-md-preview- ```++In other terminals, the mod shows the normal text. Refer to [Install](docs/install.md#terminals) for all the details, and run `/iui details` to see why pictures do or do not show.- Answer `y` to add the marketplace, then push Enter to install for your user. The mod starts at once, with no restart.+ ```+ brew install typst+ ```- From a shell:+ Then, in Claude Code:```- claude plugin install md-preview --marketplace razorback16/claude-md-preview+ /plugin install intelligent-ui --marketplace razorback16/claude-intelligent-ui```- To try it from a clone without installing: `claude --plugin-dir /path/to/claude-md-preview`.+ It works at once, with no restart.- ## Use+ ## Commands| Command | What it does ||---|---|- | `/md-preview` | Shows the state, the text size and the terminal font that the mod found |- | `/md-preview on` / `off` | Turns the pictures on or off (kept for later sessions) |- | `/md-preview setup` / `setup remove` | iTerm2: adds or removes the shell line that turns pictures on (then close the tab and open a new one) |- | `/md-preview size <80–200>` | Text size in percent. 100 is the same visual size as your terminal text. |- | `/md-preview theme` | Lists the themes, shows which one is in use, and shows the folder for your own themes |- | `/md-preview theme <name>` | Changes to that theme (kept for later sessions) |- | `/md-preview grab` | Copies the text under your last mouse selection of pictures |- | `/md-preview dump` | Shows the last clipboard text with picture cells and how the mod read it (for a bug report) |-- ### Copy text from a picture-- Select the text in a picture (an answer or a plan) with the mouse, as you do with normal text. The selection puts picture cells on the clipboard. On macOS, the mod reads the clipboard every 0.3 s. When the clipboard has picture cells, the mod replaces them with the text under your selection, and a toast shows the number of characters. Wait approximately 0.3 s after you select, then paste. The mod does not change a clipboard that has no picture cells.-- If the clipboard did not change, use `/md-preview grab`. It reads Claude Code's last mouse selection (fullscreen mode only) and copies its text. If the copied text is not correct, `/md-preview dump` shows the cells that the mod found and the page that it used. It also writes all of this to `copy-debug.json` in the cache folder.-- ### Plan approval-- When Claude exits plan mode, the mod draws the plan as a picture in the transcript. Under the picture, the mod shows its own question, "Approve this plan?", in place of the Claude Code dialog. A dim line above the question tells you that the rendered plan is above. The question has these options:-- | Option | What it does |- |---|---|- | Yes, auto-accept edits | Approves the plan. Claude Code then accepts file edits with no question (`acceptEdits` mode). |- | Yes, manually approve edits | Approves the plan. Claude Code then asks you before each file edit (`default` mode). |- | Yes, clear context + auto-accept | Approves the plan, stops the turn and runs `/clear`. Then the mod sends "Implement this plan:" and the plan as a new prompt, in `acceptEdits` mode. |- | Edit the plan | Opens the plan file in an editor. The mod waits until you close the file (10 minutes at most). Then it asks "Approve the edited plan?". When you approve, Claude gets the edited plan. |- | Type something | Sends your text to Claude as changes to the plan. Claude stays in plan mode and writes a new plan. |- | Esc | Rejects the plan and stops the turn. |-- The editor is VS Code (`code --wait`) when the `code` command is on your PATH. If `code` is not on the PATH, macOS uses TextEdit (`open -W -t`). In that case, quit TextEdit when you complete the edit. Over ssh and on Linux with no `code` command, the "Edit the plan" option does not show.-- The mod shows the plan file as it is when the question opens. Claude can write the plan file and exit plan mode in the same message. Then Claude Code sends the plan from before that write. In this case, the mod waits for the write to complete (5 seconds at most) and reads the file again. You approve the plan that you see, and Claude gets that plan.-- The mod uses this flow only when it can draw the plan: the mod is on, Typst is installed, the terminal draws pictures, and the plan is from the main conversation (not from a subagent). In all other conditions, Claude Code shows its own dialog, as with no mod. If the flow fails, Claude Code also shows its own dialog.-- ## Themes-- A theme sets the colours, fonts and spacing of the picture. Two themes are in the mod:-- | Name | Looks like |- |---|---|- | `vscode-modern` (default) | VS Code's Markdown preview with Dark Modern / Light Modern |- | `vscode` | The same, with the Dark+ / Light+ colours |-- Each theme has a dark and a light part. The mod uses the part that agrees with Claude Code's theme.-- ### Make your own theme-- 1. Make a folder: `~/.claude/md-preview/themes/<name>/`.- 2. Put a `theme.json` in it. Write only the keys that you change. The mod merges your file over the base theme, `vscode` (not over the default, `vscode-modern`).- 3. Run `/md-preview theme <name>`. You do not have to restart.-- Example: pink inline code with rounder boxes.-- ```json- {- "name": "Pink code",- "dark": { "inline-code-fg": "#ff79c6", "inline-code-bg": "#ff79c626" },- "light": { "inline-code-fg": "#c2185b" },- "inline-code": { "radius-px": 8 }- }- ```-- - A user theme with the same folder name as a built-in theme is used in its place. It is still merged over the built-in `vscode`.- - Colours are `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`. The picture has no background, so a translucent colour (for example `#ffffff1a`) looks correct on all terminal colours.- - A value of the wrong type is ignored, and the `vscode` value is used. If the file is not valid JSON, the theme is skipped, the default theme is used, and `/md-preview theme` tells you why.- - For your own syntax colours, put TextMate theme files in the folder and name them: `"syntax": { "dark": "dark.tmTheme", "light": "light.tmTheme" }`. A file that you name must exist.-- All keys, their units and their defaults are in [`render/themes/README.md`](render/themes/README.md).-- The `vscode` and `vscode-modern` values come from VS Code (MIT licence, Copyright (c) 2015 - present Microsoft Corporation). The `LICENSE` file is in each of those folders.-- ## How it works-- 1. A `ui.render` hook on `AssistantMessage` gets each block of the answer as Markdown.- 2. While Claude writes a block, the block is hidden. The block is final when the model request starts its next block (a tool call, more text) or ends. If the mod did not see the request, the block is final after its text stops changing for 400 ms. Then the mod writes the block to a JSON file and runs `typst compile` with `render/md.typ`. Long answers are cut at block boundaries into pages. One page is one PNG.- 3. The hook draws one `Image` per PNG, in place of the text.- 4. Text size: the mod finds the terminal font (iTerm2 profile, Ghostty, kitty or Rio config, else Menlo metrics) and the cell size in pixels. Typst then measures both fonts so that 100% looks as large as the terminal text.- 5. If a compile fails (a bad Typst block or an unknown LaTeX command), the mod compiles once more in safe mode: Typst blocks and math show as code. A dim line under the picture names the error. If that also fails, the normal text shows.- 6. Pictures are kept in `${TMPDIR}/md-preview-<uid>/`. Folders older than 2 days are deleted at start.- 7. The plan: a `ui.render` hook on the ExitPlanMode `ToolUse` row draws the plan through the same steps. Claude Code shows that row above the approval question. The approved result row then shows only its header, so the plan does not show two times. A `tool.call` hook on ExitPlanMode asks the mod's question (`$.ui.ask`) before Claude Code asks for permission. Then a `classic.PermissionRequest` hook gives the answer to Claude Code at once, so the Claude Code dialog does not show. For an approval, the hook sends the plan (`updatedInput`) and the new permission mode (`setMode`). For the person's text, the `tool.call` hook refuses the call with that text.- 8. Copy: after the PNGs, the mod runs `typst query` with `probe=1` on the same template. The probe gives the position of each word and each code line, and the mod keeps these positions in `positions.json` beside the pages. The PNGs do not change. On macOS, a timer reads the clipboard with `pbpaste`. A picture cell holds its row and its column (kitty placeholder U+10EEEE plus two combining marks). The mod finds the drawn page that has these rows, takes the words in the selected cells, and writes the text with `$.ui.copy`.-- ### How `auto` is resolved-- Claude Code finds the light or dark mode for `auto` by asking the terminal for its background colour (OSC 11). A mod cannot see that answer, so md-preview uses these sources, in this order. The first source that gives an answer is used:-- 1. **The iTerm2 profile:** the background colour of the profile in use (`ITERM_PROFILE`, else the default profile). md-preview finds iTerm2 by `TERM_PROGRAM`. If `TERM_PROGRAM` is not set, `ITERM_PROFILE`, `ITERM_SESSION_ID` or `LC_TERMINAL=iTerm2` also show iTerm2. If the profile has separate colours for light and dark mode, md-preview uses the set for iTerm2's theme (Settings > Appearance). If that theme is Automatic, Minimal or Compact, it uses the set for the OS appearance.- 2. **The Ghostty config:** the `background` that `ghostty +show-config` gives. With a `theme = light:A,dark:B`, md-preview reads the background from the theme file for the OS appearance. With no theme and no `background`, it uses Ghostty's default (`#282c34`, dark).- - **cmux** (Ghostty inside, found by its `CMUX_*` variables) reads the same Ghostty config. If that config sets no `theme`, `background`, `foreground` or `palette`, cmux uses its adaptive default theme. md-preview then uses cmux's appearance: `app.appearance` in `~/.config/cmux/cmux.json`, else the value in cmux's Settings. If that appearance is System, md-preview uses the OS appearance. If `terminal.adaptiveDefaultTheme` is `false` in `cmux.json`, md-preview uses the Ghostty rules above.- 3. **The kitty config:** the `background` in `kitty.conf` and in the files that it includes (`include` lines only). The themes kitten writes such an include. If the config folder has `dark-theme.auto.conf`, `light-theme.auto.conf` or `no-preference-theme.auto.conf` (kitty 0.38 and later), md-preview uses the file for the OS appearance, as kitty does. With no `background`, it uses kitty's default (`#000000`, dark). The config folder is `KITTY_CONFIG_DIRECTORY`. If that is not set, it is the first of `$XDG_CONFIG_HOME/kitty`, `~/.config/kitty` and (on macOS) `~/Library/Preferences/kitty` that has a `kitty.conf`.- 4. **The Rio config:** `config.toml` in `RIO_CONFIG_HOME`, else in `~/.config/rio` (on Linux, `$XDG_CONFIG_HOME/rio` if that is set). With an `[adaptive-theme]`, md-preview reads the theme file for `force-theme`, else for the OS appearance. Else it reads the file for `theme`, else the `[colors] background`. Theme files are in the `themes` folder. With no background, it uses Rio's default (`#0F0D0E`, dark).- 5. **`COLORFGBG`**, as it was when Claude Code started. Ghostty does not set it.- 6. **The OS appearance:** macOS Dark or Light, or GNOME's `color-scheme` on Linux.- 7. **Dark.**-- The terminal comes before the OS: a dark terminal on a light Mac is dark.-- md-preview checks every 3 s. After a change, each mode's pictures compile once. `/md-preview probe` asks the terminal for its background with OSC 11 (5 times) and shows the raw answers. This is a test of whether the answer can reach the mod. The 3 s check does not use OSC 11 yet.-- ## Limitations-- - **Copying text from a picture** (see [Copy text from a picture](#copy-text-from-a-picture)) has these limits:- - The automatic copy works only on macOS, and not over ssh (`pbpaste` reads the clipboard of the computer that runs Claude Code). On other systems, the clipboard keeps the picture cells. Use `/md-preview grab`, Claude Code's `/copy` (the last answer as Markdown, `/copy 2` for the one before it), or turn the mod off (`/md-preview off`) to select text.- - The mod copies whole words. It copies a word when the selection covers the middle of the word. In a code block, it copies each character whose middle is in the selection.- - The mod does not copy math or the text in an image.- - The cells do not identify the answer. The mod uses the answer of the selected row if it knows it, else the newest answer whose pages fit the selection. A selection in one page of a long answer fits each page that is tall enough, and the mod uses the first one. Thus the text can come from a different page or an older answer of the same width. `/md-preview dump` shows the page that the mod used.- - To stop the clipboard write on select, set `copyOnSelect` to `false` in `/config`.- - **Search does not find text in a picture.**- - **While Claude writes**, the block is hidden, and Claude Code's spinner shows the progress. When the block is final, its picture shows after the compile (0.15–0.6 s). A long answer shows only when it is done. If the picture is not ready 2 s after the block is final, the normal text shows until the picture is ready. If the compile fails, the normal text stays. An earlier answer that is not in the cache (for example, after a resume) is blank for up to 1 s, then shows as text until its picture is ready.- - **Short summaries** between tool calls stay as text.- - **Plan approval:** a mod cannot draw the Claude Code approval dialog, so the mod shows its own question. That question can have 4 options at most. Thus it has no option to keep planning (use Type something or Esc). The edit option cannot use a terminal editor (vim, nano), because a mod has no terminal. Where an organization manages Claude Code, `classic.PermissionRequest` hooks of a plugin that you install do not run. Then the Claude Code dialog shows after the mod's question.- - **Typst blocks:** `#page`, `#pagebreak` and `#set page` are errors. A package that is not in the mod cannot be downloaded (the network is blocked for Typst), so its block shows as code.- - **Security:** Typst runs with `--root /`, so a Typst block can read any file that you can read and draw it in the picture. Nothing leaves the computer.- - **The look is close to VS Code, not exact:** Typst does not use CSS. Raw HTML in Markdown is shown in a simple form or dropped. Loose lists have tight spacing.- - **A picture that the terminal dropped from its image memory** (after many large pictures) is not sent again when you scroll back to it.- - **Over ssh**, the mod cannot read the terminal's config on your computer. So it uses Menlo metrics for the text size, and `auto` uses `COLORFGBG` if ssh sends it. Else `auto` is dark. The mod does not use the OS appearance of the remote computer. Pages are shorter, so that each one is at most 4096 pixels tall. In tmux or screen on the remote computer, no pictures show.- - **`auto` theme** reads the iTerm2 profile, the Ghostty, kitty and Rio configs, and the cmux settings directly. It does not read kitty's `globinclude`, `envinclude` and `geninclude` lines, or colours that you set while kitty runs. In other terminals, it uses `COLORFGBG` (set only when the terminal starts), then the OS appearance. If you change the theme of such a terminal and the OS appearance does not change, md-preview does not see it. A change shows after up to 3 s.-- ## Develop-- ```- git clone https://github.com/razorback16/claude-md-preview- cd claude-md-preview- claude --plugin-dir . # once: Claude Code writes the API types to .claude-plugin/types/- npx -p typescript tsc -p . # type check- claude plugin test . # tests- claude plugin validate .- ```-- `.claude-plugin/types/` is not in git. `tsconfig.json` extends the `tsconfig.json` in it, so run Claude Code with the folder once before `tsc`.-- The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile) `draw.tsx` (the pages of an answer), `answer.ts` (one text through the compile and cache steps) `plan.tsx` (the plan approval question and the plan rows) and `copy.ts` (the text under a mouse selection of pictures). The values that change are in one object, `S`, in `state.ts`. The tests import from `hooks/register.tsx`, which exports the names that they use.+ | `/iui` | Shows the state and a problem that keeps pictures away |+ | `/iui on` / `off` | Turns the pictures on or off |+ | `/iui theme <name>` | Changes the theme: `claude-code`, `vscode-modern`, `vscode` or your own |+ | `/iui size <80–200>` | Text size in percent of your terminal text |+ | `/iui details` | Shows the terminal, font, mode and Typst that the mod found |+ | `/iui setup` | iTerm2: adds the shell line that turns pictures on |++| `/iui grab` | Copies the text under your last mouse selection of pictures |++| `/iui dump` | Shows how the mod read the last clipboard with picture cells (for a bug report) |++ All commands are in [Usage](docs/usage.md).++ ## Docs++ - [Install](docs/install.md): requirements and terminal support-- [Usage](docs/usage.md): what it draws, commands, plan approval++- [Usage](docs/usage.md): what it draws, commands, copy, plan approval+ - [Themes](docs/themes.md): built-in themes and your own+ - [How it works](docs/how-it-works.md): the render steps and light or dark mode+ - [Limitations](docs/limitations.md): copy, search, timing and other limits+ - [Development](docs/development.md): build, test and module layout+ - [Gallery](docs/gallery.md): all the sample answers++ ## Disclaimer++ Intelligent UI is an independent project. It is not made, supported or endorsed by Anthropic. Claude and Claude Code are trademarks of Anthropic, PBC.## Licencediff --cc docs/development.mdindex 0000000,a68de6e..ef82312mode 000000,100644..100644--- a/docs/development.md+++ b/docs/development.md@@@ -1,0 -1,30 +1,30 @@@+ # Development++ ← Back to the [README](../README.md)++ ## Build and test++ ```+ git clone https://github.com/razorback16/claude-intelligent-ui+ cd claude-intelligent-ui+ claude --plugin-dir . # once: Claude Code writes the API types to .claude-plugin/types/+ npx -p typescript tsc -p . # type check+ claude plugin test . # tests+ claude plugin validate .+ ```++ `.claude-plugin/types/` is not in git. `tsconfig.json` extends the `tsconfig.json` in it, so run Claude Code with the folder once before `tsc`.++ ## Debug log++ Set `IUI_DEBUG=1` before you start Claude Code. The mod then writes trace lines to `debug.log` in the cache folder (`${TMPDIR}/intelligent-ui-<uid>/`).++ ## Module layout+-The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile), `draw.tsx` (the pages of an answer), `answer.ts` (one text through the compile and cache steps) and `plan.tsx` (the plan approval question and the plan rows). The values that change are in one object, `S`, in `state.ts`. The tests import from `hooks/register.tsx`, which exports the names that they use.++The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile), `draw.tsx` (the pages of an answer), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `copy.ts` (the text under a mouse selection of pictures) and `probe.ts` (the drawn pages and the probe that finds their words). The values that change are in one object, `S`, in `state.ts`. The tests import from `hooks/register.tsx`, which exports the names that they use.++ The Typst template is `render/md.typ`. The themes are in `render/themes/` (refer to [`render/themes/README.md`](../render/themes/README.md)). The vendored Typst packages are in `render/packages/preview/`.++ ## Marketing images++ `outcomes/build.sh` renders the samples in `outcomes/samples/` and frames them into the images in `outcomes/out/`. Refer to the [Gallery](gallery.md).diff --cc docs/how-it-works.mdindex 0000000,ea4ab7e..904e2a1mode 000000,100644..100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@@ -1,0 -1,30 +1,31 @@@+ # How it works++ ← Back to the [README](../README.md)++ ## The steps++ 1. A `ui.render` hook on `AssistantMessage` gets each block of the answer as Markdown.+ 2. While Claude writes a block, the block is hidden. The block is final when the model request starts its next block (a tool call, more text) or ends. If the mod did not see the request, the block is final after its text stops changing for 400 ms. Then the mod writes the block to a JSON file and runs `typst compile` with `render/md.typ`. Long answers are cut at block boundaries into pages. One page is one PNG.+ 3. The hook draws one `Image` per PNG, in place of the text.+ 4. Text size: the mod finds the terminal font (iTerm2 profile, Ghostty, kitty or Rio config, else Menlo metrics) and the cell size in pixels. Typst then measures both fonts so that 100% looks as large as the terminal text.+ 5. If a compile fails (a bad Typst block or an unknown LaTeX command), the mod compiles once more in safe mode: Typst blocks and math show as code. A dim line under the picture names the error. If that also fails, the normal text shows.+ 6. Pictures are kept in `${TMPDIR}/intelligent-ui-<uid>/`. Folders older than 2 days are deleted at start. The drawing space of each answer at its first compile is kept in `~/.cache/intelligent-ui/designs`, so that its Typst drawings keep the same share of the screen in later sessions.+ 7. The plan: a `ui.render` hook on the ExitPlanMode `ToolUse` row draws the plan through the same steps. Claude Code shows that row above the approval question. The approved result row then shows only its header, so the plan does not show two times. A `tool.call` hook on ExitPlanMode asks the mod's question (`$.ui.ask`) before Claude Code asks for permission. Then a `classic.PermissionRequest` hook gives the answer to Claude Code at once, so the Claude Code dialog does not show. For an approval, the hook sends the plan (`updatedInput`) and the new permission mode (`setMode`). For the person's text, the `tool.call` hook refuses the call with that text.++8. Copy: each compile also writes `probe.json` beside the pages. It has the same Typst inputs as the PNG compile, plus `probe=1`. It does not start a process. The probe (`typst query` on the same template with `probe=1`) gives the position of each word and each code line. It runs when a copy needs the positions, or before: one probe at a time, only when no compile runs or waits and no new size is in progress. A new compile stops it. The mod keeps the positions in `positions.json` beside the pages. The PNGs do not change. On macOS, a timer reads the mouse selection (`$.ui.selection`) and then the clipboard (`pbpaste`). It runs only while the mod is on and has drawn a picture in this session. A picture cell holds its row and its column (kitty placeholder U+10EEEE plus two combining marks). The mod finds the drawn page that has these rows, at the size that it is drawn, takes the words in the selected cells, and writes the text with `$.ui.copy`. A `ui.copy` hook also changes a copy with picture cells to the text.++ ## How `auto` is resolved++ Claude Code finds the light or dark mode for `auto` by asking the terminal for its background colour (OSC 11). A mod cannot see that answer, so Intelligent UI uses these sources, in this order. The first source that gives an answer is used:++ 1. **The iTerm2 profile:** the background colour of the profile in use (`ITERM_PROFILE`, else the default profile). Intelligent UI finds iTerm2 by `TERM_PROGRAM`. If `TERM_PROGRAM` is not set, `ITERM_PROFILE`, `ITERM_SESSION_ID` or `LC_TERMINAL=iTerm2` also show iTerm2. If the profile has separate colours for light and dark mode, Intelligent UI uses the set for iTerm2's theme (Settings > Appearance). If that theme is Automatic, Minimal or Compact, it uses the set for the OS appearance.+ 2. **The Ghostty config:** the `background` that `ghostty +show-config` gives. With a `theme = light:A,dark:B`, Intelligent UI reads the background from the theme file for the OS appearance. With no theme and no `background`, it uses Ghostty's default (`#282c34`, dark).+ - **cmux** (Ghostty inside, found by its `CMUX_*` variables) reads the same Ghostty config. If that config sets no `theme`, `background`, `foreground` or `palette`, cmux uses its adaptive default theme. Intelligent UI then uses cmux's appearance: `app.appearance` in `~/.config/cmux/cmux.json`, else the value in cmux's Settings. If that appearance is System, Intelligent UI uses the OS appearance. If `terminal.adaptiveDefaultTheme` is `false` in `cmux.json`, Intelligent UI uses the Ghostty rules above.+ 3. **The kitty config:** the `background` in `kitty.conf` and in the files that it includes (`include` lines only). The themes kitten writes such an include. If the config folder has `dark-theme.auto.conf`, `light-theme.auto.conf` or `no-preference-theme.auto.conf` (kitty 0.38 and later), Intelligent UI uses the file for the OS appearance, as kitty does. With no `background`, it uses kitty's default (`#000000`, dark). The config folder is `KITTY_CONFIG_DIRECTORY`. If that is not set, it is the first of `$XDG_CONFIG_HOME/kitty`, `~/.config/kitty` and (on macOS) `~/Library/Preferences/kitty` that has a `kitty.conf`.+ 4. **The Rio config:** `config.toml` in `RIO_CONFIG_HOME`, else in `~/.config/rio` (on Linux, `$XDG_CONFIG_HOME/rio` if that is set). With an `[adaptive-theme]`, Intelligent UI reads the theme file for `force-theme`, else for the OS appearance. Else it reads the file for `theme`, else the `[colors] background`. Theme files are in the `themes` folder. With no background, it uses Rio's default (`#0F0D0E`, dark).+ 5. **`COLORFGBG`**, as it was when Claude Code started. Ghostty does not set it.+ 6. **The OS appearance:** macOS Dark or Light, or GNOME's `color-scheme` on Linux.+ 7. **Dark.**++ The terminal comes before the OS: a dark terminal on a light Mac is dark.++ Intelligent UI checks every 3 s. After a change, each mode's pictures compile once. `/iui probe` asks the terminal for its background with OSC 11 (5 times) and shows the raw answers. This is a test of whether the answer can reach the mod. The 3 s check does not use OSC 11 yet.diff --cc docs/install.mdindex 0000000,c6aebcd..f8ed4f1mode 000000,100644..100644--- a/docs/install.md+++ b/docs/install.md@@@ -1,0 -1,49 +1,49 @@@+ # Install++ ← Back to the [README](../README.md)++ ## Requirements++ - Claude Code 2.1.301 or later (tested on 2.1.301)+ - [Typst](https://typst.app) 0.15 (tested on 0.15.1)+ - macOS (tested). Linux can work, but it is not tested.+ - A terminal where Claude Code draws pictures. Refer to [Terminals](#terminals).++ ## Terminals+-- **kitty (0.28 or later) and Ghostty:** pictures work with no setting.++- **kitty (0.28 or later), Ghostty and cmux (Ghostty inside):** pictures work with no setting.+ - **iTerm2 3.6 or later (3.7.5 tested):** Claude Code needs `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` when it starts. A mod cannot set it early enough. The first time the mod runs in iTerm2, it asks to add one line to your shell's start file (`~/.zshrc`, `~/.bash_profile` or a fish `conf.d` file). The line sets the variable in iTerm2 only, not in tmux or screen. Then close the tab, open a new iTerm2 tab, and start Claude Code there. You can also run `/iui setup` (undo: `/iui setup remove`).+ - **Rio 0.5.27 or later (not tested):** set `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` before you start Claude Code.+ - Do not put the variable in the `env` of `~/.claude/settings.json`. It then applies in every terminal, also where pictures cannot show.+ - **Not supported:** WezTerm, Warp and Konsole do not draw kitty pictures with Unicode placeholders, so they show no pictures, also with the variable set. Alacritty, Terminal.app, Windows Terminal, GNOME Terminal (and other VTE terminals), foot, VS Code, Tabby, Hyper and JetBrains terminals have no kitty pictures.+ - **tmux and screen:** no pictures. Claude Code does not send pictures through tmux or screen, also with the variable set. Set `IUI_FORCE=1` to try anyway.+ - **ssh:** pictures work when the terminal on your computer is kitty or Ghostty (`TERM` must come through ssh), or when you set `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` on the remote computer. The mod sends each picture as data, because the terminal cannot read files on the remote computer. A page larger than 4096 pixels on a side or 2 MiB shows as text. An image of that size does not show.+ - Background sessions (agent view, forks, `claude attach`) cannot draw pictures.++ Where pictures cannot draw, the mod shows the normal text. To see why a terminal can or cannot show pictures, run `/iui details`.++ ## Install steps++ 1. Install Typst: `brew install typst` (or see [Typst's install page](https://github.com/typst/typst#installation)).+ 2. At the prompt of a Claude Code session in the terminal, type:++ ```+ /plugin install intelligent-ui --marketplace razorback16/claude-intelligent-ui+ ```++ Answer `y` to add the marketplace, then push Enter to install for your user. The mod starts at once, with no restart.++ From a shell:++ ```+ claude plugin install intelligent-ui --marketplace razorback16/claude-intelligent-ui+ ```++ ## Try it from a clone++ To try it from a clone without installing:++ ```+ git clone https://github.com/razorback16/claude-intelligent-ui+ claude --plugin-dir /path/to/claude-intelligent-ui+ ```diff --cc docs/limitations.mdindex 0000000,c1b30d5..2176151mode 000000,100644..100644--- a/docs/limitations.md+++ b/docs/limitations.md@@@ -1,0 -1,15 +1,22 @@@+ # Limitations++ ← Back to the [README](../README.md)+-- **Copying text from a picture does not work.** A picture fills its cells with kitty placeholder characters (U+10EEEE plus combining marks). Claude Code's mouse selection copies those cells directly to the clipboard, and no mod hook runs before that copy. So a paste gives strange characters, not the text. Use Claude Code's `/copy` to copy the last answer as Markdown (`/copy 2` for the one before it; it shows a picker for the full answer or one code block, unless "Skip the /copy picker" is on in `/config`), or turn the mod off (`/iui off`) to select text. To stop the clipboard write on select, set `copyOnSelect` to `false` in `/config`.++- **Copying text from a picture** (refer to [Copy text from a picture](usage.md#copy-text-from-a-picture)) has these limits:++ - The automatic copy works only on macOS, and not over ssh (`pbpaste` reads the clipboard of the computer that runs Claude Code). On other systems, the clipboard keeps the picture cells (U+10EEEE plus combining marks), and a paste gives strange characters. Use `/iui grab`, Claude Code's `/copy` (the last answer as Markdown, `/copy 2` for the one before it), or turn the mod off (`/iui off`) to select text.++ - The mod copies whole words. It copies a word when the selection covers the middle of the word. In a code block, in a long word (30 characters or more, for example a path or a URL) and in CJK text, it copies each character whose middle is in the selection.++ - The mod does not copy math, the text in an image, or the text in a Typst drawing.++ - The cells do not identify the answer. The mod uses the answer of the selected row if it knows it, else the newest answer whose pages fit the selection. A selection in one page of a long answer fits each page that is tall enough, and the mod uses the first one. Thus the text can come from a different page or an older answer of the same width. `/iui dump` shows the page that the mod used.++ - The mod knows only the last 64 answers, plans or files that it drew in this session.++ - With two Claude Code sessions on one computer, a session that has no selection can change a copy from the other session, with the text of its own picture.++ - To stop the clipboard write on select, set `copyOnSelect` to `false` in `/config`. Then the mod does not copy a selection either. It changes only a clipboard that has picture cells (for example, after a copy with a key).+ - **Search does not find text in a picture.**+ - **While Claude writes**, the block is hidden, and Claude Code's spinner shows the progress. When the block is final, its picture shows after the compile (0.15–0.6 s). A long answer shows only when it is done. If the picture is not ready 2 s after the block is final, the normal text shows until the picture is ready. If the compile fails, the normal text stays. An earlier answer that is not in the cache (for example, after a resume) is blank for up to 1 s, then shows as text until its picture is ready.+ - **Short summaries** between tool calls stay as text.+ - **Plan approval:** a mod cannot draw the Claude Code approval dialog, so the mod shows its own question. That question can have 4 options at most. Thus it has no option to keep planning (use Type something or Esc). The edit option cannot use a terminal editor (vim, nano), because a mod has no terminal. Where an organization manages Claude Code, `classic.PermissionRequest` hooks of a plugin that you install do not run. Then the Claude Code dialog shows after the mod's question.+ - **Typst blocks:** `#page`, `#pagebreak` and `#set page` are errors. A package that is not in the mod cannot be downloaded (the network is blocked for Typst), so its block shows as code.+ - **Security:** Typst runs with `--root /`, so a Typst block can read any file that you can read and draw it in the picture. Nothing leaves the computer.+ - **The look is close to VS Code, not exact:** Typst does not use CSS. Raw HTML in Markdown is shown in a simple form or dropped. Loose lists have tight spacing.+ - **A picture that the terminal dropped from its image memory** (after many large pictures) is not sent again when you scroll back to it.+ - **Over ssh**, the mod cannot read the terminal's config on your computer. So it uses Menlo metrics for the text size, and `auto` uses `COLORFGBG` if ssh sends it. Else `auto` is dark. The mod does not use the OS appearance of the remote computer. Pages are shorter, so that each one is at most 4096 pixels tall. In tmux or screen on the remote computer, no pictures show.+ - **`auto` theme** reads the iTerm2 profile, the Ghostty, kitty and Rio configs, and the cmux settings directly. It does not read kitty's `globinclude`, `envinclude` and `geninclude` lines, or colours that you set while kitty runs. In other terminals, it uses `COLORFGBG` (set only when the terminal starts), then the OS appearance. If you change the theme of such a terminal and the OS appearance does not change, Intelligent UI does not see it. A change shows after up to 3 s.diff --cc docs/usage.mdindex 0000000,5782090..3f9ce04mode 000000,100644..100644--- a/docs/usage.md+++ b/docs/usage.md@@@ -1,0 -1,71 +1,83 @@@+ # Usage++ ← Back to the [README](../README.md)++ Intelligent UI draws Claude's answers as rendered Markdown pictures. Only the drawing changes. The saved answer stays Markdown.++ ## What it draws++ - Headings, lists, task lists, tables, block quotes, links, footnotes and horizontal rules+ - Code blocks with syntax colours, in your terminal's font (found for iTerm2, Ghostty, kitty and Rio; else Menlo, SF Mono or DejaVu Sans Mono)+ - Math (`$…$` and `$$…$$`, LaTeX syntax, through mitex)+ - Images from ``. A relative path starts from the session's folder. Remote images show as an alt-text box.+ - Live Typst: a fenced block with the language `typst` (or `typ`) is rendered, not shown as code. These packages are in the mod and work offline:++ ```+ #import "@preview/cetz:0.5.2"+ #import "@preview/cetz-plot:0.1.4": plot, chart+ #import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge+ ```++ A `theme` dictionary (`theme.fg`, `theme.muted`, `theme.blue`, `theme.palette`, `theme.width`, …) is in scope, so drawings match the terminal's colours. The mod tells Claude about this in a short part of the system prompt. `theme.width` and `theme.height` give the space for a drawing. The mod keeps the size that a message had when it was drawn the first time. When the terminal size changes, the mod makes the drawings larger or smaller by the same amount.+ - Files that Claude sends to you (the SendUserFile tool). The mod draws each file under the row that shows the files, in the same order:+ - PNG, JPEG and WebP images. Typst changes a JPEG or WebP image into a PNG image in the cache folder. The PNG image is the size of the space for the picture in the transcript, or smaller. Typst does this one time for each version of the file and each size of the space. When the space changes, the mod shows the old PNG image until Typst makes the new one.+ - Markdown files (`.md` or `.markdown`, 256 KiB or less). The mod draws the file as rendered pictures, the same as an answer. A relative image path in the file starts from the folder of the file.++ Other files stay as the normal row. JPEG images, WebP images and Markdown files need Typst.+ - Images that you paste into the prompt (`[Image #N]`). The mod draws each image under your prompt.++ These pictures are not larger than the image. They are not wider than the transcript. The height setting (`/iui height`) sets the most rows that they can use (Typst drawings use it too): by default, half the screen and not more than 24 rows. The mod draws PNG, JPEG and WebP images only. Other image types (for example GIF and SVG) stay as the normal row.+ - The plan in plan mode (the ExitPlanMode tool). The mod draws the plan as a picture in the transcript, the same as an answer. Then the mod asks you to approve the plan. Refer to [Plan approval](#plan-approval).++ ## Commands++ | Command | What it does |+ |---|---|+ | `/iui` | Shows the state, the theme, the text size, the width and the image height, and a problem that keeps pictures away |+ | `/iui details` | Shows all that the mod found: where the mode comes from, the terminal font, the Typst path and why the terminal can or cannot show pictures |+ | `/iui on` / `off` | Turns the pictures on or off (kept for later sessions) |+ | `/iui setup` / `setup remove` | iTerm2: adds or removes the shell line that turns pictures on (then close the tab and open a new one) |+ | `/iui size <80–200>` | Text size in percent. 100 is the same visual size as your terminal text. |+ | `/iui width` | Shows the width: the most columns that a picture can use |+ | `/iui width <40–400>` | Sets the most columns that a picture can use (kept for later sessions) |+ | `/iui width full` | Pictures use the full width of the terminal, the same as the text of Claude Code (kept for later sessions). This is the default. A picture is never wider than 255 columns. |+ | `/iui height` | Shows the image height: the most rows that an image can use. This applies to images (sent or pasted) and to Typst drawings in answers. |+ | `/iui height half` | An image uses half the terminal height, from 6 to 24 rows (kept for later sessions). This is the default. |+ | `/iui height full` | An image uses the terminal height less 16 rows (kept for later sessions). The 16 rows are for the row of the file, the text around it and the prompt. |+ | `/iui height <6–200>` | Sets the most rows that an image can use (kept for later sessions). An image is never taller than with `full`. |+ | `/iui theme` | Lists the themes, shows which one is in use, and shows the folder for your own themes |+ | `/iui theme <name>` | Changes to that theme (kept for later sessions) |++| `/iui grab` | Copies the text under your last mouse selection of pictures. Refer to [Copy text from a picture](#copy-text-from-a-picture). |++| `/iui dump` | Shows the last clipboard text with picture cells and how the mod read it (for a bug report). It also writes this to `copy-debug.json` in the cache folder. |+ | `/iui probe` | Asks the terminal for its background colour with OSC 11 and shows the raw answers. Refer to [How `auto` is resolved](how-it-works.md#how-auto-is-resolved). |+++## Copy text from a picture++++Select the text in a picture (an answer, a plan or a Markdown file that Claude sent) with the mouse, as you do with normal text. The selection puts picture cells on the clipboard. On macOS, while the mod is on and has drawn a picture in this session, the mod reads the mouse selection and the clipboard every 0.3 s. When they have picture cells, the mod puts the text under your selection on the clipboard, and a toast shows the number of characters. In fullscreen mode, if this session has a selection, the mod changes the clipboard only when the clipboard holds that selection. Thus a copy from a different Claude Code session usually stays as it is. Wait approximately 0.3 s after you select, then paste. The mod does not change a clipboard that has no picture cells.++++The mod finds the position of each word when a copy needs it, or before, when no picture compiles. The first copy from a picture can thus take a short time more.++++If the clipboard did not change, use `/iui grab`. It reads the last mouse selection of Claude Code (fullscreen mode only) and copies its text. If the copied text is not correct, `/iui dump` shows the cells that the mod found and the page that it used. It also writes all of this to `copy-debug.json` in the cache folder.++++For the limits, refer to [Limitations](limitations.md).+++ ## Plan approval++ When Claude exits plan mode, the mod draws the plan as a picture in the transcript. Under the picture, the mod shows its own question, "Approve this plan?", in place of the Claude Code dialog. A dim line above the question tells you that the rendered plan is above. The question has these options:++ | Option | What it does |+ |---|---|+ | Yes, auto-accept edits | Approves the plan. Claude Code then accepts file edits with no question (`acceptEdits` mode). |+ | Yes, manually approve edits | Approves the plan. Claude Code then asks you before each file edit (`default` mode). |+ | Yes, clear context + auto-accept | Approves the plan, stops the turn and runs `/clear`. Then the mod sends "Implement this plan:" and the plan as a new prompt, in `acceptEdits` mode. |+ | Edit the plan | Opens the plan file in an editor. The mod waits until you close the file (10 minutes at most). Then it asks "Approve the edited plan?". When you approve, Claude gets the edited plan. |+ | Type something | Sends your text to Claude as changes to the plan. Claude stays in plan mode and writes a new plan. |+ | Esc | Rejects the plan and stops the turn. |++ The editor is VS Code (`code --wait`) when the `code` command is on your PATH. If `code` is not on the PATH, macOS uses TextEdit (`open -W -t`). In that case, quit TextEdit when you complete the edit. Over ssh and on Linux with no `code` command, the "Edit the plan" option does not show.++ The mod shows the plan file as it is when the question opens. Claude can write the plan file and exit plan mode in the same message. Then Claude Code sends the plan from before that write. In this case, the mod waits for the write to complete (5 seconds at most) and reads the file again. You approve the plan that you see, and Claude gets that plan.++ The mod uses this flow only when it can draw the plan: the mod is on, Typst is installed, the terminal draws pictures, and the plan is from the main conversation (not from a subagent). In all other conditions, Claude Code shows its own dialog, as with no mod. If the flow fails, Claude Code also shows its own dialog.++ For the limits of this flow, refer to [Limitations](limitations.md).diff --cc hooks/lib/command.tsindex 5672dd6,aacf6eb..092191c--- a/hooks/lib/command.ts+++ b/hooks/lib/command.ts@@@ -2,13 -2,20 +2,22 @@@// its registration.import type { EngineInterface } from 'claude-code'- import { DEFAULT_SIZE, MAX_SIZE, MIN_SIZE } from './settings'+ import {+ DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_WIDTH, IMAGE_MAX_COLUMNS, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, PICTURE_ROOM_ROWS,+ type Height, type Width,+ } from './settings'import { isThemeName, type ThemeInfo } from './themes'- // `/md-preview` arguments: on, off, size <80-200>, or nothing (show state).+ // `/iui` arguments: on, off, size <80-200>, width [40-400|full],-// height [6-200|half|full], details (all Intelligent UI found), or nothing (show state). A `width` or `height`-// with no value shows it.++// height [6-200|half|full], details (all Intelligent UI found), grab (copy++// the text of the last mouse selection of pictures), dump (how the last++// clipboard with picture cells was read), or nothing (show state). A `width`++// or `height` with no value shows it.export type Command =- | { kind: 'on' | 'off' | 'show' | 'probe' | 'grab' | 'dump' }- | { kind: 'on' | 'off' | 'show' | 'details' | 'probe' }++ | { kind: 'on' | 'off' | 'show' | 'details' | 'probe' | 'grab' | 'dump' }| { kind: 'size'; percent: number }+ | { kind: 'width'; width?: Width }+ | { kind: 'height'; height?: Height }| { kind: 'theme'; name?: string }| { kind: 'setup'; remove: boolean }| { kind: 'bad' }@@@ -21,7 -28,7 +30,9 @@@ export function parseCommand(args: striif (typed.length === 2 && isThemeName(typed[1]!)) return { kind: 'theme', name: typed[1]! }return { kind: 'bad' }}- if (words.length === 1 && (words[0] === 'on' || words[0] === 'off' || words[0] === 'probe' || words[0] === 'grab' || words[0] === 'dump')) return { kind: words[0] }- if (words.length === 1 && (words[0] === 'on' || words[0] === 'off' || words[0] === 'details' || words[0] === 'probe')) return { kind: words[0] }++ if (words.length === 1 && (words[0] === 'on' || words[0] === 'off' || words[0] === 'details' || words[0] === 'probe' || words[0] === 'grab' || words[0] === 'dump')) {++ return { kind: words[0] }++ }if (words[0] === 'setup' && words.length === 1) return { kind: 'setup', remove: false }if (words[0] === 'setup' && words.length === 2 && words[1] === 'remove') return { kind: 'setup', remove: true }if (words[0] === 'size' && words.length === 2 && /^\d+%?$/.test(words[1]!)) {@@@ -36,17 -55,21 +59,23 @@@ const SUBCOMMANDS ={ name: 'on', description: 'draw answers as pictures' },{ name: 'off', description: 'show answers as text' },{ name: 'size', description: `text size, ${MIN_SIZE}-${MAX_SIZE}%` },+ { name: 'width', description: `the most columns a picture takes, ${MIN_WIDTH}-${MAX_WIDTH} or full` },+ { name: 'height', description: `the most rows an image or a Typst drawing takes, ${MIN_HEIGHT}-${MAX_HEIGHT}, half or full` },{ name: 'theme', description: 'list the themes, or switch to one' },{ name: 'setup', description: 'iTerm2: add the shell line that turns pictures on' },+ { name: 'details', description: 'the mode source, the terminal font, Typst and the terminal' },+ { name: 'grab', description: 'copy the text of the pictures you last selected' },+ { name: 'dump', description: 'show what the clipboard held and how it was read' },] as constconst SIZES = [80, 90, 100, 110, 120, 125, 150, 175, 200]+ const WIDTHS: readonly Width[] = [80, 100, 120, 160, 200, 'full']+ const HEIGHTS: readonly Height[] = ['half', 'full', 12, 24, 36]- // Typeahead rows for `/md-preview` arguments: the word at the cursor (`token`,- // starting at `start` in `text`) completed as a subcommand, a theme name or a- // size. Right after `theme` or `size`, rows hold the word and its argument,- // since the typeahead asks only while a word is at the cursor.+ // Typeahead rows for `/iui` arguments: the word at the cursor (`token`,+ // starting at `start` in `text`) completed as a subcommand, a theme name, a+ // size, a width or a height. Right after `theme`, `size`, `width` or+ // `height`, rows hold the word and its argument, since the typeahead asks+ // only while a word is at the cursor.export type Suggestion = { text: string; label?: string; description?: string }export function commandSuggestions(text: string, token: string, start: number,@@@ -81,8 -125,8 +131,8 @@@// there after a hot reload too.export async function registerCommand($: EngineInterface) {await $.command.register({- name: 'md-preview',- description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), theme [name] (list or switch themes), grab (copy the selected pictures' text), dump (copy diagnostics)",- argumentHint: '[on|off|size <percent>|theme [name]|grab|dump]',+ name: 'iui',- description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), width [40-400|full] (the most columns a picture takes), height [6-200|half|full] (the most rows an image or a Typst drawing takes), theme [name] (list or switch themes)",- argumentHint: '[on|off|size <percent>|width [columns|full]|height [rows|half|full]|theme [name]]',++ description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), width [40-400|full] (the most columns a picture takes), height [6-200|half|full] (the most rows an image or a Typst drawing takes), theme [name] (list or switch themes), grab (copy the selected pictures' text), dump (copy diagnostics)",++ argumentHint: '[on|off|size <percent>|width [columns|full]|height [rows|half|full]|theme [name]|grab|dump]',}).catch(() => undefined)}diff --cc hooks/lib/copy.tsindex d12d05c,0000000..f9617f6mode 100644,000000..100644--- a/hooks/lib/copy.ts+++ b/hooks/lib/copy.ts@@@ -1,330 -1,0 +1,368 @@@+// Copy (pure): the text under a mouse selection of answer pictures.+//+// Claude Code draws an Image as kitty Unicode placeholders: each cell is+// U+10EEEE, then the diacritic of its row, then the diacritic of its column+// (indices into DIACRITICS; the image id is only in the cell's colour, so it+// never reaches the clipboard). A mouse copy puts those cells on the+// clipboard, one line per screen row. decodeSelection reads them back as+// runs of (row, columns) per picture; positionsOf turns the template's probe+// marks (render/md.typ, `<mdpos>`) into word boxes in PNG pixels; pickPages+// says which drawn page each run is; textOfRun reads the words under a run.- // The clipboard watcher and the commands are in register.tsx.++// The drawn pages and the probe runs are in probe.ts; the clipboard watcher++// and the commands are in register.tsx.++// kitty's rowcolumn-diacritics.txt: 297 combining marks; mark i means row or+// column i. (The same table is in Claude Code's binary.)+export const DIACRITICS: readonly number[] = [+ 0x0305, 0x030d, 0x030e, 0x0310, 0x0312, 0x033d, 0x033e, 0x033f, 0x0346, 0x034a, 0x034b, 0x034c,+ 0x0350, 0x0351, 0x0352, 0x0357, 0x035b, 0x0363, 0x0364, 0x0365, 0x0366, 0x0367, 0x0368, 0x0369,+ 0x036a, 0x036b, 0x036c, 0x036d, 0x036e, 0x036f, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487, 0x0592,+ 0x0593, 0x0594, 0x0595, 0x0597, 0x0598, 0x0599, 0x059c, 0x059d, 0x059e, 0x059f, 0x05a0, 0x05a1,+ 0x05a8, 0x05a9, 0x05ab, 0x05ac, 0x05af, 0x05c4, 0x0610, 0x0611, 0x0612, 0x0613, 0x0614, 0x0615,+ 0x0616, 0x0617, 0x0657, 0x0658, 0x0659, 0x065a, 0x065b, 0x065d, 0x065e, 0x06d6, 0x06d7, 0x06d8,+ 0x06d9, 0x06da, 0x06db, 0x06dc, 0x06df, 0x06e0, 0x06e1, 0x06e2, 0x06e4, 0x06e7, 0x06e8, 0x06eb,+ 0x06ec, 0x0730, 0x0732, 0x0733, 0x0735, 0x0736, 0x073a, 0x073d, 0x073f, 0x0740, 0x0741, 0x0743,+ 0x0745, 0x0747, 0x0749, 0x074a, 0x07eb, 0x07ec, 0x07ed, 0x07ee, 0x07ef, 0x07f0, 0x07f1, 0x07f3,+ 0x0816, 0x0817, 0x0818, 0x0819, 0x081b, 0x081c, 0x081d, 0x081e, 0x081f, 0x0820, 0x0821, 0x0822,+ 0x0823, 0x0825, 0x0826, 0x0827, 0x0829, 0x082a, 0x082b, 0x082c, 0x082d, 0x0951, 0x0953, 0x0954,+ 0x0f82, 0x0f83, 0x0f86, 0x0f87, 0x135d, 0x135e, 0x135f, 0x17dd, 0x193a, 0x1a17, 0x1a75, 0x1a76,+ 0x1a77, 0x1a78, 0x1a79, 0x1a7a, 0x1a7b, 0x1a7c, 0x1b6b, 0x1b6d, 0x1b6e, 0x1b6f, 0x1b70, 0x1b71,+ 0x1b72, 0x1b73, 0x1cd0, 0x1cd1, 0x1cd2, 0x1cda, 0x1cdb, 0x1ce0, 0x1dc0, 0x1dc1, 0x1dc3, 0x1dc4,+ 0x1dc5, 0x1dc6, 0x1dc7, 0x1dc8, 0x1dc9, 0x1dcb, 0x1dcc, 0x1dd1, 0x1dd2, 0x1dd3, 0x1dd4, 0x1dd5,+ 0x1dd6, 0x1dd7, 0x1dd8, 0x1dd9, 0x1dda, 0x1ddb, 0x1ddc, 0x1ddd, 0x1dde, 0x1ddf, 0x1de0, 0x1de1,+ 0x1de2, 0x1de3, 0x1de4, 0x1de5, 0x1de6, 0x1dfe, 0x20d0, 0x20d1, 0x20d4, 0x20d5, 0x20d6, 0x20d7,+ 0x20db, 0x20dc, 0x20e1, 0x20e7, 0x20e9, 0x20f0, 0x2cef, 0x2cf0, 0x2cf1, 0x2de0, 0x2de1, 0x2de2,+ 0x2de3, 0x2de4, 0x2de5, 0x2de6, 0x2de7, 0x2de8, 0x2de9, 0x2dea, 0x2deb, 0x2dec, 0x2ded, 0x2dee,+ 0x2def, 0x2df0, 0x2df1, 0x2df2, 0x2df3, 0x2df4, 0x2df5, 0x2df6, 0x2df7, 0x2df8, 0x2df9, 0x2dfa,+ 0x2dfb, 0x2dfc, 0x2dfd, 0x2dfe, 0x2dff, 0xa66f, 0xa67c, 0xa67d, 0xa6f0, 0xa6f1, 0xa8e0, 0xa8e1,+ 0xa8e2, 0xa8e3, 0xa8e4, 0xa8e5, 0xa8e6, 0xa8e7, 0xa8e8, 0xa8e9, 0xa8ea, 0xa8eb, 0xa8ec, 0xa8ed,+ 0xa8ee, 0xa8ef, 0xa8f0, 0xa8f1, 0xaab0, 0xaab2, 0xaab3, 0xaab7, 0xaab8, 0xaabe, 0xaabf, 0xaac1,+ 0xfe20, 0xfe21, 0xfe22, 0xfe23, 0xfe24, 0xfe25, 0xfe26, 0x10a0f, 0x10a38, 0x1d185, 0x1d186, 0x1d187,+ 0x1d188, 0x1d189, 0x1d1aa, 0x1d1ab, 0x1d1ac, 0x1d1ad, 0x1d242, 0x1d243, 0x1d244,+]+export const PLACEHOLDER = 0x10eeee+const INDEX = new Map(DIACRITICS.map((cp, i) => [cp, i]))++// The cell string Claude Code draws at (row, col): for the tests.+export const placeholderCell = (row: number, col: number) =>+ String.fromCodePoint(PLACEHOLDER, DIACRITICS[row]!, DIACRITICS[col]!)++export const hasPlaceholders = (text: string) => text.includes(String.fromCodePoint(PLACEHOLDER))++// One screen row of a picture in the selection: its row in the picture and+// the first and last picture columns selected (inclusive).+export type RunLine = { row: number; colStart: number; colEnd: number }+// The selection in order: plain text lines, and runs of picture rows (one+// picture's rows, top to bottom).+export type Segment = { kind: 'text'; text: string } | { kind: 'image'; lines: RunLine[] }++// The reply bullet and the gutter's spaces left of a picture.+const GUTTER = /^[\s⏺●]*$/++// The selection's text as segments. A run ends where a row does not follow+// the one above (the next picture, or the next page of the same answer,+// starts again at row 0) or where a line has no placeholder.+export function decodeSelection(text: string): Segment[] {+ const out: Segment[] = []+ let run: RunLine[] | null = null+ const addText = (line: string) => {+ run = null+ const last = out[out.length - 1]+ if (last?.kind === 'text') last.text += `\n${line}`+ else out.push({ kind: 'text', text: line })+ }+ for (const line of text.split(/\r?\n/)) {+ const cps = Array.from(line, c => c.codePointAt(0)!)+ const cells: { row: number; col: number }[] = []+ let other = ''+ for (let i = 0; i < cps.length; i++) {+ if (cps[i] !== PLACEHOLDER) {+ other += String.fromCodePoint(cps[i]!)+ continue+ }+ const row = INDEX.get(cps[i + 1] ?? -1)+ const col = INDEX.get(cps[i + 2] ?? -1)+ if (row === undefined) continue+ i += col === undefined ? 1 : 2+ // No column mark: the cell after the one before (kitty's rule).+ const prev = cells[cells.length - 1]+ cells.push({ row, col: col ?? (prev && prev.row === row ? prev.col + 1 : 0) })+ }+ if (!cells.length) {+ addText(line)+ continue+ }+ if (!GUTTER.test(other)) addText(other.trim())+ const row = cells[0]!.row+ const cols = cells.filter(c => c.row === row).map(c => c.col)+ const at: RunLine = { row, colStart: Math.min(...cols), colEnd: Math.max(...cols) }+ const open = run as RunLine[] | null+ if (open && open[open.length - 1]!.row < row) open.push(at)+ else {+ run = [at]+ out.push({ kind: 'image', lines: run })+ }+ }+ // A selection's last line break gives an empty last line: not text.+ const last = out[out.length - 1]+ if (last?.kind === 'text') {+ last.text = last.text.replace(/\n+$/, '')+ if (!last.text) out.pop()+ }+ return out+}++// ---- Where the words are ---------------------------------------------------++// A probe mark as `typst query <mdpos> --field value` gives it (pt).+export type Mark = {+ k: 'w' | 'c' | 'b'+ p: number+ x: number+ y: number+ s?: number+ t?: string+ w?: number+ h?: number+ n?: number+ a?: number+ d?: number+ kind?: string+ prefix?: string+ cx?: number++ g?: number+}+// A word, or a whole code line (`adv`: its character advance), in PNG+// pixels: its box, the block it is in, and its place in the document (`i`).- export type Item = { i: number; text: string; x0: number; y0: number; x1: number; y1: number; block: number; adv?: number }++// `glued`: a character of a long word or of CJK text after the first (it++// joins the one before with no space).++export type Item = { i: number; text: string; x0: number; y0: number; x1: number; y1: number; block: number; adv?: number; glued?: boolean }+// A block: paragraph, heading, code, quote, cell (`cx` its column), item+// (`prefix`); `first` its first item.+export type TextBlock = { kind: string; prefix: string; cx?: number; first: number }+// positions.json: by page (0-based: PNG page N+1).+export type Positions = { ppi: number; blocks: TextBlock[]; pages: Item[][] }++const round = (n: number) => Math.round(n * 100) / 100++// The break chances the template adds (a zws in a long word), the strut++// before inline code (a zwj) and other marks that draw nothing.++const INVISIBLE = /[\u200b-\u200d\u2060\ufeff]/g++++// A list's marker ("-", "1.") is drawn just before its item's mark: the++// item's prefix says it. It is the word before an item mark that is the++// prefix's first word, or that is left of the item's first word on its line++// (another theme's marker, a numbering of its own). The last word of a++// paragraph before a list is on a line above.++function isMarker(marks: readonly Mark[], j: number): boolean {++ const m = marks[j]!++ 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')++ return !!body && body.p === m.p && body.x > m.x && Math.abs(body.y - m.y) < (m.h ?? m.s ?? 11) / 2++}++// The probe's marks (document order) as boxes in pixels at `ppi`. A list's- // number ("1.") is drawn before its item's mark: it is dropped, the item's- // prefix says it. A block mark with no word since the last one (an item,- // then its paragraph) adds to that block.++// marker is dropped (isMarker). 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.+export function positionsOf(marks: readonly Mark[], ppi: number): Positions {+ const k = ppi / 72+ const blocks: TextBlock[] = []+ const pages: Item[][] = []+ let hasItems = false+ let count = 0+ marks.forEach((m, j) => {+ if (m.k === 'b') {+ const cur = blocks[blocks.length - 1]+ if (cur && !hasItems) {+ cur.prefix ||= m.prefix ?? ''+ if (m.kind === 'cell') Object.assign(cur, { kind: 'cell', cx: m.cx ?? 0 })+ else if (cur.kind !== 'item' && cur.kind !== 'cell') cur.kind = m.kind ?? cur.kind+ } else {+ blocks.push({ kind: m.kind ?? 'par', prefix: m.prefix ?? '', ...(m.kind === 'cell' ? { cx: m.cx ?? 0 } : {}), first: -1 })+ hasItems = false+ }+ return+ }- const next = marks[j + 1]- if (m.k === 'w' && next?.k === 'b' && next.kind === 'item' && next.prefix?.trim() === m.t) return++ if (isMarker(marks, j)) return+ if (!blocks.length) blocks.push({ kind: 'par', prefix: '', first: -1 })+ const block = blocks.length - 1+ const item: Item =+ m.k === 'c'+ ? {- i: count, text: m.t ?? '', block, x0: round(m.x * k), x1: round((m.x + (m.w ?? 0)) * k),++ i: count, text: (m.t ?? '').replace(INVISIBLE, ''), block, x0: round(m.x * k), x1: round((m.x + (m.w ?? 0)) * k),+ y0: round((m.y - (m.a ?? 0.8 * (m.s ?? 11))) * k), y1: round((m.y + (m.d ?? 0.25 * (m.s ?? 11))) * k),+ adv: m.n ? ((m.w ?? 0) * k) / m.n : 0,+ }- : { i: count, text: m.t ?? '', block, x0: round(m.x * k), x1: round((m.x + (m.w ?? 0)) * k), y0: round(m.y * k), y1: round((m.y + (m.h ?? m.s ?? 11)) * k) }++ : {++ i: count, text: (m.t ?? '').replace(INVISIBLE, ''), block, x0: round(m.x * k), x1: round((m.x + (m.w ?? 0)) * k),++ y0: round(m.y * k), y1: round((m.y + (m.h ?? m.s ?? 11)) * k), ...(m.g ? { glued: true } : {}),++ }+ if (!item.text) return+ count+++ if (!hasItems) blocks[block]!.first = item.i+ hasItems = true+ const page = Math.max(0, m.p - 1)+ while (pages.length <= page) pages.push([])+ pages[page]!.push(item)+ })+ return { ppi, blocks, pages }+}++// ---- Which page a run is ---------------------------------------------------+- // A page drawn this session: its PNG size and the rows its Image takes.- export type DrawnPage = { file: string; width: number; height: number; rows: number }- // An answer drawn this session (`seq` grows with each new one).- export type Drawn = { id: string; seq: number; columns: number; dir: string; pages: DrawnPage[] }++// A page drawn this session: its PNG size and the box its Image takes as++// 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 }++// 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[] }+export type Pick = { id: string; page: number } | null+++// 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.++export const isDrawnIn = (id: string, requestId: string) =>++ id === requestId || id === `plan:${requestId}` || id.startsWith(`file:${requestId}:`)+++// For each segment, the drawn page its run is (null: text, or none fits).+// Runs next to each other (no text between) are one picture after the other,+// so consecutive pages of one answer: a run that goes on in the next must+// end on its page's last row, and the next start at row 0. A chain is- // matched to the answer `requestId` names (the selection's transcript row)- // when it fits, else to the newest answer it fits. Ambiguous by nature: a++// 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.+export function pickPages(segments: readonly Segment[], drawn: readonly Drawn[], requestId?: string): Pick[] {+ const picks: Pick[] = segments.map(() => null)- const order = [...drawn].sort((a, b) => (a.id === requestId ? -1 : b.id === requestId ? 1 : b.seq - a.seq))++ 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)+ let i = 0+ while (i < segments.length) {+ if (segments[i]!.kind !== 'image') {+ i+++ continue+ }+ let j = i+ while (j < segments.length && segments[j]!.kind === 'image') j+++ const runs = segments.slice(i, j) as { kind: 'image'; lines: RunLine[] }[]+ const fits = (d: Drawn, start: number) =>+ runs.every((run, n) => {+ const page = d.pages[start + n]+ if (!page) return false+ const rows = run.lines.map(l => l.row)+ const maxRow = Math.max(...rows)+ const maxCol = Math.max(...run.lines.map(l => l.colEnd))- if (maxRow >= page.rows || maxCol >= d.columns) return false++ if (maxRow >= page.rows || maxCol >= page.columns) return false+ if (n > 0 && Math.min(...rows) !== 0) return false+ return n === runs.length - 1 || maxRow === page.rows - 1+ })+ found: for (const d of order) {+ for (let start = 0; start + runs.length <= d.pages.length; start++) {+ if (!fits(d, start)) continue+ runs.forEach((_, n) => (picks[i + n] = { id: d.id, page: start + n }))+ break found+ }+ }+ i = j+ }+ return picks+}++// ---- The text under a run --------------------------------------------------++// The words of one page under a run, in reading order. The picture fills- // `columns` x `rows` cells, so a cell is width / columns by height / rows- // PNG pixels. A word is under the run when its box's centre is in a selected++// its drawn box of `columns` x `rows` cells, so a cell is width / columns by++// height / rows PNG pixels (a page drawn smaller has larger cells). A word is under the run when its box's centre is in a selected+// cell (its row by the vertical centre, its column by the horizontal one):+// half a word selected copies the word when the selection covers its middle.+// A code line is cut by characters, each by its own centre.- export function textOfRun(lines: readonly RunLine[], items: readonly Item[], blocks: readonly TextBlock[], page: { width: number; height: number; rows: number }, columns: number): string {- const colW = page.width / columns++export function textOfRun(++ lines: readonly RunLine[], items: readonly Item[], blocks: readonly TextBlock[], page: { width: number; height: number; columns: number; rows: number },++): string {++ const colW = page.width / page.columns+ const rowH = page.height / page.rows+ const sel = new Map(lines.map(l => [l.row, l]))+ const picked: { item: Item; text: string }[] = []+ for (const item of items) {+ const line = sel.get(Math.floor((item.y0 + item.y1) / 2 / rowH))+ if (!line) continue+ const inside = (x: number) => {+ const col = Math.floor(x / colW)+ return col >= line.colStart && col <= line.colEnd+ }+ if (item.adv) {+ const chars = Array.from(item.text)+ const kept = chars.filter((_, c) => inside(item.x0 + (c + 0.5) * item.adv!))+ if (!kept.length) continue+ const first = chars.findIndex((_, c) => inside(item.x0 + (c + 0.5) * item.adv!))+ picked.push({ item, text: chars.slice(first, first + kept.length).join('') })+ } else if (inside((item.x0 + item.x1) / 2)) picked.push({ item, text: item.text })+ }+ return joinItems(picked, blocks)+}++// Joins picked words: a new line between blocks (a tab between the cells of+// a table row), a block's prefix when its first word is in, a new line+// between code lines; inside a block a space between words, none between+// the pieces of one word (boxes on one line closer than a fifth of the line- // height: a space is wider, the padding beside inline code narrower), none after a - or /- // that ends a line.++// height: a space is wider, the padding beside inline code narrower; none++// before a glued character that follows the one before it), none after a++// - or / that ends a line.+export function joinItems(picked: readonly { item: Item; text: string }[], blocks: readonly TextBlock[]): string {+ let out = ''+ let prev: { item: Item; text: string } | null = null+ const prefixOf = (item: Item) => {+ const b = blocks[item.block]+ return b?.prefix && b.first === item.i ? b.prefix : ''+ }+ for (const p of picked) {+ if (!prev) out += prefixOf(p.item)+ else if (p.item.block !== prev.item.block) {+ const b = blocks[p.item.block]+ const before = blocks[prev.item.block]+ out += b?.kind === 'cell' && (b.cx ?? 0) > 0 && before?.kind === 'cell' ? '\t' : '\n'+ out += prefixOf(p.item)+ } else if (p.item.adv !== undefined || prev.item.adv !== undefined) out += '\n'++ else if (p.item.glued && p.item.i === prev.item.i + 1) out += ''+ else {+ const height = p.item.y1 - p.item.y0+ const sameLine = Math.abs((p.item.y0 + p.item.y1) / 2 - (prev.item.y0 + prev.item.y1) / 2) < height / 2+ if (sameLine) out += p.item.x0 - prev.item.x1 > height * 0.2 ? ' ' : ''+ else out += /[-/]$/.test(prev.text) ? '' : ' '+ }+ out += p.text+ prev = p+ }+ return out+}++// The copy: text segments as they are, each run as its page's text (a run+// with no page, or no words, gives nothing), joined by new lines.+export function joinSegments(segments: readonly Segment[], texts: readonly (string | null)[]): string {+ return segments+ .map((s, i) => (s.kind === 'text' ? s.text : texts[i] ?? ''))+ .filter((t, i) => t !== '' || segments[i]!.kind === 'text')+ .join('\n')+}+- // For /md-preview dump: the first `max` cells or characters of the++// For /iui dump: the first `max` cells or characters of the+// text, a placeholder cell as `[r,c]`, other characters as U+XXXX.+export function codePointsOf(text: string, max = 40): string {+ const cps = Array.from(text, c => c.codePointAt(0)!)+ const out: string[] = []+ for (let i = 0; i < cps.length && out.length < max; i++) {+ const cp = cps[i]!+ if (cp === PLACEHOLDER) {+ const row = INDEX.get(cps[i + 1] ?? -1)+ const col = INDEX.get(cps[i + 2] ?? -1)+ out.push(`U+10EEEE[${row ?? '?'},${col ?? '?'}]`)+ i += (row === undefined ? 0 : 1) + (col === undefined ? 0 : 1)+ } else out.push(`U+${cp.toString(16).toUpperCase().padStart(4, '0')}`)+ }+ return out.join(' ')+}diff --cc hooks/lib/env.tsindex b3a9e55,bf400b0..a4614ff--- a/hooks/lib/env.ts+++ b/hooks/lib/env.ts@@@ -51,6 -58,6 +58,7 @@@ export function setUp($: EngineInterfacconst raw = rows.find(row => row.key === 'theme')?.valueS.settingRaw = typeof raw === 'string' ? raw : ''S.setting = settingOf(raw)++ S.copyOnSelect = rows.find(row => row.key === 'copyOnSelect')?.value !== falseS.hostOs = os.trim()S.termProgram = programS.termName = termdiff --cc hooks/lib/epoch.tsindex 0000000,fc31d3a..674ecafmode 000000,100644..100644--- a/hooks/lib/epoch.ts+++ b/hooks/lib/epoch.ts@@@ -1,0 -1,126 +1,131 @@@+ // The epoch: one for each new target (a settled resize, a font size change,+ // a setting, the light or dark mode). It stops the compiles of the old+ // target, and its pictures swap in all at once: a job of the open epoch that+ // ends does not redraw; the epoch commits (S.shown = S.frame, with the+ // height setting of the target, one redraw) when its jobs on screen are done. A burst (a drag not quiet yet) holds the-// jobs and the commit.++// jobs and the commit. An epoch begun stops the probe ahead (probe.ts); a++// commit, or a burst's end, arms it again.+ import type { EngineInterface } from 'claude-code'++ import { COMMIT_MAX_MS, COMMIT_MIN_MS } from './settings'+ import { converting, epochOpen, queue, refresh, running, S, type Frame, type Job } from './state'+ import { traceDebug } from './log'++import { probeLater, stopProbe } from './probe'++ // The open epoch: `ready` once COMMIT_MIN_MS passed with no new activity+ // (a row drawn, a job enqueued: extendEpoch), `overdue` once COMMIT_MAX_MS+ // passed since it began (it commits with jobs still running). A new epoch+ // has new flags and cancels the old timers.+ let ready = false+ let overdue = false+ let minTimer: { cancel: () => void } | null = null+ let maxTimer: { cancel: () => void } | null = null+ // For the trace: when the open epoch began, and the jobs enqueued in it.+ let begunAt = 0+ let jobsIn = 0++ // Begins a new epoch for `frame` (else the target now): stops every compile+ // that runs (it does not wait for them), empties the queue, sets the target+ // and redraws once. The rows draw their old pictures and enqueue the target.+ export function beginEpoch($: EngineInterface, frame?: Frame | null) {+ S.resizing = false+ S.missed = false+ const cancelled = running.size+ const dropped = queue.length+ for (const { cancel } of running.values()) {+ try {+ cancel()+ } catch {}+ }+ queue.length = 0++ stopProbe()+ const target = frame ?? S.frame+ if (target) S.frame = { ...target }+ const epoch = ++S.epoch+ begunAt = Date.now()+ jobsIn = 0+ const f = S.frame+ traceDebug($, `epoch ${epoch} begin: target ${f ? `${f.columns}x${f.rows} cell ${f.cell.width}x${f.cell.height}` : 'none'}; cancelled ${cancelled} running, dropped ${dropped} queued`)+ ready = false+ overdue = false+ maxTimer?.cancel()+ maxTimer = $.clock.after(COMMIT_MAX_MS, () => {+ if (S.epoch !== epoch) return+ overdue = true+ maybeCommit($)+ })+ armReady($)+ refresh($)+ }++ // The rows of the open epoch still come (each draws again after the+ // epoch's redraw, after round trips to the host): its COMMIT_MIN_MS starts+ // again, so a row drawn late still swaps at the commit. COMMIT_MAX_MS still+ // counts from the begin. Nothing once it is ready.+ export function extendEpoch($: EngineInterface) {+ if (epochOpen() && !ready) armReady($)+ }++ // A job was enqueued (for the trace).+ export function jobQueued(job: Job) {+ if (job.epoch === S.epoch && epochOpen()) jobsIn+++ }++ // (Re)starts the open epoch's COMMIT_MIN_MS timer.+ function armReady($: EngineInterface) {+ const epoch = S.epoch+ minTimer?.cancel()+ minTimer = $.clock.after(COMMIT_MIN_MS, () => {+ if (S.epoch !== epoch) return+ ready = true+ maybeCommit($)+ })+ }++ // A burst began: no job starts and the epoch does not commit until+ // releaseJobs.+ export function holdJobs() {+ S.resizing = true+ }++ // The burst ended with no new target: a job that ended during it redraws+ // now (with no epoch open), and a commit that came due happens now.+ export function releaseJobs($: EngineInterface) {+ S.resizing = false+ if (S.missed && !epochOpen()) refresh($)+ S.missed = false+ maybeCommit($)++ probeLater($)+ }++ // A job ended (its result is stored): during a burst it is noted; in an open+ // epoch the epoch may commit; else its row redraws.+ export function jobDone($: EngineInterface) {+ if (S.resizing) S.missed = true+ else if (epochOpen()) maybeCommit($)+ else refresh($)+ }++ // A job holds the commit when it is of the open epoch and its row is not+ // known to be off screen.+ const holds = (job: Job) => job.epoch === S.epoch && job.onScreen !== false++ // Commits the open epoch when no burst runs and it is overdue, or it is+ // ready and no job of it on screen waits or runs and no JPEG or WebP+ // converts.+ function maybeCommit($: EngineInterface) {+ if (S.resizing || !epochOpen()) return+ if (!overdue) {+ if (!ready || converting.size > 0 || queue.some(holds)) return+ for (const { job } of running.values()) if (holds(job)) return+ }+ if (S.debug) {+ const left = (jobs: Iterable<Job>) => [...jobs].filter(job => job.epoch === S.epoch).length+ traceDebug($, `epoch ${S.epoch} commit after ${Date.now() - begunAt} ms (${overdue ? 'overdue' : 'ready'}): ${jobsIn} jobs queued, ${left(queue)} waiting, ${left([...running.values()].map(r => r.job))} running, ${converting.size} converting`)+ }+ S.shown = S.frame+ S.shownHeight = S.height+ S.shownEpoch = S.epoch+ refresh($)++ probeLater($)+ }diff --cc hooks/lib/pictures.tsxindex cd8afb8,44ad87e..c95c09d--- a/hooks/lib/pictures.tsx+++ b/hooks/lib/pictures.tsx@@@ -17,14 -19,38 +19,38 @@@ import { frameFor, pictureColumns, showexport type Picture = { file: string; stamp: string; bytes: number; width: number; height: number }export type Shown = { source: ImageSource; columns: number; rows: number; alt: string }// What draws under a SendUserFile row: a picture, or a Markdown file's- // pages (`blank`: an empty space while they compile).- export type Under = Shown | { drawing: Exclude<Drawing, { kind: 'text' }>; columns: number }+ // pages (`blank`: an empty space while they compile; an older, wider page-// draws smaller to fit).-export type Under = Shown | { drawing: Exclude<Drawing, { kind: 'text' }> }++// draws smaller to fit) with its pagesOf id (a copy reads them by it).++export type Under = Shown | { drawing: Exclude<Drawing, { kind: 'text' }>; id: string }export type RowInput = RenderInput<'ToolResult' | 'UserMessage', 'terminal'>+ // Where a stat is read: the `done` value the row read and the row's+ // requestId. A row that draws again with no new `done` (a scroll step, a new+ // onScreen) reads each stat once; a new row (the same file sent again)+ // reads it anew. With none given, the file is stat'ed each time.+ export type StatAt = { done: number; row: string }+ const STATS_KEPT = 4096+ let statsDone: number | undefined+ const stats = new Map<string, Promise<FsStat | null>>()+ function statOf($: EngineInterface, file: string, at?: StatAt): Promise<FsStat | null> {+ if (!at) return $.fs.stat(file).catch(() => null)+ if (statsDone !== at.done || stats.size >= STATS_KEPT) {+ stats.clear()+ statsDone = at.done+ }+ const key = `${at.row}\n${file}`+ let got = stats.get(key)+ if (!got) {+ got = $.fs.stat(file).catch(() => null)+ stats.set(key, got)+ }+ return got+ }+// A PNG's pixel size from its first 24 bytes, read again only when its stat// changes; null for a file that is gone or not a PNG.- export async function pictureOf($: EngineInterface, file: string): Promise<Picture | null> {- const st = await $.fs.stat(file).catch(() => null)+ export async function pictureOf($: EngineInterface, file: string, at?: StatAt): Promise<Picture | null> {+ const st = await statOf($, file, at)if (!st || st.kind !== 'file') return nullconst stamp = `${st.mtimeMs}:${st.size}`let kept = pictures.get(file)@@@ -169,15 -223,22 +223,23 @@@ export async function sentOffor (const f of o.files) {const full = imagePathOf(f.path, o.ready.cwd)if (f.kind === 'markdown') {- const text = o.markdown ? await sentTextOf($, full) : null+ const text = o.markdown ? await sentTextOf($, full, o.at) : nullif (!o.markdown || !text) continue- const drawing = await pagesOf($, { id: `file:${o.id}:${f.path}`, text, columns, env: o.markdown, canStream: false, base: folderOf(full) })- if (drawing.kind !== 'text') under.push({ drawing, columns })++ const id = `file:${o.id}:${f.path}`+ const drawing = await pagesOf($, {- id: `file:${o.id}:${f.path}`, text, frame: frameFor(e.viewport), env: o.markdown, canStream: false, base: folderOf(full),++ id, text, frame: frameFor(e.viewport), env: o.markdown, canStream: false, base: folderOf(full),+ onScreen: onScreenOf(e.props.onScreen),+ })- if (drawing.kind !== 'text') under.push({ drawing })++ if (drawing.kind !== 'text') under.push({ drawing, id })continue}- const png = f.kind === 'png' ? full : await convertedOf($, o.ready, full)- const shown = png ? await shownOne($, e, o.ready, png, nameOf(full)) : null- if (shown) under.push(shown)+ if (f.kind !== 'png' && next && (next.width !== box.width || next.height !== box.height)) {+ void convertedOf($, o.ready, full, next, o.at).catch(() => null)+ if (!(await hasPngOf($, full, o.at))) continue+ }+ const png = f.kind === 'png' ? full : await convertedOf($, o.ready, full, box, o.at)+ const picture = png ? await shownOne($, e, o.ready, png, nameOf(full), o.at) : null+ if (picture) under.push(picture)}return under}diff --cc hooks/lib/probe.tsindex 0000000,0000000..9cb079cnew file mode 100644--- /dev/null+++ b/hooks/lib/probe.ts@@@ -1,0 -1,0 +1,144 @@@++// The pages a copy reads (copy.ts) and the words on them: each answer, plan++// and Markdown file Claude sent is noted as drawn (its pages at the box they++// are drawn at), and the probe (runProbe) makes a key folder's++// positions.json from its probe.json: at once when a copy needs it, else++// ahead, one at a time, only while nothing compiles, waits or is in an open++// epoch. A job enqueued or an epoch begun stops the probe ahead.++import type { EngineInterface } from 'claude-code'++++import { PROBE_AHEAD, PROBE_IDLE_MS } from './settings'++import { clip, DRAWN_KEPT, drawnAnswers, epochOpen, keep, lastKey, positionsByDir, queue, results, running, S, type Result } from './state'++import { fitBox } from './terminal'++import { runProbe, type ProbeJob } from './typst'++import { traceDebug } from './log'++import type { DrawnPage, Positions } from './copy'++++// Notes the pages of `id` as drawn now, each at fitBox(page, room), as++// drawPages draws it. A redraw with the same pages at the same boxes keeps++// its place, so `seq` is when it was first drawn so. A new one arms the++// probe ahead.++export function noteDrawn($: EngineInterface, id: string, result: Result, room: 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)++ const same = (p: DrawnPage, i: 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++ keep(drawnAnswers, id, { id, seq: ++clip.seq, dir, pages }, DRAWN_KEPT)++ probeLater($)++}++++// 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($: EngineInterface, id: string, room: number) {++ if (drawnAnswers.has(id)) return++ const result = results.get(lastKey.get(id)?.key ?? '')++ if (result && result !== 'failed') noteDrawn($, id, result, room)++}++++// ---- Positions ----------------------------------------------------------------++++// The probes that run now by folder: a copy of the same folder waits for++// it (and runs its own when it was cancelled).++const inflight = new Map<string, Promise<Positions | null | 'cancelled'>>()++// The probe ahead: its timer, and the run with its cancel. Folders whose++// probe failed are not probed ahead again (bounded: cleared when full).++let idleTimer: { cancel: () => void } | null = null++let idle: { dir: string; cancel: () => void } | null = null++const failed = new Set<string>()++++// A folder's positions: kept, positions.json, else the probe (probe.json).++async function load($: EngineInterface, dir: string, signal?: AbortSignal): Promise<Positions | null | 'cancelled'> {++ const kept = await $.fs.read(`${dir}/positions.json`).catch(() => null)++ try {++ const got = kept ? (JSON.parse(kept) as Positions) : null++ if (got && Array.isArray(got.pages) && Array.isArray(got.blocks)) return got++ } catch {}++ const job = await $.fs.read(`${dir}/probe.json`).catch(() => null)++ let probe: ProbeJob++ try {++ probe = JSON.parse(job ?? '') as ProbeJob++ if (!Array.isArray(probe.argv) || !(probe.ppi > 0)) return null++ } catch {++ return null++ }++ if (signal?.aborted) return 'cancelled'++ return runProbe($, dir, probe, signal)++}++++async function positionsRun($: EngineInterface, dir: string, signal?: AbortSignal): Promise<Positions | null | 'cancelled'> {++ const known = positionsByDir.get(dir)++ if (known) return known++ const ahead = inflight.get(dir)++ if (ahead) {++ const got = await ahead++ return got === 'cancelled' && !signal?.aborted ? positionsRun($, dir, signal) : got++ }++ const run = load($, dir, signal)++ inflight.set(dir, run)++ const got = await run.catch(() => null)++ if (inflight.get(dir) === run) inflight.delete(dir)++ if (got && got !== 'cancelled') keep(positionsByDir, dir, got, DRAWN_KEPT)++ return got++}++++// A folder's word positions for a copy, now; null when there are none.++export async function positionsFor($: EngineInterface, dir: string): Promise<Positions | null> {++ const got = await positionsRun($, dir)++ return got === 'cancelled' ? null : got++}++++// ---- The probe ahead ------------------------------------------------------------++++const isIdle = () => !S.resizing && !epochOpen() && !queue.length && !running.size++++// Arms the probe ahead: PROBE_IDLE_MS after the last call (a drawing noted,++// the last job ended, an epoch committed, a burst ended).++export function probeLater($: EngineInterface) {++ idleTimer?.cancel()++ idleTimer = $.clock.after(PROBE_IDLE_MS, () => {++ idleTimer = null++ probeNext($)++ })++}++++// Stops the probe ahead (a job enqueued, an epoch begun): its timer, and its++// run (killed; the folder is probed again later).++export function stopProbe() {++ idleTimer?.cancel()++ idleTimer = null++ idle?.cancel()++}++++// One probe ahead, while idle: the newest drawing (of the PROBE_AHEAD++// newest) with no positions yet; when it ends, the next one.++function probeNext($: EngineInterface) {++ if (idle || !isIdle()) return++ const next = [...drawnAnswers.values()]++ .sort((a, b) => b.seq - a.seq)++ .slice(0, PROBE_AHEAD)++ .find(d => d.dir && !positionsByDir.has(d.dir) && !failed.has(d.dir) && !inflight.has(d.dir))++ if (!next) return++ const controller = new AbortController()++ const entry = { dir: next.dir, cancel: () => controller.abort() }++ idle = entry++ void positionsRun($, next.dir, controller.signal)++ .catch(() => null)++ .then(got => {++ if (idle === entry) idle = null++ traceDebug($, `probe ahead ${next.dir}: ${got === 'cancelled' ? 'cancelled' : got ? 'done' : 'failed'}`)++ // Cancelled: again once idle (a job that ended meanwhile armed it while++ // this run held the slot).++ if (got === 'cancelled') {++ if (isIdle()) probeLater($)++ return++ }++ if (!got) {++ if (failed.size >= DRAWN_KEPT * 4) failed.clear()++ failed.add(next.dir)++ }++ probeNext($)++ })++}diff --cc hooks/lib/settings.tsindex cbb3494,87280ce..47d6a1e--- a/hooks/lib/settings.ts+++ b/hooks/lib/settings.ts@@@ -51,9 -64,6 +64,16 @@@ export const NO_NETWORK = 'http://127.0// how long one read may take.export const HOST_POLL_MS = 3000export const HOST_CHECK_MS = 2000+// How often the clipboard is read (macOS pbpaste) for a mouse copy of+// answer pictures.+export const CLIP_POLL_MS = 300++// The word positions of a drawn page (the probe, a `typst query`) are made++// when a copy needs them, or ahead: one probe at a time, once nothing has++// compiled, waited or drawn new for this long; ahead only for the++// PROBE_AHEAD newest drawings (the rows drawn last: after a resize, the++// ones on screen).++export const PROBE_IDLE_MS = 1000++export const PROBE_AHEAD = 8// The base every theme merges over (its theme.json and syntax files).export const BASE_THEME = 'vscode'// The theme used when none is chosen, or when the chosen one is not usable.diff --cc hooks/lib/state.tsindex 6650326,a1c7460..13e4427--- a/hooks/lib/state.ts+++ b/hooks/lib/state.ts@@@ -7,8 -7,7 +7,8 @@@ import type { IuiTheme } from '../../tyimport type { ThemeInfo } from './themes'import type { HostMode, ThemeSetting } from './mode'import type { PlanVerdict } from './plan'+import type { Drawn, Positions } from './copy'- import { DEFAULT_SIZE } from './settings'+ import { DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_WIDTH, type Height, type Width } from './settings'// The `done` atom (see types/index.d.ts) for refresh. The state scan of// `claude plugin validate` reads an atom only from a const in the file that@@@ -115,7 -167,8 +168,11 @@@ export const S =planVerdict: null as PlanVerdict | null,planAsking: '',planCode: null as string | null,++ // Claude Code's copyOnSelect setting (setUp, config.set): false, a mouse++ // selection is not copied, so the watcher does not copy it either.++ copyOnSelect: true,}+ // The compile results by key (an LRU: set with `keep` at RESULTS_KEPT).export const results = new Map<string, Result | 'failed'>()// Streaming: model requests of the main loop in flight (`S.stepsLive`), the// blocks drawn blank while their text streams (with the job to compile once@@@ -153,27 -215,17 +219,44 @@@ export const subagentPlans = new Set<st// waits for its file's).export const writesLive = new Map<string, number>()- // Redraws every reader of `done`; an invalidate where the write is refused.- export function refresh($: EngineInterface) {- void update($, done, n => n + 1).catch(() => $.ui.invalidate('ui.render'))- }-- // Copy: the answers drawn this session by their requestId (a plan by- // `plan:<tool_use_id>`; oldest first, at most DRAWN_KEPT), each answer- // folder's word positions once read, and the clipboard watcher's state: its- // timer and when it last ran, the clipboard text last seen and last written- // (so a write is never read back as new), the last text with placeholders- // and how it was read (for dump).++// Copy (copy.ts, probe.ts): the pages drawn this session by their id (an++// answer's requestId, `plan:<tool_use_id>`, `file:<tool_use_id>:<path>`;++// oldest first, at most DRAWN_KEPT), and each key folder's word positions++// once read (the oldest go past DRAWN_KEPT).+export const drawnAnswers = new Map<string, Drawn>()+export const DRAWN_KEPT = 64+export const positionsByDir = new Map<string, Positions>()++// The clipboard watcher (register.tsx): its timer and when it last ran,++// whether its first tick noted the selection there was (`seeded`), the++// clipboard text last seen and last written (so a write is never read back++// as new), the last selection handled, the last text with placeholders++// with its row (`rawRow`, when known) and how it was read (for dump), and++// the order of the drawings (`seq`).+export const clip = {+ watch: null as { cancel: () => void } | null,+ ticked: 0,++ seeded: false,+ busy: false,+ seen: '',+ wrote: '',++ selected: '',+ raw: '',++ rawRow: undefined as string | undefined,+ seq: 0,+ last: null as unknown,+}+++ // Sets a cache entry as the newest; the oldest go past `max`.+ export function keep<T>(cache: Map<string, T>, key: string, value: T, max: number) {+ cache.delete(key)+ cache.set(key, value)+ for (const old of cache.keys()) {+ if (cache.size <= max) break+ cache.delete(old)+ }+ }++ // Redraws every reader of `done`; an invalidate where the write is refused.+ export function refresh($: EngineInterface) {+ void update($, done, n => n + 1).catch(() => $.ui.invalidate('ui.render'))+ }diff --cc hooks/lib/stream.tsindex 2d05776,f5e80d0..95af151--- a/hooks/lib/stream.ts+++ b/hooks/lib/stream.ts@@@ -1,37 -1,84 +1,88 @@@// Streaming and the compile queue: a block is blank while its text streams,// final when its request moves on (or its text is still), then compiled, at- // most MAX_RUNNING at once.+ // most MAX_RUNNING at once: rows on screen first, then the newest. No job+ // starts during a burst (S.resizing); a job that ends calls jobDone (no-// redraw while an epoch is open: the epoch commits).++// redraw while an epoch is open: the epoch commits). A job enqueued stops++// the probe ahead (probe.ts); the last job that ends arms it again.import type { EngineInterface } from 'claude-code'- import { BLANK_AFTER_LIVE_MS, MAX_RUNNING } from './settings'- import { finalized, live, pending, queue, refresh, results, running, type Job } from './state'+ import { BLANK_AFTER_LIVE_MS, MAX_RUNNING, RESULTS_KEPT } from './settings'+ import { finalized, keep, live, pending, queue, refresh, results, running, S, type Job } from './state'import { hashOf } from './draw'+ import { noteDesign, recordDesign } from './designs'import { compile, logDebug } from './typst'+ import { extendEpoch, jobDone, jobQueued } from './epoch'++import { probeLater, stopProbe } from './probe'++ // The order of enqueue calls: a higher `order` is newer.+ let enqueued = 0++ // The queue's next job: one on screen first, then one not known (onScreen+ // undefined), then one known off screen; among them the newest.+ const rankOf = (j: Job) => (j.onScreen === true ? 2 : j.onScreen === false ? 0 : 1)+ export function nextJob(jobs: readonly Job[]): number {+ let best = -1+ for (let i = 0; i < jobs.length; i++) {+ const j = jobs[i]!+ const b = jobs[best]+ if (!b || (rankOf(j) !== rankOf(b) ? rankOf(j) > rankOf(b) : (j.order ?? 0) > (b.order ?? 0))) best = i+ }+ return best+ }export function pump($: EngineInterface) {+ if (S.resizing) returnwhile (running.size < MAX_RUNNING && queue.length) {- const job = queue.shift()!- running.add(job.key)- void compile($, job)+ const job = queue.splice(nextJob(queue), 1)[0]!+ const controller = new AbortController()+ const entry = { job, cancel: () => controller.abort(), signal: controller.signal }+ running.set(job.key, entry)+ void compile($, job, controller.signal).catch(async (err: unknown) => {await logDebug($, job.env.cache, `compile ${job.key} threw: ${String(err)}`)return 'failed' as const})- .then(result => {- results.set(job.key, result)- running.delete(job.key)- refresh($)+ .then(async result => {+ // A cancelled compile keeps nothing: no result, no design.+ if (result !== 'cancelled') {+ // A first compile of a final text keeps its design (a job compiles+ // only once its text is final). Any job of the text saves it: the+ // first job may have been replaced in the queue by a later one with+ // the same design (recordDesign does nothing once it is saved).+ if (result !== 'failed' && job.room) {+ await recordDesign($, job.env.designs, job.room.designKey, job.room.design).catch(() => undefined)+ }+ keep(results, job.key, result, RESULTS_KEPT)+ }+ // A new run of the same key may have taken the entry.+ if (running.get(job.key) === entry) running.delete(job.key)+ // A cancelled compile draws nothing new: no redraw.+ if (result !== 'cancelled') jobDone($)pump($)++ if (!queue.length && !running.size) probeLater($)})}}+ // A newer text of the same message replaces its job still waiting; the same+ // job again takes its new place (on screen or not, and newest).export function enqueue($: EngineInterface, job: Job) {- if (results.has(job.key) || running.has(job.key)) return- // A newer text of the same message replaces its job still waiting.+ // A first compile's design is in memory at once, so a render of the same+ // text while it compiles (a resize) uses it too.+ if (job.room?.isNew) noteDesign(job.room.designKey, job.room.design)+ if (results.has(job.key)) return+ // A run cancelled (by beginEpoch) still ends; its key compiles again.+ const runs = running.get(job.key)+ if (runs && !runs.signal.aborted) returnconst stale = queue.findIndex(j => j.requestId === job.requestId || j.key === job.key)if (stale >= 0) queue.splice(stale, 1)+ job.epoch = S.epoch+ job.order = ++enqueued++ stopProbe()queue.push(job)+ jobQueued(job)+ // A job of the open epoch: its rows still come, the commit waits for them.+ extendEpoch($)pump($)}diff --cc hooks/lib/typst.tsindex 948d6a8,9ab56ed..af88df3--- a/hooks/lib/typst.ts+++ b/hooks/lib/typst.ts@@@ -8,7 -8,7 +8,8 @@@ import { firstLine, imagePathOf, localIimport { inlineBudget } from './terminal'import { alignFirstLine, firstLineOf, fontFit, sizing } from './draw'import { HEADERS_SH } from './host'+ import { logDebug } from './log'+import { positionsOf, type Mark, type Positions } from './copy'// The typst command and its environment. Network off (see NO_NETWORK) and a// package cache of our own, so only the vendored packages load.@@@ -141,81 -146,195 +147,237 @@@ export async function existingImages($return found}- // The template's inputs for a job (the PNG compile and the probe share them).+ // The template's inputs for the room of a drawing (pt): the room height, and+ // the design's page width and room height.+ export function roomInputs(room: Job['room']): Record<string, number> {+ if (!room) return {}+ const pt = (v: number) => Math.round(v * 100) / 100+ return { height: pt(room.heightPt), 'design-w': pt(room.design.widthPt), 'design-h': pt(room.design.heightPt) }+ }++ // The rows a page of `height` pixels takes in cells of `cell` (the template+ // pads each page to whole rows, so this rounds).+ export const pageRowsOf = (height: number, cell: Cell) => Math.max(1, Math.round(height / cell.height))++ // A kept pages.json as a Result; null when it is not one (an older format).+ export function resultOf(text: string): Result | null {+ try {+ const r = JSON.parse(text) as Result+ const isPage = (p: Page) => !!p && typeof p.file === 'string' && p.columns > 0 && p.rows > 0+ return Array.isArray(r.pages) && r.pages.length > 0 && r.pages.every(isPage) ? r : null+ } catch {+ return null+ }+ }++ // Paths in use (key folders, design files): their mtime is set to now, so+ // the cleanups go by use. touchLater only notes the path (no process in a+ // render path); one `touch -c` runs per TOUCH_FLUSH_MS for at most+ // TOUCH_BATCH paths, the rest wait for the next run.+ export const TOUCH_BATCH = 200+ const TOUCH_KEPT = 4096+ // The paths not touched yet (empty after each flush; answer.ts keeps the+ // keys touched in this load, so a redraw does not note them again).+ const toTouch = new Set<string>()+ let touchTimer: { cancel: () => void } | null = null++ export function touchLater($: EngineInterface, path: string) {+ if (toTouch.size >= TOUCH_KEPT && !toTouch.has(path)) return+ toTouch.add(path)+ if (touchTimer) return+ touchTimer = $.clock.after(TOUCH_FLUSH_MS, () => {+ touchTimer = null+ const paths = [...toTouch].slice(0, TOUCH_BATCH)+ for (const each of paths) toTouch.delete(each)+ if (paths.length) void Promise.resolve($.process.run(['touch', '-c', ...paths], { timeoutMs: 5000 })).catch(() => undefined)+ if (toTouch.size) touchLater($, toTouch.values().next().value!)+ })+ }++ // Clears the paths not touched yet and the timer (for tests).+ export function forgetTouches() {+ touchTimer?.cancel()+ touchTimer = null+ toTouch.clear()+ }++ // A command with a PID line first: `sh` writes its own PID, then becomes+ // the command (exec keeps the PID), so `kill <pid>` stops the command.+ export const wrapPid = (argv: readonly string[]): string[] => ['sh', '-c', 'echo $$; exec "$@"', 'sh', ...argv]++ // How a run ended: `isCancelled` when `signal` stopped it (its output does+ // not count).+ export type Ran = { exitCode: number; stdout: string; stderr: string; isCancelled?: boolean }++ // Runs `argv` through wrapPid with $.process.spawn: its stdout (less the PID+ // line) and stderr, and its exit code (1 when a signal ended it). `signal`+ // and the timeout (`timeoutMs`, on $.clock) kill it by its PID; a timeout+ // ends with exit 1 and stderr `timed out`.+ export async function runKillable(+ $: EngineInterface,+ argv: readonly string[],+ o: { env?: Record<string, string>; signal?: AbortSignal; timeoutMs: number },+ ): Promise<Ran> {+ if (o.signal?.aborted) return { exitCode: 1, stdout: '', stderr: 'cancelled', isCancelled: true }+ let pid = ''+ let head = ''+ let stdout = ''+ let stderr = ''+ let why: 'cancel' | 'timeout' | null = null+ let isKillSent = false+ const killNow = () => {+ if (!why || !pid || isKillSent) return+ isKillSent = true+ void Promise.resolve($.process.run(['kill', pid], { timeoutMs: 5000 })).catch(() => undefined)+ }+ const stop = (reason: 'cancel' | 'timeout') => {+ if (why) return+ why = reason+ killNow()+ }+ const onAbort = () => stop('cancel')+ o.signal?.addEventListener('abort', onAbort, { once: true })+ const timer = $.clock.after(o.timeoutMs, () => stop('timeout'))+ let code: number | null = 1+ try {+ const child = $.process.spawn({ argv: wrapPid(argv), ...(o.env ? { env: o.env } : {}) })+ for (;;) {+ const got = await child.next()+ if (got.done) {+ code = got.value?.code ?? 1+ break+ }+ const { stream, text } = got.value+ if (stream === 'stderr') stderr += text+ else if (pid) stdout += text+ else {+ head += text+ const at = head.indexOf('\n')+ if (at >= 0) {+ pid = head.slice(0, at).trim()+ stdout += head.slice(at + 1)+ head = ''+ if (!/^\d+$/.test(pid)) pid = ''+ killNow()+ }+ }+ }+ } catch (err: unknown) {+ stderr += `${stderr ? '\n' : ''}typst did not run: ${String(err)}`+ code = 1+ } finally {+ timer.cancel()+ o.signal?.removeEventListener('abort', onAbort)+ }+ // A cancel that came after typst ended (before its end was read) drops a+ // whole result too: the key compiles again (rare, and accepted).+ if (why === 'cancel') return { exitCode: 1, stdout, stderr, isCancelled: true }+ if (why === 'timeout') return { exitCode: 1, stdout, stderr: 'timed out' }+ return { exitCode: code, stdout, stderr }+ }+-export async function runTypst($: EngineInterface, job: Job, segments: readonly string[], dir: string, tag: string, isSafe: boolean, signal?: AbortSignal): Promise<Ran> {++// The template's inputs for a job and its ppi (the PNG compile and the++// probe share them).+export function typstInputs(job: Job, segments: readonly string[], dir: string, isSafe: boolean) {const fit = fontFit(job.env.metrics, job.size)const { widthPt, ppi, rowPt } = sizing(job.columns, job.cell, fit.columnPt)const { topPt } = alignFirstLine(firstLineOf(segments[0] ?? ''), rowPt)- const { argv, env: vars } = typstCall({- typst: job.env.typst!,- root: job.env.root,- cache: job.env.cache,- ppi,- inputs: {- theme: job.theme,- width: widthPt,- top: topPt,- row: Math.round(rowPt * 10000) / 10000,- code: fit.code,- ...(job.env.termFont ? { 'term-font': job.env.termFont } : {}),- 'theme-dir': job.themeDir,- doc: `${dir}/doc.json`,- ...roomInputs(job.room),- ...(isSafe ? { safe: 1 } : {}),- },- out: `${dir}/${tag}-{0p}.png`,- })+ const inputs: Record<string, string | number> = {+ theme: job.theme,+ width: widthPt,+ top: topPt,+ row: Math.round(rowPt * 10000) / 10000,+ code: fit.code,+ ...(job.env.termFont ? { 'term-font': job.env.termFont } : {}),+ 'theme-dir': job.themeDir,+ doc: `${dir}/doc.json`,++ ...roomInputs(job.room),+ ...(isSafe ? { safe: 1 } : {}),+ }+ return { inputs, ppi }+}+- export async function runTypst($: EngineInterface, job: Job, segments: readonly string[], dir: string, tag: string, isSafe: boolean) {++export async function runTypst($: EngineInterface, job: Job, segments: readonly string[], dir: string, tag: string, isSafe: boolean, signal?: AbortSignal): Promise<Ran> {+ const { inputs, ppi } = typstInputs(job, segments, dir, isSafe)- const { argv, env: vars } = typstCall({- typst: job.env.typst!,- root: job.env.root,- cache: job.env.cache,- ppi,- inputs,- out: `${dir}/${tag}-{0p}.png`,- })- return $.process- .run(argv, { timeoutMs: COMPILE_TIMEOUT_MS, env: vars })- .catch((err: unknown) => ({ exitCode: 1, stdout: '', stderr: `typst did not run: ${String(err)}` }))++ const { argv, env: vars } = typstCall({ typst: job.env.typst!, root: job.env.root, cache: job.env.cache, ppi, inputs, out: `${dir}/${tag}-{0p}.png` })+ return runKillable($, argv, { env: vars, timeoutMs: COMPILE_TIMEOUT_MS, ...(signal ? { signal } : {}) })}+// ---- The probe: where the words are ---------------------------------------++// `typst query` of the template's <mdpos> marks with probe=1: the PNG+// compile's own inputs, root, package path and env (no ppi, format or out).+export function probeCall(o: { typst: string; root: string; cache: string; inputs: Readonly<Record<string, string | number>> }): { argv: string[]; env: Record<string, string> } {+ const argv = [+ o.typst, 'query',+ '--root', '/',+ '--package-path', `${o.root}/render/packages`,+ '--diagnostic-format', 'short',+ ...Object.entries({ ...o.inputs, probe: 1 }).flatMap(([k, v]) => ['--input', `${k}=${v}`]),+ `${o.root}/render/md.typ`,+ '<mdpos>',+ '--field', 'value',+ ]+ return { argv, env: noNetworkEnv(o.cache) }+}+- // What a page set's probe needs, kept as probe.json beside pages.json, so- // positions.json can be made later (a key compiled in an earlier session).++// What a page set's probe needs, kept as probe.json beside pages.json: the++// probe runs only when a copy needs it or when nothing compiles (probe.ts),++// in this load or a later one.+export type ProbeJob = { argv: string[]; env: Record<string, string>; ppi: number }+- // Runs the probe and writes positions.json; the positions, or null.- export async function runProbe($: EngineInterface, dir: string, probe: ProbeJob): Promise<Positions | null> {- const got = await $.process.run(probe.argv, { timeoutMs: COMPILE_TIMEOUT_MS, env: probe.env }).catch(() => null)- if (!got || got.exitCode !== 0 || got.isStdoutTruncated) return null++// Runs the probe and writes positions.json: the positions, null when it++// failed, 'cancelled' when `signal` stopped it.++export async function runProbe($: EngineInterface, dir: string, probe: ProbeJob, signal?: AbortSignal): Promise<Positions | null | 'cancelled'> {++ const ran = await runKillable($, probe.argv, { env: probe.env, timeoutMs: COMPILE_TIMEOUT_MS, ...(signal ? { signal } : {}) })++ if (ran.isCancelled) return 'cancelled'++ if (ran.exitCode !== 0) {++ await logDebug($, dir.replace(/\/[^/]*$/, ''), `probe ${dir} failed:\n${ran.stderr}`)++ return null++ }+ try {- const positions = positionsOf(JSON.parse(got.stdout) as Mark[], probe.ppi)++ const positions = positionsOf(JSON.parse(ran.stdout) as Mark[], probe.ppi)+ await $.fs.write(`${dir}/positions.json`, JSON.stringify(positions))+ return positions+ } catch {+ return null+ }+}+- export async function compile($: EngineInterface, job: Job): Promise<Result | 'failed'> {+ // The pages of one run: its PNGs (by tag) in order, with their sizes and+ // the box each takes. Null when there are none or a size can not be read.+ async function pagesOfRun($: EngineInterface, job: Job, dir: string, tag: string, segments: readonly string[]): Promise<Page[] | null> {+ const files = (await $.fs.list(dir))+ .filter(f => f.kind === 'file' && f.name.startsWith(`${tag}-`) && f.name.endsWith('.png'))+ .map(f => f.name)+ .sort((x, y) => Number(x.replace(/\D/g, '')) - Number(y.replace(/\D/g, '')))+ .map(name => `${dir}/${name}`)+ if (!files.length) return null+ const heads = await $.process.run(['sh', '-c', HEADERS_SH, 'sh', ...files])+ const sizes = parseOd(heads.stdout).map(pngSize)+ if (sizes.length !== files.length || sizes.some(s => !s)) {+ await logDebug($, job.env.cache, `compile ${job.key}: could not read PNG sizes`)+ return null+ }+ return files.map((file, i) => ({+ file, ...sizes[i]!, alt: plainOf(segments[i] ?? job.text), columns: job.columns, rows: pageRowsOf(sizes[i]!.height, job.cell),+ }))+ }++ // Compiles a job's text to its pages (kept in its key folder). `signal`+ // stops it: a run killed by it, or a retry not begun, is 'cancelled' (not a+ // result: nothing is kept).+ export async function compile($: EngineInterface, job: Job, signal?: AbortSignal): Promise<Result | 'failed' | 'cancelled'> {const dir = `${job.env.cache}/${job.key}`const kept = await $.fs.read(`${dir}/pages.json`).catch(() => null)- if (kept) return JSON.parse(kept) as Result+ const keptResult = kept ? resultOf(kept) : null+ if (keptResult) {+ touchLater($, dir)+ return keptResult+ }+ if (signal?.aborted) return 'cancelled'- const segments = splitSegments(job.text, job.columns, job.env.inline ? inlineBudget(job.cell) : SEGMENT_ROWS)+ let segments = splitSegments(job.text, job.columns, job.env.inline ? inlineBudget(job.cell) : SEGMENT_ROWS, job.size)const base = job.base ?? job.env.cwdconst images = await existingImages($, segments, base)await $.fs.write(`${dir}/doc.json`, JSON.stringify({ base, segments, images }))@@@ -235,26 -359,29 +402,38 @@@}}- const files = (await $.fs.list(dir))- .filter(f => f.kind === 'file' && f.name.startsWith(`${tag}-`) && f.name.endsWith('.png'))- .map(f => f.name)- .sort((x, y) => Number(x.replace(/\D/g, '')) - Number(y.replace(/\D/g, '')))- .map(name => `${dir}/${name}`)- if (!files.length) return 'failed'- const heads = await $.process.run(['sh', '-c', HEADERS_SH, 'sh', ...files])- const sizes = parseOd(heads.stdout).map(pngSize)- if (sizes.length !== files.length || sizes.some(s => !s)) {- await logDebug($, job.env.cache, `compile ${job.key}: could not read PNG sizes`)- return 'failed'+ let pages = await pagesOfRun($, job, dir, tag, segments)+ if (!pages) return 'failed'+ // A page taller than an Image can be (the row estimate was short): its+ // 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]))+ if (cut.length > segments.length) {+ if (signal?.aborted) return 'cancelled'+ await $.fs.write(`${dir}/doc.json`, JSON.stringify({ base, segments: cut, images }))+ const again = await runTypst($, job, cut, dir, isSafe ? 'd' : 'c', isSafe, signal)+ if (again.isCancelled) return 'cancelled'+ const split = again.exitCode === 0 ? await pagesOfRun($, job, dir, isSafe ? 'd' : 'c', cut) : null+ if (split) {+ pages = split+ segments = cut- } else await logDebug($, job.env.cache, `compile ${job.key}: the split retry failed:\n${again.stderr}`)++ } else {++ await logDebug($, job.env.cache, `compile ${job.key}: the split retry failed:\n${again.stderr}`)++ // The probe reads doc.json: the segments of the pages kept.++ await $.fs.write(`${dir}/doc.json`, JSON.stringify({ base, segments, images }))++ }+ }+ pages = pages.map(p => ({ ...p, rows: Math.min(MAX_IMAGE_ROWS, p.rows) }))}- const pages = files.map((file, i) => ({ file, ...sizes[i]!, alt: plainOf(segments[i] ?? job.text) }))- // The probe after the PNGs, not awaited: the pictures never wait for it.- const { inputs, ppi } = typstInputs(job, segments, dir, tag === 'b')- const probe: ProbeJob = { ...probeCall({ typst: job.env.typst!, root: job.env.root, cache: job.env.cache, inputs }), ppi }- void $.fs.write(`${dir}/probe.json`, JSON.stringify(probe)).then(() => runProbe($, dir, probe)).catch(() => undefined)const { rowPt } = sizing(job.columns, job.cell, fontFit(job.env.metrics, job.size).columnPt)const { bulletRow } = alignFirstLine(firstLineOf(segments[0] ?? ''), rowPt)- const result: Result = { pages, columns: job.columns, bulletRow, ...(note ? { note } : {}) }+ const result: Result = { pages, bulletRow, ...(note ? { note } : {}) }++ // Only what the probe needs, no process: it runs later (probe.ts). Before++ // pages.json, so a kept key has it.++ const { inputs, ppi } = typstInputs(job, segments, dir, isSafe)++ const probe: ProbeJob = { ...probeCall({ typst: job.env.typst!, root: job.env.root, cache: job.env.cache, inputs }), ppi }++ await $.fs.write(`${dir}/probe.json`, JSON.stringify(probe))await $.fs.write(`${dir}/pages.json`, JSON.stringify(result))return result}diff --cc hooks/register.tsxindex 6478053,3d19199..632e960--- a/hooks/register.tsx+++ b/hooks/register.tsx@@@ -13,29 -13,29 +13,33 @@@// The work is in ./lib, one topic per module: settings, state (the shared// mutable state `S`), markdown, terminal, terminals, mode, themes, command,// setup, host, typst, draw, stream, answer (one text through the pipeline),- // env, images, pictures, plan (the plan approval flow) and copy (the text- // under a mouse copy of the pictures). This file joins them to the hooks,- // and gives the tests the names they import.-// env, images, pictures and plan (the plan approval flow). This file joins-// them to the hooks, and gives the tests the names they import.++// env, images, pictures, plan (the plan approval flow), copy (the text under++// a mouse copy of the pictures) and probe (the drawn pages and their word++// positions). This file joins them to the hooks, and gives the tests the++// names they import.import { atom, read, update } from 'claude-code'import type { EngineInterface, Register, RenderElement, RenderViewport } from 'claude-code'- import { CLIP_POLL_MS, DEFAULT_THEME, MAX_SIZE, MIN_SIZE, TYPST_PROMPT } from './lib/settings'import {- clip, DRAWN_KEPT, drawnAnswers, editedPlans, positionsByDir, refresh, S, subagentPlans, writesLive, type Cell, type Env, type Result,- } from './lib/state'- import { columnsFor } from './lib/terminal'- DEFAULT_THEME, heightText, IMAGE_MAX_COLUMNS, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, RESULTS_KEPT, TYPST_PROMPT, widthText,++ CLIP_POLL_MS, DEFAULT_THEME, heightText, IMAGE_MAX_COLUMNS, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, RESULTS_KEPT, TYPST_PROMPT, widthText,+ } from './lib/settings'-import { editedPlans, keep, queue, refresh, running, S, subagentPlans, writesLive, type Env } from './lib/state'++import { clip, drawnAnswers, editedPlans, keep, queue, refresh, running, S, subagentPlans, writesLive, type Env } from './lib/state'+ import { beginEpoch } from './lib/epoch'import { escapeControls, luminanceOf, modeLine, modeOfLuminance, parseOsc11, settingOf } from './lib/mode'import { applyTheme, themeListing, userThemesOf } from './lib/themes'import { commandSuggestions, parseCommand, registerCommand } from './lib/command'import { runSetup } from './lib/setup'import { pollHost, PROBE_RUNS, probeOsc11, showMode, USE_OSC11, watchHost } from './lib/host'- import { measureFonts, runProbe, type ProbeJob } from './lib/typst'- import { drawPages, rowsFor } from './lib/draw'- import { codePointsOf, decodeSelection, hasPlaceholders, joinSegments, pickPages, textOfRun, type Pick, type Positions, type Segment } from './lib/copy'+ import { measureFonts } from './lib/typst'+ import { drawPages } from './lib/draw'import { finalizeAll } from './lib/stream'- import { pagesOf } from './lib/answer'- import { noteViewport, setUp } from './lib/env'- import { pastedImagePath, pastedNumbers, sentFiles } from './lib/images'++import { noteDrawn, noteDrawnAgain, positionsFor } from './lib/probe'++import { codePointsOf, decodeSelection, hasPlaceholders, joinSegments, pickPages, textOfRun, type Pick, type Segment } from './lib/copy'+ import { pagesOf, type Drawing } from './lib/answer'+ import { setUp } from './lib/env'+ import { frameFor, noteView } 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 {currentPlan, decidePlan, decisionOf, drawAskLine, drawPlanResult, drawPlanUse, isPlanQuestion, planFileOf, planInputOf, planOf,@@@ -60,10 -66,12 +70,13 @@@ exportexport { commandSuggestions, parseCommand, type Command, type Suggestion } from './lib/command'export { hasSetup, SETUP_END, SETUP_START, setupBlock, shellRcOf, withoutSetup, withSetup, type ShellRc } from './lib/setup'export { OSC11_PL } from './lib/host'- export { convertCall, measureCall, noNetworkEnv, parseOd, pngSize, probeCall, shouldRetrySafe, typstCall } from './lib/typst'- export { alignFirstLine, firstLineOf, fontFit, hashOf, renderKey, rowsFor, sizing, type FirstLine } from './lib/draw'+ export {- convertCall, measureCall, noNetworkEnv, pageRowsOf, parseOd, pngSize, resultOf, roomInputs, shouldRetrySafe, typstCall,++ convertCall, measureCall, noNetworkEnv, pageRowsOf, parseOd, pngSize, probeCall, resultOf, roomInputs, shouldRetrySafe, typstCall, type ProbeJob,+ } from './lib/typst'+ export { alignFirstLine, firstLineOf, fontFit, hashOf, renderKey, scaledBulletRow, sizing, type FirstLine } from './lib/draw'+ export { nextJob } from './lib/stream'export * from './lib/images'+export * from './lib/copy'export {choiceOf, decisionOf, editorArgv, feedbackOf, isPlanQuestion, normalPath, PLAN_ASK_LINE, PLAN_AUTO, PLAN_CLEAR, PLAN_DRAWING, PLAN_EDIT,PLAN_FEEDBACK, PLAN_HEADER, PLAN_IMPLEMENT, PLAN_MANUAL, PLAN_QUESTION, PLAN_QUESTION_EDITED, PLAN_REJECTED, planFileOf, planInputOf,@@@ -112,161 -180,6 +185,181 @@@ async function planEnv($: EngineInterfareturn ready?.typst && ready.canDraw ? ready : null}+// ---- Copy -----------------------------------------------------------------+// A mouse copy over a picture puts kitty placeholder cells on the clipboard,- // and no hook sees that copy, so the clipboard is read afterwards (pbpaste,- // every CLIP_POLL_MS on macOS) and, when it holds placeholders, written- // again with the words under them (see lib/copy.ts).-- // An answer's pages as drawn: kept by requestId, newest last. A redraw with- // the same pages keeps its place, so `seq` is when it was first drawn so.- function noteDrawn(id: string, result: Result, columns: number, px: Cell) {- const pages = result.pages.map(p => ({ file: p.file, width: p.width, height: p.height, rows: rowsFor(p, columns, px) }))- const dir = result.pages[0]?.file.replace(/\/[^/]*$/, '') ?? ''- const was = drawnAnswers.get(id)- if (was && was.dir === dir && was.columns === columns && was.pages.every((p, i) => p.rows === pages[i]?.rows)) return- drawnAnswers.delete(id)- drawnAnswers.set(id, { id, seq: ++clip.seq, columns, dir, pages })- for (const old of drawnAnswers.keys()) {- if (drawnAnswers.size <= DRAWN_KEPT) break- drawnAnswers.delete(old)- }- }-- // An answer folder's word positions: positions.json, else the probe run now- // (from probe.json: a key compiled before this load, or a probe not done yet).- async function positionsFor($: EngineInterface, dir: string): Promise<Positions | null> {- const known = positionsByDir.get(dir)- if (known) return known- let got: Positions | null = null- const kept = await $.fs.read(`${dir}/positions.json`).catch(() => null)++// and no hook sees that copy, so the selection and the clipboard are read++// afterwards (every CLIP_POLL_MS on macOS) and, when they hold placeholders,++// the clipboard is written again with the words under them (see++// lib/copy.ts; the drawn pages and their positions are in lib/probe.ts).++++// Notes a drawing for a copy (noteDrawn, noteDrawnAgain) and starts the++// watcher; a failure never stops the row from drawing.++function noteCopy($: EngineInterface, note: () => void) {+ try {- if (kept) got = JSON.parse(kept) as Positions++ note()++ watchClipboard($)+ } catch {}- if (!got) {- const probe = await $.fs.read(`${dir}/probe.json`).catch(() => null)- try {- if (probe) got = await runProbe($, dir, JSON.parse(probe) as ProbeJob)- } catch {}- }- if (got) positionsByDir.set(dir, got)- return got+}++type CopyRead = { text: string; segments: Segment[]; picks: Pick[]; runs: number; resolved: number }++// The text for a clipboard (or selection) text with placeholders.+async function readCopy($: EngineInterface, raw: string, requestId?: string): Promise<CopyRead> {+ const segments = decodeSelection(raw)+ const picks = pickPages(segments, [...drawnAnswers.values()], requestId)+ const texts: (string | null)[] = []+ let resolved = 0+ for (const [i, seg] of segments.entries()) {+ const pick = picks[i]+ const d = pick ? drawnAnswers.get(pick.id) : undefined+ const page = pick && d ? d.pages[pick.page] : undefined+ if (seg.kind !== 'image' || !pick || !d || !page) {+ texts.push(null)+ continue+ }+ const positions = await positionsFor($, d.dir)- const text = positions ? textOfRun(seg.lines, positions.pages[pick.page] ?? [], positions.blocks, page, d.columns) : ''++ const text = positions ? textOfRun(seg.lines, positions.pages[pick.page] ?? [], positions.blocks, page) : ''+ if (text) resolved+++ texts.push(text || null)+ }+ const runs = segments.filter(seg => seg.kind === 'image').length+ const read = { text: joinSegments(segments, texts), segments, picks, runs, resolved }- clip.last = { requestId: requestId ?? null, ...read, drawn: [...drawnAnswers.values()].map(d => ({ id: d.id, seq: d.seq, columns: d.columns, dir: d.dir, pages: d.pages.map(p => ({ rows: p.rows, width: p.width, height: p.height })) })) }++ clip.last = { requestId: requestId ?? null, ...read, drawn: [...drawnAnswers.values()] }+ return read+}+- // One clipboard read: placeholders that are not our own write are read and- // written back as text. Never touches a clipboard with no placeholders.++// Writes the text read for `raw` (placeholders) to the clipboard, once:++// our own write is never read back as new.++async function copyRead($: EngineInterface, raw: string, requestId?: string) {++ clip.raw = raw++ clip.rawRow = requestId++ const read = await readCopy($, raw, requestId)++ if (!read.resolved) {++ // Not read again from the clipboard (one toast).++ clip.seen = raw++ $.ui.toast('Intelligent UI: could not read the selected picture (/iui dump says why)')++ return++ }++ clip.wrote = read.text++ clip.seen = read.text++ await $.ui.copy({ text: read.text })++ $.ui.toast(`Intelligent UI: copied ${read.text.length} chars of text`)++}++++// A selection and a clipboard text are the same copy (a copy can end in++// line breaks that the selection does not have, or the other way).++const sameCopy = (a: string, b: string) => a.replace(/\r\n/g, '\n').replace(/\s+$/, '') === b.replace(/\r\n/g, '\n').replace(/\s+$/, '')++++// One tick: first the mouse selection (in-process; a new one is copied only++// when Claude Code copies on select), else the clipboard (pbpaste).++// Placeholders that are not our own write are read and written back as++// text. A clipboard with no placeholders is never touched. When this++// session has a selection (fullscreen), the clipboard is rewritten only++// when it is that selection: another session's copy is that session's to++// read. The first tick of a watcher only notes the selection there is (an++// old one, after a hot reload), so it is never copied again.+async function clipTick($: EngineInterface) {+ if (clip.busy) return+ clip.busy = true+ try {++ const selected = await $.ui.selection().catch(() => undefined)++ if (!clip.seeded) {++ clip.seeded = true++ clip.selected = selected?.text ?? ''++ return++ }++ if (S.copyOnSelect && selected && selected.text !== clip.selected && hasPlaceholders(selected.text)) {++ clip.selected = selected.text++ await copyRead($, selected.text, selected.requestId)++ return++ }+ const got = await $.process.run(['pbpaste'], { timeoutMs: 2000, env: { LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' } }).catch(() => null)+ if (!got || got.exitCode !== 0) return+ const text = got.stdout+ if (text === clip.seen) return+ clip.seen = text+ if (text === clip.wrote || !hasPlaceholders(text)) return- clip.raw = text- const selected = await $.ui.selection().catch(() => undefined)- const read = await readCopy($, text, selected && hasPlaceholders(selected.text) ? selected.requestId : undefined)- if (!read.resolved) {- $.ui.toast('md-preview: could not read the selected picture (/md-preview dump says why)')- return- }- clip.wrote = read.text- clip.seen = read.text- await $.ui.copy({ text: read.text })- $.ui.toast(`md-preview: copied ${read.text.length} chars of text`)++ if (selected && !sameCopy(selected.text, text)) return++ if (selected) clip.selected = selected.text++ await copyRead($, text, selected?.requestId)+ } finally {+ clip.busy = false+ }+}++// The watcher: on macOS, on this computer (over ssh pbpaste reads the remote- // one's clipboard). One per load: a hot reload drops the old load's timers.- // A timer whose period was refused stops; one silent for 10 periods is- // started again (`ticked` is when it last ran).++// one's clipboard), only while Intelligent UI is on (its callers draw, or++// read the atom) and a picture is drawn. One per load: a hot reload drops++// the old load's timers. A timer whose period was refused stops; one silent++// for 10 periods is started again (`ticked` is when it last ran).+function watchClipboard($: EngineInterface) {- if (!S.env?.isMac || S.isRemote) return++ if (!S.env?.isMac || S.isRemote || !drawnAnswers.size) return+ if (clip.watch && Date.now() - clip.ticked < 10 * CLIP_POLL_MS) return+ clip.watch?.cancel()+ clip.ticked = Date.now()++ clip.seeded = false+ try {+ clip.watch = $.clock.every(CLIP_POLL_MS, () => {+ clip.ticked = Date.now()+ void clipTick($).catch(() => undefined)+ })+ } catch {+ clip.watch = null+ }+}+- // /md-preview grab: the last mouse selection, read and copied.++// Intelligent UI off, or the session's end: no reads.++function stopClipboard() {++ clip.watch?.cancel()++ clip.watch = null++}++++// /iui grab: the last mouse selection, read and copied.+async function grab($: EngineInterface): Promise<string> {+ const selected = await $.ui.selection().catch(() => undefined)- if (!selected) return 'md-preview: no mouse selection (it needs fullscreen mode; select over a picture first).'- if (!hasPlaceholders(selected.text)) return `md-preview: the selection has no picture cells; it is ${selected.text.length} chars of text already.`++ if (!selected) return 'Intelligent UI: no mouse selection (it needs fullscreen mode; select over a picture first).'++ if (!hasPlaceholders(selected.text)) return `Intelligent UI: the selection has no picture cells; it is ${selected.text.length} chars of text already.`+ clip.raw = selected.text++ clip.rawRow = selected.requestId++ clip.selected = selected.text+ const read = await readCopy($, selected.text, selected.requestId)- if (!read.resolved) return `md-preview: found ${read.runs} picture run(s) but could not read them (see /md-preview dump).`++ if (!read.resolved) return `Intelligent UI: found ${read.runs} picture run(s) but could not read them (see /iui dump).`+ clip.wrote = read.text+ clip.seen = read.text+ const copied = await $.ui.copy({ text: read.text })+ return copied.isCopied- ? `md-preview: copied ${read.text.length} chars (${read.resolved} of ${read.runs} picture runs read${selected.requestId ? `, row ${selected.requestId}` : ''}).`- : `md-preview: the copy failed: ${'reason' in copied ? String(copied.reason) : 'unknown'}.`++ ? `Intelligent UI: copied ${read.text.length} chars (${read.resolved} of ${read.runs} picture runs read${selected.requestId ? `, row ${selected.requestId}` : ''}).`++ : `Intelligent UI: the copy failed: ${copied.reason}.`+}+- // /md-preview dump: the last placeholder text seen, as code points, how- // it was read, and the same in full in <cache>/copy-debug.json.++// /iui dump: the last placeholder text seen, as code points, how it was++// read, and the same in full in <cache>/copy-debug.json.+async function dump($: EngineInterface): Promise<string> {- if (!clip.raw) return `md-preview: no clipboard text with picture cells seen yet (watcher ${clip.watch ? 'on' : 'off'}; ${drawnAnswers.size} answers drawn).`- const read = await readCopy($, clip.raw)++ const watcher = clip.watch ? 'on' : 'off'++ if (!clip.raw) return `Intelligent UI: no clipboard text with picture cells seen yet (watcher ${watcher}; ${drawnAnswers.size} pictures drawn).`++ const read = await readCopy($, clip.raw, clip.rawRow)+ const runs = read.segments+ .map((seg, i) => {+ if (seg.kind === 'text') return `text: ${JSON.stringify(seg.text.slice(0, 60))}`+ const rows = seg.lines.map(l => `${l.row}:${l.colStart}-${l.colEnd}`).join(' ')+ const pick = read.picks[i]+ return `run rows ${rows} -> ${pick ? `answer ${pick.id} page ${pick.page}` : 'no page fits'}`+ })+ .join('\n')+ const cache = S.env?.cache ?? ''- if (cache) await $.fs.write(`${cache}/copy-debug.json`, JSON.stringify({ raw: clip.raw, codePoints: codePointsOf(clip.raw, 100000), ...(clip.last as object) }, null, 1)).catch(() => undefined)++ if (cache) {++ const full = { raw: clip.raw, codePoints: codePointsOf(clip.raw, 100000), ...(clip.last as object) }++ await $.fs.write(`${cache}/copy-debug.json`, JSON.stringify(full, null, 1)).catch(() => undefined)++ }+ return [- `md-preview: last clipboard with picture cells (${Array.from(clip.raw).length} code points; watcher ${clip.watch ? 'on' : 'off'}):`,++ `Intelligent UI: last clipboard with picture cells (${Array.from(clip.raw).length} code points; watcher ${watcher}):`,+ codePointsOf(clip.raw, 40),+ runs,+ `Read as ${read.text.length} chars: ${JSON.stringify(read.text.slice(0, 200))}`,+ cache ? `Full dump: ${cache}/copy-debug.json` : '',+ ].filter(Boolean).join('\n')+}+// ---- Hooks ----------------------------------------------------------------export const register: Register = on => {@@@ -276,35 -189,50 +369,76 @@@return next(e)})+ on('session.end', async ($, e, next) => {- clip.watch?.cancel()- clip.watch = null++ stopClipboard()+ return next(e)- })++ }).catch(($, e, next) => next(e))++++ // A copy with placeholders (a copy of picture cells, when the engine sends++ // one through `$.ui.copy`): the words under them instead. Our own copies++ // hold no placeholders and pass on as they are.++ on('ui.copy', async ($, e, next) => {++ if (!hasPlaceholders(e.text) || !drawnAnswers.size) return next(e)++ const selected = await $.ui.selection().catch(() => undefined)++ clip.raw = e.text++ clip.rawRow = selected?.text === e.text ? selected.requestId : undefined++ const read = await readCopy($, e.text, clip.rawRow)++ if (!read.resolved) return next(e)++ // The watcher does not copy the same selection again.++ if (selected?.text === e.text) clip.selected = e.text++ clip.wrote = read.text++ clip.seen = read.text++ return next({ ...e, text: read.text })++ }).catch(($, e, next) => next(e))+- // Typeahead for /md-preview arguments; the theme list is the last scan's.+ // Typeahead for /iui arguments; the theme list is the last scan's.on('prompt.autocomplete', async ($, e, next) => {const got = await next(e)- if (!/^\s*\/md-preview\s/.test(e.text)) return got+ if (!/^\s*\/iui\s/.test(e.text)) return gotif (!S.themeChoices.length) await setUp($).catch(() => null)- const mine = commandSuggestions(e.text, e.token, e.start, { themes: S.themeChoices, active: S.look?.name ?? DEFAULT_THEME, size: S.size })+ const mine = commandSuggestions(e.text, e.token, e.start, { themes: S.themeChoices, active: S.look?.name ?? DEFAULT_THEME, size: S.size, width: S.width, height: S.height })return mine.length ? { suggestions: [...got.suggestions, ...mine] } : got})- on('command.run', { command: 'md-preview' }, async ($, e) => {+ on('command.run', { command: 'iui' }, async ($, e) => {const asked = parseCommand(e.args)+ if (asked.kind === 'grab') return { text: await grab($) }+ if (asked.kind === 'dump') return { text: await dump($) }if (asked.kind === 'on' || asked.kind === 'off') {await update($, isOn, () => asked.kind === 'on')++ // On: the watcher starts with the next picture drawn.++ if (asked.kind === 'off') stopClipboard()await $.store.set('enabled', asked.kind === 'on')- return { text: `md-preview is ${asked.kind}.` }+ return { text: `Intelligent UI is ${asked.kind}.` }}if (asked.kind === 'size') {+ // The epoch begins with the setting, so no row draws it with no epoch+ // open (the store write waits for the host).S.size = asked.percent+ beginEpoch($)await $.store.set('size', S.size)- refresh($)- return { text: `md-preview draws text at ${S.size}% of the terminal's text size (100% matches it).` }+ return { text: `Intelligent UI draws text at ${S.size}% of the terminal's text size (100% matches it).` }+ }+ if (asked.kind === 'width') {+ if (asked.width === undefined) await setUp($).catch(() => null)+ else {+ S.width = asked.width+ beginEpoch($)+ await $.store.set('width', S.width)+ }+ const most = typeof S.width === 'number' && S.width > IMAGE_MAX_COLUMNS ? ` (a picture is ${IMAGE_MAX_COLUMNS} columns at most)` : ''+ const head = asked.width === undefined ? 'The most columns a picture takes' : 'Intelligent UI pictures now take at most'+ return { text: `${head}: ${widthText(S.width)}${most}. Use /iui width <${MIN_WIDTH}-${MAX_WIDTH}> for a cap, or /iui width full (the default) for no cap.` }+ }+ if (asked.kind === 'height') {+ if (asked.height === undefined) await setUp($).catch(() => null)+ else {+ S.height = asked.height+ beginEpoch($)+ await $.store.set('height', S.height)+ }+ const head = asked.height === undefined ? 'The most rows an image or a Typst drawing takes' : 'Intelligent UI images and Typst drawings now take at most'+ return { text: `${head}: ${heightText(S.height)}. This applies to images (sent or pasted) and to Typst drawings in answers. Use /iui height half (the default), /iui height full, or /iui height <${MIN_HEIGHT}-${MAX_HEIGHT}> (never more than full).` }}if (asked.kind === 'setup') {await setUp($).catch(() => null)@@@ -366,6 -303,6 +509,13 @@@return set}).catch(($, e, next) => next(e))++ // Claude Code's copyOnSelect: off, the watcher does not copy a selection.++ on('config.set', { key: 'copyOnSelect' }, async ($, e, next) => {++ const set = await next(e)++ if (set.value !== undefined) S.copyOnSelect = set.value !== false++ return set++ }).catch(($, e, next) => next(e))++on('prompt.compose', async ($, e, next) => {const composed = await next(e)if (!e.surfaces.includes('terminal') || !(await read($, isOn))) return composed@@@ -432,15 -369,18 +582,23 @@@if (e.surface !== 'terminal' || e.props.isSummary || !e.props.text.trim()) return next(e)const ready = await answerEnv($, e)if (!ready) return next(e)- const columns = columnsFor(e.viewport?.columns)- const drawing = await pagesOf($, { id: e.requestId, text: e.props.text, columns, env: ready, canStream: true })+ const bullet = !!e.props.isFirstOfReply+ 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)- if (kept) return kept++ if (kept) {++ noteCopy($, () => noteDrawnAgain($, e.requestId, roomColumns(e.viewport)))++ 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') {- try {- noteDrawn(e.requestId, drawing.result, columns, drawing.px)- watchClipboard($)- } catch {}- return drawPages($, e, drawing.result, columns, drawing.px, drawing.bytes, { bullet: !!e.props.isFirstOfReply })+ const tree = drawPages($, e, drawing.result, drawing.bytes, { bullet })++ const { result } = drawing++ noteCopy($, () => noteDrawn($, e.requestId, result, roomColumns(e.viewport)))+ memoSet(answers, e.requestId, k, tree)+ return tree}+ answers.delete(e.requestId)if (drawing.kind === 'text') return next(e)const { Box } = $.ui.resolve(e)return <Box />@@@ -457,8 -397,20 +615,27 @@@try {const files = sentFiles(e.props.output)const ready = files.length ? await pictureEnv($, e) : null- const markdown = ready && files.some(f => f.kind === 'markdown') ? await answerEnv($, e) : null- if (ready) under = await sentOf($, e, { ready, markdown, files, id: e.props.tool_use_id })+ if (ready) {+ const markdown = files.some(f => f.kind === 'markdown') && ready.env.typst ? ready.env : null+ const id = e.props.tool_use_id+ const onScreen = onScreenOf(e.props.onScreen)+ 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}:`))- if (kept) under = kept- else {++ if (kept) {++ under = kept++ for (const u of under) if ('drawing' in u) noteCopy($, () => noteDrawnAgain($, u.id, roomColumns(e.viewport)))++ } 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 { result } = u.drawing++ noteCopy($, () => noteDrawn($, u.id, result, roomColumns(e.viewport)))++ }+ }+ }} catch {under = []}@@@ -499,7 -458,6 +683,8 @@@// The main loop's running turn, which "clear context" ends.on('turn.start', async ($, e, next) => {if (e.agentId === undefined) S.mainTurnId = e.turnId- watchClipboard($)++ // The watcher again if it went silent.++ if (await read($, isOn)) watchClipboard($)return next(e)}).catch(($, e, next) => next(e))@@@ -514,17 -472,8 +699,14 @@@const plan = planShownOf(editedPlans.get(e.props.tool_use_id), e.props.output, e.props.input)const ready = plan ? await answerEnv($, e) : nullif (!ready) return row- const columns = columnsFor(e.viewport?.columns)- const drawing = await pagesOf($, { id: `plan:${e.props.tool_use_id}`, text: plan, columns, env: ready, canStream: false })- // Its pages can be copied as an answer's: kept by the call's id, as the- // row's requestId can be an answer's own.+ 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).+ if (drawing.kind === 'pages') {- try {- noteDrawn(`plan:${e.props.tool_use_id}`, drawing.result, columns, drawing.px)- watchClipboard($)- } catch {}++ const { result } = drawing++ noteCopy($, () => noteDrawn($, `plan:${e.props.tool_use_id}`, result, roomColumns(e.viewport)))+ }- return drawPlanUse($, e, row, drawing, columns)+ return drawPlanUse($, e, row, drawing)} catch {return row}diff --cc render/md.typindex 6fb22cf,704933e..48794dd--- a/render/md.typ+++ b/render/md.typ@@@ -208,75 -278,6 +278,87 @@@// running off the page.#show regex("\S{30,}"): it => it.text.clusters().join(sym.zws)+// ---------- probe: where the text lies ----------+// probe=1 is given only to `typst query <md.typ> "<mdpos>" --field value`+// (same inputs as the PNG compile), never to the PNG compile itself: the+// word rule below splits text into separately shaped runs, which moves+// glyphs by a fraction of a pixel (a PNG with probe=1 differs from one+// without in anti-aliasing, max 64/255 on a channel, but no word moves and+// no line breaks elsewhere). Its marks are `metadata` labelled <mdpos>, in+// document order:+// w: a word (a run of non-space characters, cut after - and /), boxed;+// x, y the top-left of its box: y is the top of its line box (text+// top-edge "ascender"), w its advance width and h its ascender-to-+// descender height. Its ink lies inside the box (1-4 px side bearings+// at 2.75 px/pt), its centre is y + h/2.++// A long word (30+ characters) or CJK text breaks anywhere: each of++// its characters (clusters) is a word, boxed, `g` on all but the++// first (they join with no space).+// c: a block code line: x its start, y its baseline, a and d the code+// font's ascender and descender, w its width, n its characters.+// b: a block starts: paragraph, heading, code block, quote, table cell+// (column `cx`), list item (`prefix`: "- ", "1. ", "- [x] ").++// Math and live ```typst drawings have no marks (a drawing is scaled, so++// its marks would not be where it is drawn).+// Each mark has its page `p` (1-based, = the PNG's {0p}) and the text size+// `s`; all lengths in pt from the page's top-left. A bare (unboxed) mark at+// the start of a wrapped line is placed at the end of the line above, and+// one at a paragraph's end on the next line; hence the boxes.+#let probe = inp.at("probe", default: "0") not in ("", "0", "false", "no", "off")+#let mark(kind, ..extra) = context {+ let at = here().position()+ [#metadata((k: kind, p: at.page, x: at.x / 1pt, y: at.y / 1pt, s: text.size.to-absolute() / 1pt, ..extra.named()))<mdpos>]+}- // Block code sets this (an unused cost) so the word rule leaves its text to- // the line marks.- #let in-code(costs) = costs.runt == 101%++// 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 cjk = regex("[\\p{Han}\\p{Hiragana}\\p{Katakana}\\p{Hangul}]")+#let probe-rules(body) = {+ // A word is cut after a hyphen or a slash, where a line may break; a+ // token of 30+ characters is one word (it breaks anywhere, see above).- show regex("\\S{30,}|[^\\s/-]*[/-]+|[^\\s/-]+"): it => context if in-code(text.costs) { it } else {++ show regex("\\S{30,}|[^\\s/-]*[/-]+|[^\\s/-]+"): it => context if in-code(text.costs) or no-marks(text.costs) { it } else {+ let size = measure(it)+ let t = it.text+ if t.clusters().len() >= 30 or t.match(cjk) != none {- // A long word (zws break chances, above) or CJK text (breaks- // anywhere) keeps its breaks: only a mark where it starts.- mark("w", t: t, w: size.width / 1pt, h: size.height / 1pt)- it++ // A long word or CJK text breaks anywhere: a box for each character++ // (a line may break between boxes, as at the long-word rule's zws).++ // Bare text here would be matched by that rule again as one word,++ // with all the marks after it.++ for (i, c) in t.clusters().enumerate() {++ let one = measure(c)++ box({ mark("w", t: c, w: one.width / 1pt, h: one.height / 1pt, ..if i > 0 { (g: 1) } else { (:) }); c })++ }+ } else {+ // Boxed, so the mark is where the word is drawn (a bare mark at the+ // start of a wrapped line stays at the end of the line above).+ box({ mark("w", t: t, w: size.width / 1pt, h: size.height / 1pt); it })+ }+ }+ // A code line: a zero-size box at its start (its y is the baseline). An+ // empty line has none: a box would give it a height.+ show raw.line: it => context if not in-code(text.costs) or it.text == "" { it } else {+ let asc = measure(text(top-edge: "ascender", bottom-edge: "baseline", "x")).height+ let desc = measure(text(top-edge: "baseline", bottom-edge: "descender", "x")).height+ box(mark("c", t: it.text, w: measure(it.body).width / 1pt, n: it.text.clusters().len(), a: asc / 1pt, d: desc / 1pt))+ it+ }+ show raw.where(block: true): it => {+ mark("b", kind: "code")- set text(costs: (runt: 101%))++ set text(costs: (orphan: 101%))+ it+ }++ show math.equation: set text(costs: (orphan: 102%))+ show par: it => { mark("b", kind: "par"); it }+ show heading: it => { mark("b", kind: "heading"); it }+ show quote.where(block: true): it => { mark("b", kind: "quote"); it }+ show table.cell: it => { mark("b", kind: "cell", cx: it.x); it }+ body+}+#show: body => if probe { probe-rules(body) } else { body }+#let item-mark(prefix, body) = if not probe { body } else { mark("b", kind: "item", prefix: prefix); body }+// ---------- helpers ----------#let alt-box(alt, why: none) = box(stroke: px + C.muted, inset: (x: 4pt, y: 1.5pt), outset: (y: 1pt), radius: 3pt,@@@ -543,10 -559,27 +647,29 @@@if block and not safe and l in live-langs {// Inside a block, so #pagebreak() and #set page() are errors (one// segment must stay one page); a column break is dropped.- std.block(width: 100%, above: 1.2em, below: 1.2em, {+ let drawing = {show colbreak: none- eval(src, mode: "markup", scope: (theme: theme))- })++ // The probe: no marks (see no-marks).++ set text(costs: (orphan: 102%)) if probe+ eval(src, mode: "markup", scope: (theme: live-theme))+ }+ std.block(width: 100%, above: 1.2em, below: 1.2em, layout(size => {+ // The space here (less than the content width in a list or a quote).+ let space = if size.width.pt() < 1e6 { size.width } else { content-w }+ // Lay the code out in the design width (in design units: the space / f+ // when that is less, so 100% widths fill the space here).+ let w = calc.min(design-content-w, space / factor)+ // Fit guard: a part with a fixed size wider than w gets a smaller+ // factor, so it is never cut. A tall drawing is never made smaller+ // (the page grows; the factor has the height ratio already).+ let k = factor+ let wide = needed-width(drawing, w)+ if wide > w { k = calc.min(k, space / wide) }+ // Lay a too-wide drawing out in the width it needs: in the width w, an+ // align(center, ..) puts the extra width left of the block, where the+ // scale cannot bring it back (it is cut off at the page edge).+ scale(k * 100%, origin: top + left, reflow: true, std.block(width: calc.max(w, wide), drawing))+ }))} else if block and safe and l in live-langs {// Retry mode: show the source, with a note that it was not drawn.std.block(above: 1.2em, below: 0pt, sticky: true,diff --cc tests/copy-fixture.tsindex 5e94a98,0000000..8f61dc6mode 100644,000000..100644--- a/tests/copy-fixture.ts+++ b/tests/copy-fixture.ts@@@ -1,47 -1,0 +1,318 @@@+// A real probe: `typst query render/md.typ "<mdpos>" --field value` with+// probe=1, for the Markdown below at 98 columns of a 16 x 32 px cell (the- // default metrics: width 570.02 pt, ppi 198.0562, top 4.36 pt). Its PNG is- // 1568 x 512 px, 16 rows.++// 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++// 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++// --input theme-dir=$PWD/render/themes/claude-code --input doc=$PWD/doc.json":++// typst compile --root / --package-path render/packages --format png \++// --ppi 198.0562 $IN render/md.typ 'a-{0p}.png' # the PNG size++// typst query --root / --package-path render/packages $IN --input probe=1 \++// render/md.typ '<mdpos>' --field value # SMALL_MARKS++// The tests below say which rows the lines are in (row = 32 px).+export const SMALL_MD = "## Copy test\n\nThe quick brown fox jumps over the lazy dog, then keeps running across the wide green field until the well-known path ends.\n\n- first item\n- second item\n\n```sh\necho hello world\nls -la\n```\n"++export const SMALL_PPI = 198.0562- export const SMALL_PAGE = { width: 1568, height: 512, rows: 16 }++export const SMALL_PAGE = { width: 1568, height: 512, columns: 98, rows: 16 }++export const SMALL_MARKS = [+ {"k": "b", "p": 1, "x": 0.0, "y": 4.36, "s": 13.2, "kind": "heading"},+ {"k": "w", "p": 1, "x": 0.0, "y": 4.36, "s": 19.8, "t": "Copy", "w": 50.12841796875, "h": 23.628515625000002},+ {"k": "w", "p": 1, "x": 55.3974609375, "y": 4.36, "s": 19.8, "t": "test", "w": 38.04345703125, "h": 23.628515625000002},- {"k": "b", "p": 1, "x": 0.0, "y": 44.928515625, "s": 11.0, "kind": "par"},- {"k": "w", "p": 1, "x": 0.0, "y": 44.928515625, "s": 11.0, "t": "The", "w": 19.72802734375, "h": 13.126953125},- {"k": "w", "p": 1, "x": 22.82177734375, "y": 44.928515625, "s": 11.0, "t": "quick", "w": 27.96728515625, "h": 13.126953125},- {"k": "w", "p": 1, "x": 53.8828125, "y": 44.928515625, "s": 11.0, "t": "brown", "w": 32.00634765625, "h": 13.126953125},- {"k": "w", "p": 1, "x": 88.98291015625, "y": 44.928515625, "s": 11.0, "t": "fox", "w": 15.7373046875, "h": 13.126953125},- {"k": "w", "p": 1, "x": 107.81396484375, "y": 44.928515625, "s": 11.0, "t": "jumps", "w": 31.173828125, "h": 13.126953125},- {"k": "w", "p": 1, "x": 142.08154296875, "y": 44.928515625, "s": 11.0, "t": "over", "w": 22.5048828125, "h": 13.126953125},- {"k": "w", "p": 1, "x": 167.68017578125, "y": 44.928515625, "s": 11.0, "t": "the", "w": 16.75244140625, "h": 13.126953125},- {"k": "w", "p": 1, "x": 187.5263671875, "y": 44.928515625, "s": 11.0, "t": "lazy", "w": 20.75390625, "h": 13.126953125},- {"k": "w", "p": 1, "x": 211.3740234375, "y": 44.928515625, "s": 11.0, "t": "dog,", "w": 23.224609375, "h": 13.126953125},- {"k": "w", "p": 1, "x": 237.6923828125, "y": 44.928515625, "s": 11.0, "t": "then", "w": 23.1708984375, "h": 13.126953125},- {"k": "w", "p": 1, "x": 263.95703125, "y": 44.928515625, "s": 11.0, "t": "keeps", "w": 30.744140625, "h": 13.126953125},- {"k": "w", "p": 1, "x": 297.794921875, "y": 44.928515625, "s": 11.0, "t": "running", "w": 39.2841796875, "h": 13.126953125},- {"k": "w", "p": 1, "x": 340.1728515625, "y": 44.928515625, "s": 11.0, "t": "across", "w": 34.16015625, "h": 13.126953125},- {"k": "w", "p": 1, "x": 377.4267578125, "y": 44.928515625, "s": 11.0, "t": "the", "w": 16.75244140625, "h": 13.126953125},- {"k": "w", "p": 1, "x": 397.27294921875, "y": 44.928515625, "s": 11.0, "t": "wide", "w": 24.27734375, "h": 13.126953125},- {"k": "w", "p": 1, "x": 424.64404296875, "y": 44.928515625, "s": 11.0, "t": "green", "w": 29.71826171875, "h": 13.126953125},- {"k": "w", "p": 1, "x": 457.4560546875, "y": 44.928515625, "s": 11.0, "t": "field", "w": 22.52099609375, "h": 13.126953125},- {"k": "w", "p": 1, "x": 483.07080078125, "y": 44.928515625, "s": 11.0, "t": "until", "w": 22.3330078125, "h": 13.126953125},- {"k": "w", "p": 1, "x": 508.49755859375, "y": 44.928515625, "s": 11.0, "t": "the", "w": 16.75244140625, "h": 13.126953125},- {"k": "w", "p": 1, "x": 528.34375, "y": 44.928515625, "s": 11.0, "t": "well-", "w": 25.3408203125, "h": 13.126953125},- {"k": "w", "p": 1, "x": 0.0, "y": 62.23546875, "s": 11.0, "t": "known", "w": 33.6123046875, "h": 13.126953125},- {"k": "w", "p": 1, "x": 36.7060546875, "y": 62.23546875, "s": 11.0, "t": "path", "w": 23.25146484375, "h": 13.126953125},- {"k": "w", "p": 1, "x": 63.05126953125, "y": 62.23546875, "s": 11.0, "t": "ends.", "w": 28.48291015625, "h": 13.126953125},- {"k": "b", "p": 1, "x": 30.799999999999997, "y": 88.562421875, "s": 11.0, "kind": "item", "prefix": "- "},- {"k": "w", "p": 1, "x": 30.799999999999997, "y": 88.562421875, "s": 11.0, "t": "first", "w": 20.47998046875, "h": 13.126953125},- {"k": "w", "p": 1, "x": 54.37373046875, "y": 88.562421875, "s": 11.0, "t": "item", "w": 22.48876953125, "h": 13.126953125},- {"k": "b", "p": 1, "x": 30.799999999999997, "y": 105.869375, "s": 11.0, "kind": "item", "prefix": "- "},- {"k": "w", "p": 1, "x": 30.799999999999997, "y": 105.869375, "s": 11.0, "t": "second", "w": 37.87158203125, "h": 13.126953125},- {"k": "w", "p": 1, "x": 71.76533203124998, "y": 105.869375, "s": 11.0, "t": "item", "w": 22.48876953125, "h": 13.126953125},- {"k": "b", "p": 1, "x": 0.0, "y": 132.196328125, "s": 11.0, "kind": "code"},- {"k": "c", "p": 1, "x": 12.571428571428573, "y": 153.1251785714286, "s": 11.0, "t": "echo hello world", "w": 105.9609375, "n": 16, "a": 8.357421875, "d": 2.642578125},- {"k": "c", "p": 1, "x": 12.571428571428573, "y": 168.05217857142858, "s": 11.0, "t": "ls -la", "w": 39.7353515625, "n": 6, "a": 8.357421875, "d": 2.642578125},++ {"k": "b", "p": 1, "x": 0.0, "y": 38.988515625000005, "s": 11.0, "kind": "par"},++ {"k": "w", "p": 1, "x": 0.0, "y": 38.988515625000005, "s": 11.0, "t": "The", "w": 19.72802734375, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 22.82177734375, "y": 38.988515625000005, "s": 11.0, "t": "quick", "w": 27.96728515625, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 53.8828125, "y": 38.988515625000005, "s": 11.0, "t": "brown", "w": 32.00634765625, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 88.98291015625, "y": 38.988515625000005, "s": 11.0, "t": "fox", "w": 15.7373046875, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 107.81396484375, "y": 38.988515625000005, "s": 11.0, "t": "jumps", "w": 31.173828125, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 142.08154296875, "y": 38.988515625000005, "s": 11.0, "t": "over", "w": 22.5048828125, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 167.68017578125, "y": 38.988515625000005, "s": 11.0, "t": "the", "w": 16.75244140625, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 187.5263671875, "y": 38.988515625000005, "s": 11.0, "t": "lazy", "w": 20.75390625, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 211.3740234375, "y": 38.988515625000005, "s": 11.0, "t": "dog,", "w": 23.224609375, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 237.6923828125, "y": 38.988515625000005, "s": 11.0, "t": "then", "w": 23.1708984375, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 263.95703125, "y": 38.988515625000005, "s": 11.0, "t": "keeps", "w": 30.744140625, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 297.794921875, "y": 38.988515625000005, "s": 11.0, "t": "running", "w": 39.2841796875, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 340.1728515625, "y": 38.988515625000005, "s": 11.0, "t": "across", "w": 34.16015625, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 377.4267578125, "y": 38.988515625000005, "s": 11.0, "t": "the", "w": 16.75244140625, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 397.27294921875, "y": 38.988515625000005, "s": 11.0, "t": "wide", "w": 24.27734375, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 424.64404296875, "y": 38.988515625000005, "s": 11.0, "t": "green", "w": 29.71826171875, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 457.4560546875, "y": 38.988515625000005, "s": 11.0, "t": "field", "w": 22.52099609375, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 483.07080078125, "y": 38.988515625000005, "s": 11.0, "t": "until", "w": 22.3330078125, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 508.49755859375, "y": 38.988515625000005, "s": 11.0, "t": "the", "w": 16.75244140625, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 528.34375, "y": 38.988515625000005, "s": 11.0, "t": "well-", "w": 25.3408203125, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 0.0, "y": 56.29546875, "s": 11.0, "t": "known", "w": 33.6123046875, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 36.7060546875, "y": 56.29546875, "s": 11.0, "t": "path", "w": 23.25146484375, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 63.05126953125, "y": 56.29546875, "s": 11.0, "t": "ends.", "w": 28.48291015625, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 20.9, "y": 82.62242187499999, "s": 11.0, "t": "-", "w": 5.1884765625, "h": 13.126953125},++ {"k": "b", "p": 1, "x": 32.138476562499996, "y": 82.62242187499999, "s": 11.0, "kind": "item", "prefix": "- "},++ {"k": "w", "p": 1, "x": 32.138476562499996, "y": 82.62242187499999, "s": 11.0, "t": "first", "w": 20.47998046875, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 55.712207031249996, "y": 82.62242187499999, "s": 11.0, "t": "item", "w": 22.48876953125, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 20.9, "y": 99.929375, "s": 11.0, "t": "-", "w": 5.1884765625, "h": 13.126953125},++ {"k": "b", "p": 1, "x": 32.138476562499996, "y": 99.929375, "s": 11.0, "kind": "item", "prefix": "- "},++ {"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},++] as const++++// The same probe (same inputs) for a long path and a long URL (30+++// characters: each character is a word) and CJK text. Its PNG is 1568 x++// 320 px, 10 rows.++export const LONG_MD = "Path /Users/someone/Development/apps/very/long/path/to/file.ts and short.\n\n中文测试文本 and more words here.\n\nA very long one: https://example.com/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/x end.\n"++++export const LONG_PAGE = { width: 1568, height: 320, columns: 98, rows: 10 }++++export const LONG_MARKS = [++ {"k": "b", "p": 1, "x": 0.0, "y": 4.36, "s": 11.0, "kind": "par"},++ {"k": "w", "p": 1, "x": 0.0, "y": 4.36, "s": 11.0, "t": "Path", "w": 23.310546875, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 26.404296875, "y": 4.36, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 29.755859375, "y": 4.36, "s": 11.0, "t": "U", "w": 8.1103515625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 37.8662109375, "y": 4.36, "s": 11.0, "t": "s", "w": 5.7578125, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 43.6240234375, "y": 4.36, "s": 11.0, "t": "e", "w": 6.2841796875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 49.908203125, "y": 4.36, "s": 11.0, "t": "r", "w": 4.189453125, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 54.09765625, "y": 4.36, "s": 11.0, "t": "s", "w": 5.7578125, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 59.85546875, "y": 4.36, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 63.20703125, "y": 4.36, "s": 11.0, "t": "s", "w": 5.7578125, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 68.96484375, "y": 4.36, "s": 11.0, "t": "o", "w": 6.4990234375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 75.4638671875, "y": 4.36, "s": 11.0, "t": "m", "w": 9.5712890625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 85.03515625, "y": 4.36, "s": 11.0, "t": "e", "w": 6.2841796875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 91.3193359375, "y": 4.36, "s": 11.0, "t": "o", "w": 6.4990234375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 97.818359375, "y": 4.36, "s": 11.0, "t": "n", "w": 6.41845703125, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 104.23681640625, "y": 4.36, "s": 11.0, "t": "e", "w": 6.2841796875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 110.52099609375, "y": 4.36, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 113.87255859375, "y": 4.36, "s": 11.0, "t": "D", "w": 7.9921875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 121.86474609375, "y": 4.36, "s": 11.0, "t": "e", "w": 6.2841796875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 128.14892578125, "y": 4.36, "s": 11.0, "t": "v", "w": 5.9619140625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 134.11083984375, "y": 4.36, "s": 11.0, "t": "e", "w": 6.2841796875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 140.39501953125, "y": 4.36, "s": 11.0, "t": "l", "w": 2.7822265625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 143.17724609375, "y": 4.36, "s": 11.0, "t": "o", "w": 6.4990234375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 149.67626953125, "y": 4.36, "s": 11.0, "t": "p", "w": 6.7138671875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 156.39013671875, "y": 4.36, "s": 11.0, "t": "m", "w": 9.5712890625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 165.96142578125, "y": 4.36, "s": 11.0, "t": "e", "w": 6.2841796875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 172.24560546875, "y": 4.36, "s": 11.0, "t": "n", "w": 6.41845703125, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 178.6640625, "y": 4.36, "s": 11.0, "t": "t", "w": 3.99609375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 182.66015625, "y": 4.36, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 186.01171875, "y": 4.36, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 192.0810546875, "y": 4.36, "s": 11.0, "t": "p", "w": 6.7138671875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 198.794921875, "y": 4.36, "s": 11.0, "t": "p", "w": 6.7138671875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 205.5087890625, "y": 4.36, "s": 11.0, "t": "s", "w": 5.7578125, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 211.2666015625, "y": 4.36, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 214.6181640625, "y": 4.36, "s": 11.0, "t": "v", "w": 5.9619140625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 220.580078125, "y": 4.36, "s": 11.0, "t": "e", "w": 6.2841796875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 226.8642578125, "y": 4.36, "s": 11.0, "t": "r", "w": 4.189453125, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 231.0537109375, "y": 4.36, "s": 11.0, "t": "y", "w": 5.97265625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 237.0263671875, "y": 4.36, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 240.3779296875, "y": 4.36, "s": 11.0, "t": "l", "w": 2.7822265625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 243.16015625, "y": 4.36, "s": 11.0, "t": "o", "w": 6.4990234375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 249.6591796875, "y": 4.36, "s": 11.0, "t": "n", "w": 6.41845703125, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 256.07763671875, "y": 4.36, "s": 11.0, "t": "g", "w": 6.703125, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 262.78076171875, "y": 4.36, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 266.13232421875, "y": 4.36, "s": 11.0, "t": "p", "w": 6.7138671875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 272.84619140625, "y": 4.36, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 278.91552734375, "y": 4.36, "s": 11.0, "t": "t", "w": 3.99609375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 282.91162109375, "y": 4.36, "s": 11.0, "t": "h", "w": 6.47216796875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 289.3837890625, "y": 4.36, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 292.7353515625, "y": 4.36, "s": 11.0, "t": "t", "w": 3.99609375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 296.7314453125, "y": 4.36, "s": 11.0, "t": "o", "w": 6.4990234375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 303.23046875, "y": 4.36, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 306.58203125, "y": 4.36, "s": 11.0, "t": "f", "w": 3.97998046875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 310.56201171875, "y": 4.36, "s": 11.0, "t": "i", "w": 2.7177734375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 313.27978515625, "y": 4.36, "s": 11.0, "t": "l", "w": 2.7822265625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 316.06201171875, "y": 4.36, "s": 11.0, "t": "e", "w": 6.2841796875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 322.34619140625, "y": 4.36, "s": 11.0, "t": ".", "w": 3.265625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 325.61181640625, "y": 4.36, "s": 11.0, "t": "t", "w": 3.99609375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 329.60791015625, "y": 4.36, "s": 11.0, "t": "s", "w": 5.7578125, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 338.45947265625, "y": 4.36, "s": 11.0, "t": "and", "w": 19.24462890625, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 360.7978515625, "y": 4.36, "s": 11.0, "t": "short.", "w": 30.28759765625, "h": 13.126953125},++ {"k": "b", "p": 1, "x": 0.0, "y": 30.686953125, "s": 11.0, "kind": "par"},++ {"k": "w", "p": 1, "x": 0.0, "y": 31.700585937499998, "s": 11.0, "t": "中", "w": 11.0, "h": 11.0},++ {"k": "w", "p": 1, "x": 11.0, "y": 31.700585937499998, "s": 11.0, "t": "文", "w": 11.0, "h": 11.0, "g": 1},++ {"k": "w", "p": 1, "x": 22.0, "y": 31.700585937499998, "s": 11.0, "t": "测", "w": 11.0, "h": 11.0, "g": 1},++ {"k": "w", "p": 1, "x": 33.0, "y": 31.700585937499998, "s": 11.0, "t": "试", "w": 11.0, "h": 11.0, "g": 1},++ {"k": "w", "p": 1, "x": 44.0, "y": 31.700585937499998, "s": 11.0, "t": "文", "w": 11.0, "h": 11.0, "g": 1},++ {"k": "w", "p": 1, "x": 55.0, "y": 31.700585937499998, "s": 11.0, "t": "本", "w": 11.0, "h": 11.0, "g": 1},++ {"k": "w", "p": 1, "x": 69.09375, "y": 30.686953125, "s": 11.0, "t": "and", "w": 19.24462890625, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 91.43212890625, "y": 30.686953125, "s": 11.0, "t": "more", "w": 26.3828125, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 120.90869140625, "y": 30.686953125, "s": 11.0, "t": "words", "w": 31.345703125, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 155.34814453125, "y": 30.686953125, "s": 11.0, "t": "here.", "w": 26.33447265625, "h": 13.126953125},++ {"k": "b", "p": 1, "x": 0.0, "y": 57.01390625, "s": 11.0, "kind": "par"},++ {"k": "w", "p": 1, "x": 0.0, "y": 57.01390625, "s": 11.0, "t": "A", "w": 7.412109375, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 10.505859375, "y": 57.01390625, "s": 11.0, "t": "very", "w": 22.2470703125, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 35.8466796875, "y": 57.01390625, "s": 11.0, "t": "long", "w": 22.40283203125, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 61.34326171875, "y": 57.01390625, "s": 11.0, "t": "one:", "w": 22.46728515625, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 86.904296875, "y": 57.01390625, "s": 11.0, "t": "h", "w": 6.47216796875, "h": 13.126953125},++ {"k": "w", "p": 1, "x": 93.37646484375, "y": 57.01390625, "s": 11.0, "t": "t", "w": 3.99609375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 97.37255859375, "y": 57.01390625, "s": 11.0, "t": "t", "w": 3.99609375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 101.36865234375, "y": 57.01390625, "s": 11.0, "t": "p", "w": 6.7138671875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 108.08251953125, "y": 57.01390625, "s": 11.0, "t": "s", "w": 5.7578125, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 113.84033203125, "y": 57.01390625, "s": 11.0, "t": ":", "w": 3.265625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 117.10595703125, "y": 57.01390625, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 120.45751953125, "y": 57.01390625, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 123.80908203125, "y": 57.01390625, "s": 11.0, "t": "e", "w": 6.2841796875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 130.09326171875, "y": 57.01390625, "s": 11.0, "t": "x", "w": 5.7685546875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 135.86181640625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 141.93115234375, "y": 57.01390625, "s": 11.0, "t": "m", "w": 9.5712890625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 151.50244140625, "y": 57.01390625, "s": 11.0, "t": "p", "w": 6.7138671875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 158.21630859375, "y": 57.01390625, "s": 11.0, "t": "l", "w": 2.7822265625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 160.99853515625, "y": 57.01390625, "s": 11.0, "t": "e", "w": 6.2841796875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 167.28271484375, "y": 57.01390625, "s": 11.0, "t": ".", "w": 3.265625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 170.54833984375, "y": 57.01390625, "s": 11.0, "t": "c", "w": 6.1552734375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 176.70361328125, "y": 57.01390625, "s": 11.0, "t": "o", "w": 6.4990234375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 183.20263671875, "y": 57.01390625, "s": 11.0, "t": "m", "w": 9.5712890625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 192.77392578125, "y": 57.01390625, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 196.12548828125, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 202.19482421875, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 208.26416015625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 214.33349609375, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 220.40283203125, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 226.47216796875, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 232.54150390625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 238.61083984375, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 244.68017578125, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 250.74951171875, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 256.81884765625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 262.88818359375, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 268.95751953125, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 275.02685546875, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 281.09619140625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 287.16552734375, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 293.23486328125, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 299.30419921875, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 305.37353515625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 311.44287109375, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 317.51220703125, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 323.58154296875, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 329.65087890625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 335.72021484375, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 341.78955078125, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 347.85888671875, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 353.92822265625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 359.99755859375, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 366.06689453125, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 372.13623046875, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 378.20556640625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 384.27490234375, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 390.34423828125, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 396.41357421875, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 402.48291015625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 408.55224609375, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 414.62158203125, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 420.69091796875, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 426.76025390625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 432.82958984375, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 438.89892578125, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 444.96826171875, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 451.03759765625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 457.10693359375, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 463.17626953125, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 469.24560546875, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 475.31494140625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 481.38427734375, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 487.45361328125, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 493.52294921875, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 499.59228515625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 505.66162109375, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 511.73095703125, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 517.80029296875, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 523.86962890625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 529.93896484375, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 536.00830078125, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 542.07763671875, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 548.14697265625, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 554.21630859375, "y": 57.01390625, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 0.0, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 6.0693359375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 12.138671875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 18.2080078125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 24.27734375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 30.3466796875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 36.416015625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 42.4853515625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 48.5546875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 54.6240234375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 60.693359375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 66.7626953125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 72.83203125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 78.9013671875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 84.970703125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 91.0400390625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 97.109375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 103.1787109375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 109.248046875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 115.3173828125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 121.38671875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 127.4560546875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 133.525390625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 139.5947265625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 145.6640625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 151.7333984375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 157.802734375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 163.8720703125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 169.94140625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 176.0107421875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 182.080078125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 188.1494140625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 194.21875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 200.2880859375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 206.357421875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 212.4267578125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 218.49609375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 224.5654296875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 230.634765625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 236.7041015625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 242.7734375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 248.8427734375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 254.912109375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 260.9814453125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 267.05078125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 273.1201171875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 279.189453125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 285.2587890625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 291.328125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 297.3974609375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 303.466796875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 309.5361328125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 315.60546875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 321.6748046875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 327.744140625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 333.8134765625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 339.8828125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 345.9521484375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 352.021484375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 358.0908203125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 364.16015625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 370.2294921875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 376.298828125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 382.3681640625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 388.4375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 394.5068359375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 400.576171875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 406.6455078125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 412.71484375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 418.7841796875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 424.853515625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 430.9228515625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 436.9921875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 443.0615234375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 449.130859375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 455.2001953125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 461.26953125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 467.3388671875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 473.408203125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 479.4775390625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 485.546875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 491.6162109375, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 497.685546875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 503.7548828125, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 509.82421875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 515.8935546875, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 521.962890625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 528.0322265625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 534.1015625, "y": 74.320859375, "s": 11.0, "t": "a", "w": 6.0693359375, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 540.1708984375, "y": 74.320859375, "s": 11.0, "t": "/", "w": 3.3515625, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 543.5224609375, "y": 74.320859375, "s": 11.0, "t": "x", "w": 5.7685546875, "h": 13.126953125, "g": 1},++ {"k": "w", "p": 1, "x": 0.0, "y": 91.6278125, "s": 11.0, "t": "end.", "w": 22.72509765625, "h": 13.126953125},+] as constdiff --cc tests/copy.test.tsindex 1367a67,0000000..e16d1abmode 100644,000000..100644--- a/tests/copy.test.ts+++ b/tests/copy.test.ts@@@ -1,256 -1,0 +1,548 @@@+import { expect, mock, test } from 'claude-code/testing'++import {- codePointsOf, decodeSelection, DIACRITICS, hasPlaceholders, joinSegments, parseCommand, pickPages, placeholderCell, positionsOf, textOfRun,- type Drawn, type TextBlock, type Item, type Mark,++ codePointsOf, commandSuggestions, decodeSelection, DIACRITICS, hasPlaceholders, isDrawnIn, joinSegments, parseCommand, pickPages, placeholderCell,++ positionsOf, probeCall, textOfRun, type Drawn, type TextBlock, type Item, type Mark,+} from '../hooks/register'- import { SMALL_MARKS, SMALL_MD, SMALL_PAGE, SMALL_PPI } from './copy-fixture'++import { PROBE_IDLE_MS } from '../hooks/lib/settings'++import { LONG_MARKS, LONG_MD, LONG_PAGE, SMALL_MARKS, SMALL_MD, SMALL_PAGE, SMALL_PPI } from './copy-fixture'++// One screen row of a picture as Claude Code draws it: `lead` (the gutter),+// then the cells of `row` from `from` to `to`.+const cells = (row: number, from: number, to: number, lead = ' ') =>+ lead + Array.from({ length: to - from + 1 }, (_, i) => placeholderCell(row, from + i)).join('')++// ---- The diacritics ---------------------------------------------------------++test("the row/column marks are kitty's 297, in its order", () => {+ expect(DIACRITICS.length).toBe(297)+ expect(new Set(DIACRITICS).size).toBe(297)+ expect(DIACRITICS.slice(0, 18)).toEqual([0x0305, 0x030d, 0x030e, 0x0310, 0x0312, 0x033d, 0x033e, 0x033f, 0x0346, 0x034a, 0x034b, 0x034c, 0x0350, 0x0351, 0x0352, 0x0357, 0x035b, 0x0363])+ expect(DIACRITICS.slice(0, 19)).toEqual([773, 781, 782, 784, 786, 829, 830, 831, 838, 842, 843, 844, 848, 849, 850, 855, 859, 867, 868])+ expect(DIACRITICS[296]).toBe(0x1d244)+ expect(placeholderCell(2, 5)).toBe('\u{10EEEE}̎̽')+ expect(hasPlaceholders(`a${placeholderCell(0, 0)}`)).toBe(true)+ expect(hasPlaceholders('plain text')).toBe(false)+})++// ---- Decoding a clipboard ---------------------------------------------------++test('a selection over one picture is one run; the gutter and its bullet are dropped', () => {+ const text = [cells(3, 10, 20, '⏺ '), cells(4, 0, 40), cells(5, 0, 7)].join('\n')+ expect(decodeSelection(text)).toEqual([+ { kind: 'image', lines: [{ row: 3, colStart: 10, colEnd: 20 }, { row: 4, colStart: 0, colEnd: 40 }, { row: 5, colStart: 0, colEnd: 7 }] },+ ])+})++test('text between pictures stays, in order; a row that starts again starts a new run', () => {+ const text = ['> my prompt', '', cells(0, 0, 3), cells(1, 0, 3), cells(0, 0, 2), 'after', ''].join('\n')+ expect(decodeSelection(text)).toEqual([+ { kind: 'text', text: '> my prompt\n' },+ { kind: 'image', lines: [{ row: 0, colStart: 0, colEnd: 3 }, { row: 1, colStart: 0, colEnd: 3 }] },+ { kind: 'image', lines: [{ row: 0, colStart: 0, colEnd: 2 }] },+ { kind: 'text', text: 'after' },+ ])+})++test('a cell with no column mark is the one after the cell before it', () => {+ const bare = '\u{10EEEE}' + String.fromCodePoint(DIACRITICS[6]!)+ expect(decodeSelection(placeholderCell(6, 9) + bare + bare)).toEqual([{ kind: 'image', lines: [{ row: 6, colStart: 9, colEnd: 11 }] }])+})++test('dump shows cells as [row,col] and other characters as code points', () => {+ expect(codePointsOf(`⏺ ${placeholderCell(1, 2)}x`)).toBe('U+23FA U+0020 U+10EEEE[1,2] U+0078')+ expect(codePointsOf(cells(0, 0, 50, ''), 3).split(' ').length).toBe(3)+})++// ---- Positions --------------------------------------------------------------++test('probe marks become pixel boxes; a list number is dropped and an item takes its paragraph', () => {+ const marks: Mark[] = [+ { k: 'b', p: 1, x: 0, y: 0, kind: 'par' },+ { k: 'w', p: 1, x: 0, y: 0, t: 'Hi', w: 10, h: 12 },+ { k: 'w', p: 1, x: 20, y: 30, t: '1.', w: 6, h: 12 },+ { k: 'b', p: 1, x: 30, y: 30, kind: 'item', prefix: '1. ' },+ { k: 'b', p: 1, x: 30, y: 30, kind: 'par' },+ { k: 'w', p: 2, x: 30, y: 30, t: 'one', w: 15, h: 12 },+ { k: 'c', p: 2, x: 10, y: 60, t: 'ab', w: 12, n: 2, a: 8, d: 2 },+ ]+ const got = positionsOf(marks, 144)+ expect(got.blocks).toEqual([{ kind: 'par', prefix: '', first: 0 }, { kind: 'item', prefix: '1. ', first: 1 }])+ expect(got.pages[0]).toEqual([{ i: 0, text: 'Hi', block: 0, x0: 0, x1: 20, y0: 0, y1: 24 }])+ expect(got.pages[1]).toEqual([+ { i: 1, text: 'one', block: 1, x0: 60, x1: 90, y0: 60, y1: 84 },+ { i: 2, text: 'ab', block: 1, x0: 20, x1: 44, y0: 104, y1: 124, adv: 12 },+ ])+})++// A hand-made page: 10 columns of 10 px, 4 rows of 20 px.- const PAGE = { width: 100, height: 80, rows: 4 }++const 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 })+const BLOCKS: TextBlock[] = [+ { kind: 'par', prefix: '', first: 0 },+ { kind: 'item', prefix: '- ', first: 4 },+ { kind: 'code', prefix: '', first: 5 },+ { kind: 'cell', prefix: '', cx: 0, first: 7 },+ { kind: 'cell', prefix: '', cx: 1, first: 8 },+]+const ITEMS: Item[] = [+ word(0, 'alpha', 0, 0, 0), word(1, 'beta', 40, 0, 0), word(2, 'well-', 70, 0, 0), word(3, 'known', 0, 1, 0),+ word(4, 'item', 40, 1, 1),+ { i: 5, text: 'let x = 1', x0: 0, x1: 90, y0: 42, y1: 58, block: 2, adv: 10 },+ { i: 6, text: 'x++', x0: 0, x1: 30, y0: 52, y1: 58, block: 2, adv: 10 },+ word(7, 'k', 0, 3, 3), word(8, 'v', 50, 3, 4),+]++test('a word is in when its centre is in a selected cell; the first line from its column, the last to its column', () => {+ // "beta" spans x 40-64: centre 52, column 5.- expect(textOfRun([{ row: 0, colStart: 5, colEnd: 9 }], ITEMS, BLOCKS, PAGE, 10)).toBe('beta well-')- expect(textOfRun([{ row: 0, colStart: 6, colEnd: 9 }], ITEMS, BLOCKS, PAGE, 10)).toBe('well-')++ expect(textOfRun([{ row: 0, colStart: 5, colEnd: 9 }], ITEMS, BLOCKS, PAGE)).toBe('beta well-')++ expect(textOfRun([{ row: 0, colStart: 6, colEnd: 9 }], ITEMS, BLOCKS, PAGE)).toBe('well-')+ // A line broken after a hyphen joins with no space; a new block is a new line with its prefix.- expect(textOfRun([{ row: 0, colStart: 0, colEnd: 9 }, { row: 1, colStart: 0, colEnd: 9 }], ITEMS, BLOCKS, PAGE, 10)).toBe('alpha beta well-known\n- item')++ expect(textOfRun([{ row: 0, colStart: 0, colEnd: 9 }, { row: 1, colStart: 0, colEnd: 9 }], ITEMS, BLOCKS, PAGE)).toBe('alpha beta well-known\n- item')+})++test('code lines are cut by characters; table cells join with a tab', () => {- expect(textOfRun([{ row: 2, colStart: 4, colEnd: 9 }], ITEMS, BLOCKS, PAGE, 10)).toBe('x = 1')- expect(textOfRun([{ row: 2, colStart: 0, colEnd: 9 }, { row: 3, colStart: 0, colEnd: 9 }], ITEMS, BLOCKS, PAGE, 10)).toBe('let x = 1\nx++\nk\tv')++ expect(textOfRun([{ row: 2, colStart: 4, colEnd: 9 }], ITEMS, BLOCKS, PAGE)).toBe('x = 1')++ expect(textOfRun([{ row: 2, colStart: 0, colEnd: 9 }, { row: 3, colStart: 0, colEnd: 9 }], ITEMS, BLOCKS, PAGE)).toBe('let x = 1\nx++\nk\tv')+ // The two code lines lie in one row (y centres 50 and 55): both, one per line.- expect(textOfRun([{ row: 2, colStart: 0, colEnd: 1 }], ITEMS, BLOCKS, PAGE, 10)).toBe('le\nx+')++ expect(textOfRun([{ row: 2, colStart: 0, colEnd: 1 }], ITEMS, BLOCKS, PAGE)).toBe('le\nx+')+})++// ---- Which page -------------------------------------------------------------+++// An answer drawn at `columns`, its pages `rows` tall (at their own box).+const drawn = (id: string, seq: number, rows: number[], columns = 80): Drawn => ({- id, seq, columns, dir: `/c/${id}`, pages: rows.map((r, i) => ({ file: `/c/${id}/a-${i + 1}.png`, width: columns * 16, height: r * 32, rows: r })),++ id, seq, dir: `/c/${id}`, pages: rows.map((r, i) => ({ file: `/c/${id}/a-${i + 1}.png`, width: columns * 16, height: r * 32, columns, rows: r })),+})+- test('a run goes to the answer the selection names, else to the newest it fits', () => {++test('a run goes to the drawing the selection names, else to the newest it fits', () => {+ const runs = decodeSelection([cells(2, 0, 50), cells(3, 0, 50)].join('\n'))+ const answers = [drawn('old', 1, [10]), drawn('new', 2, [10]), drawn('short', 3, [3])]+ expect(pickPages(runs, answers)).toEqual([{ id: 'new', page: 0 }])+ expect(pickPages(runs, answers, 'old')).toEqual([{ id: 'old', page: 0 }])++ // A plan and a sent file by the call's tool_use_id.++ expect(pickPages(runs, [...answers, drawn('plan:tu1', 0, [10])], 'tu1')).toEqual([{ id: 'plan:tu1', page: 0 }])++ expect(pickPages(runs, [...answers, drawn('file:tu2:a.md', 0, [10])], 'tu2')).toEqual([{ id: 'file:tu2:a.md', page: 0 }])++ expect(isDrawnIn('file:tu2:a.md', 'tu2')).toBe(true)++ expect(isDrawnIn('file:tu22:a.md', 'tu2')).toBe(false)+ // Too wide for an answer drawn at 40 columns.+ expect(pickPages(runs, [drawn('narrow', 9, [10], 40)])).toEqual([null])+})++test('runs one after another are consecutive pages of one answer', () => {+ const text = [cells(8, 0, 9), cells(9, 0, 9), cells(0, 0, 9), cells(1, 0, 9)].join('\n')+ const segments = decodeSelection(text)+ expect(segments.length).toBe(2)+ // Page 0 has 10 rows, so the first run ends on its last row.+ expect(pickPages(segments, [drawn('two', 1, [10, 5]), drawn('one', 2, [20])])).toEqual([{ id: 'two', page: 0 }, { id: 'two', page: 1 }])+ expect(joinSegments([{ kind: 'text', text: 'a' }, ...segments], [null, 'x', 'y'])).toBe('a\nx\ny')+})+++test('a page drawn smaller than it was compiled for fits by its drawn box', () => {++ // Compiled 98 x 16, drawn 49 x 8 (an old page in an open epoch).++ const small: Drawn = { id: 's', seq: 1, dir: '/c/s', pages: [{ file: '/c/s/a-1.png', width: 1568, height: 512, columns: 49, rows: 8 }] }++ expect(pickPages(decodeSelection(cells(7, 0, 48)), [small])).toEqual([{ id: 's', page: 0 }])++ expect(pickPages(decodeSelection(cells(2, 0, 60)), [small])).toEqual([null])++ expect(pickPages(decodeSelection(cells(9, 0, 10)), [small])).toEqual([null])++})+++// ---- A real probe -----------------------------------------------------------++const REAL = positionsOf(SMALL_MARKS as unknown as Mark[], SMALL_PPI)+const ALL_COLUMNS = (row: number) => ({ row, colStart: 0, colEnd: 97 })++const TEXT = 'Copy test\nThe quick brown fox jumps over the lazy dog, then keeps running across the wide green field until the well-known path ends.\n- first item\n- second item\necho hello world\nls -la'++test("a real probe: the whole picture copies as the answer's text", () => {+ const all = Array.from({ length: SMALL_PAGE.rows }, (_, row) => ALL_COLUMNS(row))- expect(textOfRun(all, REAL.pages[0]!, REAL.blocks, SMALL_PAGE, 98)).toBe(- 'Copy test\nThe quick brown fox jumps over the lazy dog, then keeps running across the wide green field until the well-known path ends.\n- first item\n- second item\necho hello world\nls -la',- )++ expect(textOfRun(all, REAL.pages[0]!, REAL.blocks, SMALL_PAGE)).toBe(TEXT)+})++test('a real probe: a selection from mid-paragraph into the code block', () => {- // Rows: heading 1, paragraph 4 and 5, items 8 and 9, code 12 and 14.- const lines = [{ row: 4, colStart: 30, colEnd: 97 }, ...[5, 6, 7, 8, 9, 10, 11].map(ALL_COLUMNS), { row: 12, colStart: 0, colEnd: 14 }]- expect(textOfRun(lines, REAL.pages[0]!, REAL.blocks, SMALL_PAGE, 98)).toBe(++ // 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 }]++ 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 ',+ )+ // Part of the second item: no prefix.- expect(textOfRun([{ row: 9, colStart: 10, colEnd: 97 }], REAL.pages[0]!, REAL.blocks, SMALL_PAGE, 98)).toBe('item')++ expect(textOfRun([{ row: 9, colStart: 10, colEnd: 97 }], REAL.pages[0]!, REAL.blocks, SMALL_PAGE)).toBe('item')++})++++test('a real probe on a page drawn at half its box: a cell is twice as large', () => {++ const half = { ...SMALL_PAGE, columns: 49, rows: 8 }++ // "jumps" has its centre at x 339 px: column 21 of 16 px, column 10 of 32 px.++ expect(textOfRun([{ row: 0, colStart: 0, colEnd: 48 }, { row: 1, colStart: 0, colEnd: 10 }], REAL.pages[0]!, REAL.blocks, half)).toBe(++ 'Copy test\nThe quick brown fox jumps',++ )++ expect(textOfRun(Array.from({ length: 8 }, (_, row) => ({ row, colStart: 0, colEnd: 48 })), REAL.pages[0]!, REAL.blocks, half)).toBe(TEXT)+})++test('a real probe through the clipboard: decode, pick, read', () => {+ // "jumps" is columns 18-23, its centre in column 21.- const clipboard = [cells(1, 0, 97, '⏺ '), '', cells(4, 0, 21)].join('\n')++ const clipboard = [cells(1, 0, 97, '⏺ '), '', cells(3, 0, 21)].join('\n')+ const segments = decodeSelection(clipboard)- const answer = { id: 'r1', seq: 1, columns: 98, dir: '/c/k', pages: [{ file: '/c/k/a-1.png', ...SMALL_PAGE }] }++ const answer: Drawn = { id: 'r1', seq: 1, dir: '/c/k', pages: [{ file: '/c/k/a-1.png', ...SMALL_PAGE }] }+ const picks = pickPages(segments, [answer])+ expect(picks).toEqual([{ id: 'r1', page: 0 }, null, { id: 'r1', page: 0 }])- const texts = segments.map((s, i) => (s.kind === 'image' && picks[i] ? textOfRun(s.lines, REAL.pages[0]!, REAL.blocks, SMALL_PAGE, 98) : null))++ const texts = segments.map((s, i) => (s.kind === 'image' && picks[i] ? textOfRun(s.lines, REAL.pages[0]!, REAL.blocks, SMALL_PAGE) : null))+ expect(joinSegments(segments, texts)).toBe('Copy test\n\nThe quick brown fox jumps')+})+++const LONG = positionsOf(LONG_MARKS as unknown as Mark[], SMALL_PPI)++const longRows = (rows: number[]) => textOfRun(rows.map(ALL_COLUMNS), LONG.pages[0]!, LONG.blocks, LONG_PAGE)++++test('a real probe: a long path, a long URL that wraps and CJK text are on their own rows', () => {++ const [path, cjk, url] = LONG_MD.trim().split('\n\n')++ // Rows: the path's line 0, the CJK line 3, the URL's lines 5 and 6, "end." 8.++ expect(longRows([0])).toBe(path)++ expect(longRows([1, 2])).toBe('')++ expect(longRows([3])).toBe(cjk)++ expect(longRows([5, 6, 7, 8])).toBe(url)++ expect(longRows(Array.from({ length: LONG_PAGE.rows }, (_, row) => row))).toBe(LONG_MD.trim().replace(/\n\n/g, '\n'))++ // Each character of a long word or CJK text by its own centre.++ expect(textOfRun([{ row: 0, colStart: 0, colEnd: 9 }], LONG.pages[0]!, LONG.blocks, LONG_PAGE)).toBe('Path /Users')++ expect(textOfRun([{ row: 3, colStart: 0, colEnd: 3 }], LONG.pages[0]!, LONG.blocks, LONG_PAGE)).toBe('中文')++ // The URL's second line alone: its characters, no space.++ expect(longRows([6])).toMatch(/^a+\/x$/)++ // Every box is inside the page.++ expect(LONG.pages[0]!.every(i => i.x1 <= LONG_PAGE.width && i.y1 <= LONG_PAGE.height)).toBe(true)++})++++test('invisible marks and list markers of other themes are dropped', () => {++ const marks: Mark[] = [++ { k: 'b', p: 1, x: 0, y: 0, kind: 'par' },++ { k: 'w', p: 1, x: 0, y: 0, t: 'with', w: 20, h: 12 },++ // The strut before inline code, and a long word with its break chances.++ { k: 'w', p: 1, x: 24, y: 0, t: '', w: 0, h: 12 },++ { k: 'w', p: 1, x: 24, y: 1, t: 'code', w: 20, h: 11 },++ // The paragraph's last word, then a list with a "•" marker.++ { k: 'w', p: 1, x: 0, y: 20, t: 'end', w: 15, h: 12 },++ { k: 'w', p: 1, x: 10, y: 40, t: '•', w: 4, h: 12 },++ { k: 'b', p: 1, x: 20, y: 40, kind: 'item', prefix: '- ' },++ { k: 'w', p: 1, x: 20, y: 40, t: 'one', w: 15, h: 12 },++ ]++ const got = positionsOf(marks, 72)++ expect(got.pages[0]!.map(i => i.text)).toEqual(['with', 'code', 'end', 'one'])++})+++// ---- The command ------------------------------------------------------------+- test('/md-preview grab and dump are commands; dump with nothing seen says so', async $ => {++test('/iui grab and dump are commands with typeahead rows; dump with nothing seen says so', async $ => {+ expect(parseCommand('grab')).toEqual({ kind: 'grab' })+ expect(parseCommand('dump')).toEqual({ kind: 'dump' })- const ran = await $.command.run({ command: 'md-preview', args: 'dump' } as any)- expect(ran.text).toContain('no clipboard text with picture cells seen yet')++ expect(parseCommand('grab now')).toEqual({ kind: 'bad' })++ const rows = commandSuggestions('/iui g', 'g', 5, { themes: [], active: 'claude-code', size: 100 })++ expect(rows).toEqual([{ text: 'grab', description: 'copy the text of the pictures you last selected' }])++ expect(commandSuggestions('/iui du', 'du', 5, { themes: [], active: 'claude-code', size: 100 }).map(r => r.text)).toEqual(['dump'])++ const ran = await $.command.run({ command: 'iui', args: 'dump' } as any)++ expect(ran.text).toContain('Intelligent UI: no clipboard text with picture cells seen yet')+})+- // ---- The clipboard watcher --------------------------------------------------++// ---- The pipeline: probe.json, the probe, the watcher -------------------------+- const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } })++const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: exitCode ? 'error: boom' : '', isStdoutTruncated: false, isStderrTruncated: false } })+// The first 24 bytes of a 1568 x 512 PNG (the fixture's page), as `od` prints them.+const HEAD = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 06 20 00 00 02 00'++const WRAP = 'echo $$; exec "$@"'++const inputsOf = (argv: readonly string[]) => Object.fromEntries(argv.flatMap((a, i) => (argv[i - 1] === '--input' ? [a.split(/=(.*)/s).slice(0, 2)] : [])))+- test('a mouse copy of a drawn answer is read from the clipboard and written back as text, once', async ($, on) => {++// The world beneath the mod: a cache at /c, a typst whose compile writes a++// 1568 x 512 page and whose query gives the fixture's marks (`hold` holds++// the next query until `release`; a kill ends it), pbpaste reading++// `clipboard`, and the copies, toasts and selection the test sees.++function world(on: any, o: { failFirst?: boolean } = {}) {+ mock.store(on)+ const clock = mock.clock(on)+ mock.env(on, { HOME: '/h', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' })+ const files = new Map<string, string>()- let clipboard = 'nothing yet'- let pastes = 0- const copies: string[] = []- const toasts: string[] = []++ const compiles: Record<string, string>[] = []++ const queries: Record<string, string>[] = []++ const kills: string[] = []++ const killers = new Map<string, () => void>()++ const w = {++ clock, files, compiles, queries, kills,++ clipboard: 'nothing yet', pastes: 0, copies: [] as string[], toasts: [] as string[],++ selection: undefined as { text: string; requestId?: string } | undefined,++ gate: null as Promise<void> | null, release: () => {},++ hold() {++ w.gate = new Promise<void>(r => (w.release = r))++ },++ }++ let pids = 5000++ on('process.spawn', async function* ($: any, e: any) {++ const argv: string[] = e.argv++ if (argv[0] !== 'sh' || argv[2] !== WRAP || argv[4] !== '/usr/bin/typst') return { value: { code: 2, signal: null } }++ const pid = String(pids++)++ let killed = false++ const dead = new Promise<void>(r => killers.set(pid, () => ((killed = true), r())))++ yield { stream: 'stdout', text: `${pid}\n` }++ const typst = argv.slice(4)++ if (typst[1] === 'compile') {++ compiles.push(inputsOf(typst))++ const fail = o.failFirst && compiles.length === 1++ if (fail) yield { stream: 'stderr', text: 'error: boom' }++ return { value: { code: fail ? 1 : 0, signal: null } }++ }++ if (typst[1] !== 'query') return { value: { code: 1, signal: null } }++ expect(typst.slice(-3)).toEqual(['<mdpos>', '--field', 'value'])++ queries.push(inputsOf(typst))++ if (w.gate) await Promise.race([w.gate, dead])++ if (killed) return { value: { code: null, signal: 'SIGTERM' } }++ yield { stream: 'stdout', text: JSON.stringify(SMALL_MARKS) }++ return { value: { code: 0, signal: null } }++ })+ on('process.run', async ($: any, e: any) => {+ const argv: string[] = e.argv+ const cmd = argv.join(' ')- if (/md-preview-/.test(cmd)) return ok('/c\nDarwin\n')++ if (argv[0] === 'kill') {++ kills.push(argv[1]!)++ killers.get(argv[1]!)?.()++ return ok('')++ }++ if (/intelligent-ui-/.test(cmd)) return ok('/c\nDarwin\n')+ if (cmd.includes('command -v typst')) return ok('/usr/bin/typst\n')+ if (argv[0] === '/usr/bin/typst' && argv[1] === 'eval') return ok('{}')- if (argv[0] === '/usr/bin/typst' && argv[1] === 'compile') return ok('')- if (argv[0] === '/usr/bin/typst' && argv[1] === 'query') {- expect(argv).toContain('probe=1')- expect(argv.slice(-3)).toEqual(['<mdpos>', '--field', 'value'])- return ok(JSON.stringify(SMALL_MARKS))- }- if (cmd.includes('od -An')) return ok(`${HEAD}\n@\n`)++ if (cmd.includes('od -An')) return ok(argv.filter(a => a.endsWith('.png')).map(() => `${HEAD}\n@\n`).join(''))+ if (argv[0] === 'pbpaste') {- pastes++- return ok(clipboard)++ w.pastes++++ return ok(w.clipboard)+ }+ return ok('', 1)+ })+ on('fs.write', async ($: any, e: any) => {+ files.set(e.path, e.text)+ return { value: undefined }+ })+ on('fs.read', async ($: any, e: any, next: any) => (files.has(e.path) ? { value: files.get(e.path) } : e.path.startsWith('/c/') ? { deny: 'ENOENT' } : next(e)))- on('fs.list', async ($: any, e: any, next: any) => (e.path.startsWith('/c/') ? { value: [{ name: 'a-1.png', kind: 'file', size: 1, mtimeMs: 1, isLink: false }] } : next(e)))++ on('fs.list', async ($: any, e: any, next: any) => {++ if (!e.path.startsWith('/c/')) return next(e)++ const tag = files.has(`${e.path}/b-1.png`) || (o.failFirst && compiles.length > 1) ? 'b' : 'a'++ return { value: [{ name: `${tag}-1.png`, kind: 'file', size: 1, mtimeMs: 1, isLink: false }] }++ })+ on('ui.copy', async ($: any, e: any) => {- copies.push(e.text)- clipboard = e.text++ w.copies.push(e.text)++ w.clipboard = e.text+ return { value: { isCopied: true } }+ })- on('ui.selection', async () => ({ value: undefined }))++ on('ui.selection', async () => ({ value: w.selection }))+ on('ui.toast', async ($: any, e: any) => {- toasts.push(String(e.text ?? e.message ?? JSON.stringify(e)))++ w.toasts.push(String(e.text))+ return { value: undefined }+ })+ on('ui.render', () => ({ type: 'Text', props: {}, children: ['engine drawing'] }) as any)- await $.command.run({ command: 'md-preview', args: '' } as any)- const props = { text: SMALL_MD, isFirstOfReply: true }- const ui = await $.ui.mount({ plugin: 'md-preview', surface: 'terminal', component: 'AssistantMessage', requestId: 'ans-1', props, viewport: { columns: 100, rows: 40 } } as any)- await clock.settle()- await ui.redraw(props as any)- await clock.settle()- // The probe ran after the PNGs, by itself.- expect([...files.keys()].some(k => k.endsWith('/positions.json'))).toBe(true)- expect([...files.keys()].some(k => k.endsWith('/probe.json'))).toBe(true)++ return w++}+- // A clipboard with no placeholders is never written.- await clock.advance(300)- expect(pastes).toBeGreaterThan(0)- expect(copies).toEqual([])++const message = (requestId: string, text: string) =>++ ({++ plugin: 'intelligent-ui', surface: 'terminal', component: 'AssistantMessage', requestId,++ props: { text, isFirstOfReply: true }, viewport: { columns: 100, rows: 40 },++ }) as any++const props = (text: string) => ({ text, isFirstOfReply: true }) as any++const written = (files: Map<string, string>, name: string) => [...files.keys()].filter(k => k.endsWith(`/${name}`))++++// Draws SMALL_MD as answer `id` (98 columns: the fixture's), compiled; the++// watcher's first tick (it only notes the selection there is) has run.++async function drawAnswer($: any, w: ReturnType<typeof world>, id = 'ans-1') {++ const ui = await $.ui.mount(message(id, SMALL_MD))++ await w.clock.settle()++ await ui.redraw(props(SMALL_MD))++ await w.clock.settle()++ await w.clock.advance(300)++ return ui++}+++test('a compile writes probe.json with the PNG compile inputs and runs no probe; a copy runs it then', async ($, on) => {++ const w = world(on)++ await $.command.run({ command: 'iui', args: '' } as any)++ await drawAnswer($, w)++ expect(w.compiles.length).toBe(1)++ expect(written(w.files, 'probe.json').length).toBe(1)++ expect(written(w.files, 'positions.json')).toEqual([])++ expect(w.queries).toEqual([])++ // The probe's inputs are the compile's, and probe=1.++ const probe = JSON.parse(w.files.get(written(w.files, 'probe.json')[0]!)!)++ expect(Math.round(probe.ppi * 1000)).toBe(198056)++ expect(inputsOf(probe.argv)).toEqual({ ...w.compiles[0], probe: '1' })++ expect(probe.argv).toEqual(probeCall({ typst: '/usr/bin/typst', root: probe.argv[5].replace(/\/render\/packages$/, ''), cache: '/c', inputs: w.compiles[0]! }).argv)++ // A copy needs the positions: the probe runs now, once.++ w.clipboard = [cells(1, 0, 97, '⏺ '), cells(2, 0, 97), cells(3, 0, 21)].join('\n')++ await w.clock.advance(300)++ await w.clock.settle()++ expect(w.queries.length).toBe(1)++ expect(written(w.files, 'positions.json').length).toBe(1)++ expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])++})++++test('a compile retried in safe mode gives the probe safe=1', async ($, on) => {++ const w = world(on, { failFirst: true })++ await $.command.run({ command: 'iui', args: '' } as any)++ await drawAnswer($, w)++ expect(w.compiles.map(c => c.safe)).toEqual([undefined, '1'])++ const probe = JSON.parse(w.files.get(written(w.files, 'probe.json')[0]!)!)++ expect(inputsOf(probe.argv)).toEqual({ ...w.compiles[1], probe: '1' })++})++++test('the probe runs ahead once nothing compiles, and a new job stops it', async ($, on) => {++ const w = world(on)++ await $.command.run({ command: 'iui', args: '' } as any)++ await drawAnswer($, w)++ expect(w.queries).toEqual([])++ // Idle: the newest drawing with no positions is probed, held here.++ w.hold()++ await w.clock.advance(PROBE_IDLE_MS)++ await w.clock.settle()++ expect(w.queries.length).toBe(1)++ // A new answer compiles: the probe ahead is killed, nothing is written.++ const other = await $.ui.mount(message('ans-2', 'Another **answer**.'))++ await w.clock.settle()++ expect(w.kills.length).toBe(1)++ w.release()++ await w.clock.settle()++ expect(written(w.files, 'positions.json')).toEqual([])++ await other.redraw(props('Another **answer**.'))++ await w.clock.settle()++ // Idle again: one probe at a time, the newest first, then the next.++ w.gate = null++ await w.clock.advance(PROBE_IDLE_MS)++ await w.clock.settle()++ expect(w.queries.length).toBe(3)++ expect(written(w.files, 'positions.json').length).toBe(2)++})++++test('a mouse copy of a drawn answer is read from the clipboard and written back as text, once', async ($, on) => {++ const w = world(on)++ await $.command.run({ command: 'iui', args: '' } as any)++ // No picture drawn: no clipboard reads.++ await w.clock.advance(900)++ expect(w.pastes).toBe(0)++ await drawAnswer($, w)++ // A clipboard with no placeholders is never written.++ await w.clock.advance(300)++ expect(w.pastes).toBeGreaterThan(0)++ expect(w.copies).toEqual([])+ // The heading row and the start of the paragraph, as a mouse copy takes them.- clipboard = [cells(1, 0, 97, '⏺ '), cells(2, 0, 97), cells(3, 0, 97), cells(4, 0, 21)].join('\n')- await clock.advance(300)- await clock.settle()- expect(copies).toEqual(['Copy test\nThe quick brown fox jumps'])- expect(toasts).toContain('md-preview: copied 35 chars of text')++ w.clipboard = [cells(1, 0, 97, '⏺ '), cells(2, 0, 97), cells(3, 0, 21)].join('\n')++ await w.clock.advance(300)++ await w.clock.settle()++ expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])++ expect(w.toasts).toContain('Intelligent UI: copied 35 chars of text')+ // Our own write is not read again.- await clock.advance(900)- expect(copies.length).toBe(1)-- const dumped = await $.command.run({ command: 'md-preview', args: 'dump' } as any)++ await w.clock.advance(900)++ expect(w.copies.length).toBe(1)++ const dumped = await $.command.run({ command: 'iui', args: 'dump' } as any)+ expect(dumped.text).toContain('U+10EEEE[1,0]')+ expect(dumped.text).toContain('-> answer ans-1 page 0')- expect(files.has('/c/copy-debug.json')).toBe(true)++ expect(w.files.has('/c/copy-debug.json')).toBe(true)++ // Off: the watcher stops.++ await $.command.run({ command: 'iui', args: 'off' } as any)++ const pastes = w.pastes++ await w.clock.advance(900)++ expect(w.pastes).toBe(pastes)++})++++test('a new mouse selection with picture cells is copied at the next tick, with no clipboard read', async ($, on) => {++ const w = world(on)++ await $.command.run({ command: 'iui', args: '' } as any)++ await drawAnswer($, w, 'ans-1')++ await drawAnswer($, w, 'ans-0')++ // ans-0 is newer, but the selection names its row: ans-1.++ w.selection = { text: [cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n'), requestId: 'ans-1' }++ const pastes = w.pastes++ await w.clock.advance(300)++ await w.clock.settle()++ expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])++ expect(w.pastes).toBe(pastes)++ const dumped = await $.command.run({ command: 'iui', args: 'dump' } as any)++ expect(dumped.text).toContain('-> answer ans-1 page 0')++ // The same selection again: not copied again.++ await w.clock.advance(600)++ expect(w.copies.length).toBe(1)++ // /iui grab copies it on request.++ const grabbed = await $.command.run({ command: 'iui', args: 'grab' } as any)++ expect(grabbed.text).toBe('Intelligent UI: copied 35 chars (1 of 1 picture runs read, row ans-1).')++ expect(w.copies.length).toBe(2)++})++++// Another plugin's `$.ui.copy`, from its command `cp` (args: the text).++const COPIER = {++ name: 'copier',++ register: (on: any) => {++ on('command.run', { command: 'cp' }, async ($: any, e: any) => ({ text: JSON.stringify(await $.ui.copy({ text: e.args })) }))++ },++}++++test('a copy of picture cells through $.ui.copy is rewritten to their text; other copies pass as they are', { plugins: [COPIER] }, async ($, on) => {++ const w = world(on)++ await $.command.run({ command: 'iui', args: '' } as any)++ await drawAnswer($, w)++ const got = await $.command.run({ command: 'cp', args: [cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n') } as any)++ expect(JSON.parse(got.text!)).toEqual({ isCopied: true })++ expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])++ await $.command.run({ command: 'cp', args: 'plain text' } as any)++ expect(w.copies[1]).toBe('plain text')++})++++test('a clipboard with picture cells that is not this session\'s selection is not rewritten (another session\'s copy)', async ($, on) => {++ const w = world(on)++ await $.command.run({ command: 'iui', args: '' } as any)++ await drawAnswer($, w)++ // This session has a selection of its own (no picture cells), and the++ // clipboard has another session's picture cells.++ w.selection = { text: 'my own text', requestId: 'u1' }++ w.clipboard = [cells(1, 0, 97), cells(3, 0, 21)].join('\n')++ await w.clock.advance(600)++ expect(w.copies).toEqual([])++ // The same copy as the selection, with a last line break: rewritten.++ w.selection = { text: [cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n'), requestId: 'ans-1' }++ await $.command.run({ command: 'iui', args: 'off' } as any)++ await $.command.run({ command: 'iui', args: 'on' } as any)++ await drawAnswer($, w, 'ans-2')++ w.clipboard = `${w.selection.text}\n`++ await w.clock.advance(300)++ await w.clock.settle()++ expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])++})++++test('a watcher that starts again (a hot reload) does not copy the selection that was there before', async ($, on) => {++ const w = world(on)++ // An old selection with picture cells, and a clipboard filled elsewhere.++ w.selection = { text: [cells(1, 0, 97), cells(3, 0, 21)].join('\n'), requestId: 'ans-1' }++ w.clipboard = 'copied in another app'++ await $.command.run({ command: 'iui', args: '' } as any)++ await drawAnswer($, w)++ await w.clock.advance(900)++ expect(w.copies).toEqual([])++ expect(w.clipboard).toBe('copied in another app')++ // A new selection is copied.++ w.selection = { text: [cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n'), requestId: 'ans-1' }++ await w.clock.advance(300)++ await w.clock.settle()++ expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])++})++++test('a selection that can not be read gives one toast, not one more from the clipboard', async ($, on) => {++ const w = world(on)++ await $.command.run({ command: 'iui', args: '' } as any)++ await drawAnswer($, w)++ // Column 150: wider than any picture drawn.++ const text = [cells(1, 0, 150), cells(2, 0, 150)].join('\n')++ w.selection = { text, requestId: 'ans-1' }++ w.clipboard = text++ await w.clock.advance(900)++ await w.clock.settle()++ expect(w.copies).toEqual([])++ expect(w.toasts.filter(t => t.startsWith('Intelligent UI: could not read')).length).toBe(1)++})++++test('a $.ui.copy of the selection is not copied again by the watcher', { plugins: [COPIER] }, async ($, on) => {++ const w = world(on)++ await $.command.run({ command: 'iui', args: '' } as any)++ await drawAnswer($, w)++ const text = [cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n')++ w.selection = { text, requestId: 'ans-1' }++ await $.command.run({ command: 'cp', args: text } as any)++ await w.clock.advance(900)++ await w.clock.settle()++ expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])++ expect(w.toasts.filter(t => t.startsWith('Intelligent UI: copied')).length).toBe(0)+})