Skip to content

Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.

TypeScript claude-code-mod

Grid: /iui grid on|off puts each text line of a picture on the terminal's rows

razorback16fa545c14ff62
diff --git a/README.md b/README.md
index 427151d..715f534 100644
--- a/README.md
+++ b/README.md
@@ -79,6 +79,7 @@ More in the [gallery](docs/gallery.md): plots, fractals and a tour of all the Ma
| `/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 grid on` / `off` | Puts each line of text on the terminal rows, so that a mouse selection covers the text (off by default) |
| `/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 |
diff --git a/docs/limitations.md b/docs/limitations.md
index fa7aeae..eecd5d2 100644
--- a/docs/limitations.md
+++ b/docs/limitations.md
@@ -12,13 +12,16 @@
- 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, because it acts only when the clipboard changes. It changes only a clipboard that has picture cells (for example, after a copy with a key).
- **Links in a picture:** a click on the picture does not open a link, because the mod cannot put a link on a picture. Use the link rows under the picture (refer to [Links, file paths and commands](usage.md#links-file-paths-and-commands)). A click on a command row copies the command only where Claude Code gets mouse clicks (fullscreen mode). A `file://` link opens in the app that the terminal chooses. A file row shows only when the file exists when the mod draws the answer.
+- **The row grid** (`/iui grid on`, refer to [Selection and the row grid](usage.md#selection-and-the-row-grid)) has these limits:
+ - Inline math that is taller than a row adds 1 row or more to its line. The text stays on the rows. Math that is only a little taller than the row does not add a row, and its ink can come near the line above or below.
+ - With a large text size (`/iui size`), a line uses 2 rows. A line of code uses 2 rows from approximately 111%. A line of body text uses 2 rows from approximately 117%. These values change with the terminal font and the cell size.
- **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.
+- **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 (with `/iui grid on`, the items of a loose list have a gap of one row).
- **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 --git a/docs/usage.md b/docs/usage.md
index 0923aa0..961ae00 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -33,7 +33,7 @@ Intelligent UI draws Claude's answers as rendered Markdown pictures. Only the dr
| 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` | Shows the state, the theme, the text size, the width, the image height and the row grid, 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, why the terminal can or cannot show pictures, and if the automatic copy is on (`Auto copy:`) |
| `/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) |
@@ -45,6 +45,9 @@ Intelligent UI draws Claude's answers as rendered Markdown pictures. Only the dr
| `/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 grid` | Shows the row grid setting: on or off |
+| `/iui grid on` | Puts each line of text in a picture on the terminal rows (kept for later sessions). Refer to [Selection and the row grid](#selection-and-the-row-grid). |
+| `/iui grid off` | Lines of text in a picture have the usual spacing (kept for later sessions). This is the default. |
| `/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). |
@@ -78,6 +81,18 @@ If the clipboard did not change, use `/iui grab`. It reads the last mouse select
For the limits, refer to [Limitations](limitations.md).
+## Selection and the row grid
+
+The terminal draws a mouse selection as full cells, thus a selection covers full rows. Usually, the lines of text in a picture are not on the terminal rows. A line of body text is approximately 1.3 rows tall, and a line in a list or a table is approximately 1.6 rows tall. Thus, after some lines, the selection is not on the text that the mod copies.
+
+`/iui grid on` puts each line of text on the terminal rows:
+
+- Each line of body text, a list, a quote or a table uses one row (or more rows if the text is large). The text is in the middle of its rows.
+- Each heading, each code line and each gap between blocks uses full rows.
+- Some blocks have a height that the mod cannot set, for example display math, an image or a Typst drawing. The mod adds space to such a block, so that its height is a number of full rows.
+
+Thus the selection covers the text that the mod copies. The lines are closer together than without the grid, so the look is not the same as VS Code. The grid is off by default. 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:
diff --git a/hooks/lib/answer.ts b/hooks/lib/answer.ts
index f10d089..a6a5f04 100644
--- a/hooks/lib/answer.ts
+++ b/hooks/lib/answer.ts
@@ -107,13 +107,13 @@ export async function pagesOf($: EngineInterface, o: PagesInput): Promise<Drawin
const room = await roomOf($, { hasRoom, textHash, base, env, rows, widthPt, rowPt, isLive: liveNow() })
const key = renderKey({
textHash, columns, cell, size: S.size, mode: S.theme, termFont: env.termFont,
- columnPt, templateStamp: env.stamp, look: active, inline: env.inline, base, room,
+ columnPt, templateStamp: env.stamp, look: active, inline: env.inline, base, room, grid: S.grid,
})
const seen = lastText.get(id)
const changed = seen !== text
lastText.set(id, text)
const job: Job = {
- key, requestId: id, text, columns, cell, theme: S.theme, size: S.size, themeDir: active.dir, env, epoch: S.epoch,
+ key, requestId: id, text, columns, cell, theme: S.theme, size: S.size, grid: S.grid, themeDir: active.dir, env, epoch: S.epoch,
...(base ? { base } : {}), ...(room ? { room } : {}), ...(o.onScreen !== undefined ? { onScreen: o.onScreen } : {}),
}
// The picture drawn last for the same text, at another key.
diff --git a/hooks/lib/command.ts b/hooks/lib/command.ts
index 4ab9112..a25723e 100644
--- a/hooks/lib/command.ts
+++ b/hooks/lib/command.ts
@@ -10,15 +10,16 @@ import { isThemeName, type ThemeInfo } from './themes'
import { commandRegister } from './api'
// `/iui` arguments: on, off, size <80-200>, width [40-400|full],
-// 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.
+// height [6-200|half|full], grid [on|off], 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`, `height` or `grid` with no value shows it.
export type Command =
| { kind: 'on' | 'off' | 'show' | 'details' | 'probe' | 'grab' | 'dump' }
| { kind: 'size'; percent: number }
| { kind: 'width'; width?: Width }
| { kind: 'height'; height?: Height }
+ | { kind: 'grid'; grid?: boolean }
| { kind: 'theme'; name?: string }
| { kind: 'setup'; remove: boolean }
| { kind: 'bad' }
@@ -52,16 +53,20 @@ export function parseCommand(args: string): Command {
const height = Number.parseInt(words[1]!, 10)
if (height >= MIN_HEIGHT && height <= MAX_HEIGHT) return { kind: 'height', height }
}
+ if (words[0] === 'grid' && words.length === 1) return { kind: 'grid' }
+ if (words[0] === 'grid' && words.length === 2 && (words[1] === 'on' || words[1] === 'off')) return { kind: 'grid', grid: words[1] === 'on' }
return { kind: 'bad' }
}
-// The /iui arguments, and the sizes, widths and heights the typeahead offers.
+// The /iui arguments, and the sizes, widths, heights and grid values the
+// typeahead offers.
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: 'grid', description: 'each line of text on whole terminal rows, on or off' },
{ 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' },
@@ -71,16 +76,17 @@ const SUBCOMMANDS = [
const 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]
+const GRIDS = ['on', 'off'] as const
// 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.
+// size, a width, a height or a grid value. Right after `theme`, `size`,
+// `width`, `height` or `grid`, 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,
- o: { themes: readonly ThemeInfo[]; active: string; size: number; width?: Width; height?: Height },
+ o: { themes: readonly ThemeInfo[]; active: string; size: number; width?: Width; height?: Height; grid?: boolean },
): Suggestion[] {
const head = /^\s*\/iui\s+/.exec(text)
if (!head || start < head[0].length) return []
@@ -114,17 +120,23 @@ export function commandSuggestions(
description: h === height ? 'current' : h === DEFAULT_HEIGHT ? 'the default: half the terminal'
: h === 'full' ? `the terminal height less ${PICTURE_ROOM_ROWS} rows` : undefined,
}))
+ const grid = o.grid ? 'on' : 'off'
+ const gridRows = (prefix: string, lead: string) => GRIDS
+ .filter(g => g.startsWith(prefix))
+ .map(g => ({ text: `${lead}${g}`, label: g, description: g === grid ? 'current' : g === 'off' ? 'the default' : undefined }))
if (before.length === 0) {
if (word === 'theme') return themeRows('', 'theme ')
if (word === 'height') return heightRows('', 'height ')
if (word === 'size') return sizeRows('', 'size ')
if (word === 'width') return widthRows('', 'width ')
+ if (word === 'grid') return gridRows('', 'grid ')
return SUBCOMMANDS.filter(c => c.name.startsWith(word)).map(c => ({ text: c.name, description: c.description }))
}
if (before.length === 1 && before[0] === 'theme') return themeRows(word, '')
if (before.length === 1 && before[0] === 'size') return sizeRows(word.replace(/%$/, ''), '')
if (before.length === 1 && before[0] === 'width') return widthRows(word, '')
if (before.length === 1 && before[0] === 'height') return heightRows(word, '')
+ if (before.length === 1 && before[0] === 'grid') return gridRows(word, '')
return []
}
@@ -133,7 +145,7 @@ export function commandSuggestions(
export async function registerCommand($: EngineInterface) {
await commandRegister($, {
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), 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]',
+ 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), grid [on|off] (each line of text on whole terminal rows), 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]|grid [on|off]|theme [name]|grab|dump]',
}).catch(() => undefined)
}
diff --git a/hooks/lib/draw.tsx b/hooks/lib/draw.tsx
index 969845e..8eac341 100644
--- a/hooks/lib/draw.tsx
+++ b/hooks/lib/draw.tsx
@@ -73,6 +73,9 @@ export function renderKey(o: {
// the room height and the design. A plain text's key does not change
// with the rows.
room?: Room
+ // `/iui grid` on: the lines on the row grid, another picture. Off adds
+ // nothing, so the keys of before stay.
+ grid?: boolean
}): string {
const { room } = o
return hashOf([
@@ -80,6 +83,7 @@ export function renderKey(o: {
o.templateStamp, o.look.name, o.look.dir, o.look.stamp, TEMPLATE_VERSION, ...(o.inline ? ['inline'] : []),
...(o.base ? ['base', o.base] : []),
...(room ? ['room', room.heightPt, room.design.widthPt, room.design.heightPt] : []),
+ ...(o.grid ? ['grid'] : []),
])
}
@@ -112,7 +116,10 @@ export function firstLineOf(md: string): FirstLine {
// the first line of text on the centre of a terminal row, and which row that
// is: row 0 when the line fits there, else the first row its ink can reach
// without being cut at the picture's top. The bullet is drawn on that row.
-export function alignFirstLine(kind: FirstLine, rowPt: number): { topPt: number; bulletRow: number } {
+// With the row grid (`grid`), the first line box is row 0 at the page's top:
+// no margin, and the bullet on row 0.
+export function alignFirstLine(kind: FirstLine, rowPt: number, grid = false): { topPt: number; bulletRow: number } {
+ if (grid) return { topPt: 0, bulletRow: 0 }
const { centre, inkTop } = FIRST_LINE[kind]
const bulletRow = Math.max(0, Math.ceil((centre - inkTop + 0.5) / rowPt - 0.5 - 1e-9))
return { topPt: Math.round(((bulletRow + 0.5) * rowPt - centre) * 100) / 100, bulletRow }
diff --git a/hooks/lib/env.ts b/hooks/lib/env.ts
index 6f6b11f..b9ccc15 100644
--- a/hooks/lib/env.ts
+++ b/hooks/lib/env.ts
@@ -87,6 +87,7 @@ export function setUp($: EngineInterface): Promise<Env> {
const height = await storeGet($, 'height').catch(() => undefined)
S.height = height === 'half' || height === 'full' ? height
: Number.isInteger(height) && Number(height) >= MIN_HEIGHT && Number(height) <= MAX_HEIGHT ? Number(height) : DEFAULT_HEIGHT
+ S.grid = (await storeGet($, 'grid').catch(() => undefined)) === true
if ((await storeGet($, 'enabled').catch(() => undefined)) === false) await update($, isOn, () => false).catch(() => undefined)
const isMac = os.trim() === 'Darwin'
setFrame(await readFrame($))
diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.ts
index 182adcf..ed8dd63 100644
--- a/hooks/lib/settings.ts
+++ b/hooks/lib/settings.ts
@@ -100,6 +100,8 @@ export const heightText = (height: Height) =>
height === 'half' ? `half (half the terminal, ${PICTURE_MIN_ROWS} to ${PICTURE_MAX_ROWS} rows)`
: height === 'full' ? `full (the terminal height less ${PICTURE_ROOM_ROWS} rows)`
: `${height} rows`
+// The grid setting as words.
+export const gridText = (grid: boolean) => (grid ? 'on (each line of text on whole terminal rows)' : 'off (the default)')
export const PICTURES_KEPT = 64
// The file paths of the link rows under a picture: whether each one is a
// file, kept for this many paths (the oldest go).
diff --git a/hooks/lib/state.ts b/hooks/lib/state.ts
index 1c61272..73e677d 100644
--- a/hooks/lib/state.ts
+++ b/hooks/lib/state.ts
@@ -71,6 +71,8 @@ export type Job = {
cell: Cell
theme: IuiTheme
size: number
+ // `/iui grid`: each text line on the terminal's row grid.
+ grid: boolean
themeDir: string
env: Env
// The folder relative images start from (a Markdown file's); else env.cwd.
@@ -128,6 +130,9 @@ export const S = {
// The height setting of the pictures on screen: `height` once its epoch
// committed (with `shown`), so an image box changes in one step.
shownHeight: DEFAULT_HEIGHT as Height,
+ // `/iui grid`: each text line of a page on whole terminal rows, so a
+ // mouse selection (whole cells) covers the text it copies. Off by default.
+ grid: false,
look: null as Look | null,
// The usable themes the last scan found, for the typeahead.
themeChoices: [] as ThemeInfo[],
diff --git a/hooks/lib/typst.ts b/hooks/lib/typst.ts
index de7162a..095bd89 100644
--- a/hooks/lib/typst.ts
+++ b/hooks/lib/typst.ts
@@ -278,16 +278,17 @@ export async function runKillable(
}
// The template's inputs for a job and its ppi (the PNG compile and the
-// probe share them).
+// probe share them). With the row grid, `grid` is 1 and `top` 0.
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 { topPt } = alignFirstLine(firstLineOf(segments[0] ?? ''), rowPt, job.grid)
const inputs: Record<string, string | number> = {
theme: job.theme,
width: widthPt,
top: topPt,
row: Math.round(rowPt * 10000) / 10000,
+ ...(job.grid ? { grid: 1 } : {}),
code: fit.code,
...(job.env.termFont ? { 'term-font': job.env.termFont } : {}),
'theme-dir': job.themeDir,
@@ -438,7 +439,7 @@ export async function compile($: EngineInterface, job: Job, signal?: AbortSignal
}
pages = pages.map(p => ({ ...p, rows: Math.min(MAX_IMAGE_ROWS, p.rows) }))
}
- const { bulletRow } = alignFirstLine(firstLineOf(segments[0] ?? ''), rowPt)
+ const { bulletRow } = alignFirstLine(firstLineOf(segments[0] ?? ''), rowPt, job.grid)
const result: Result = { pages, bulletRow, ...(note ? { note } : {}) }
await fsWrite($, `${dir}/pages.json`, JSON.stringify(result))
return result
diff --git a/hooks/register.tsx b/hooks/register.tsx
index d518103..34f64f2 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -21,7 +21,7 @@ import { atom, read, update } from 'claude-code'
import type { EngineInterface, Register, RenderElement, RenderViewport } from 'claude-code'
import {
- DEFAULT_THEME, heightText, IMAGE_MAX_COLUMNS, MARGIN_TOP, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, RESULTS_KEPT, TYPST_PROMPT,
+ DEFAULT_THEME, gridText, heightText, IMAGE_MAX_COLUMNS, MARGIN_TOP, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, RESULTS_KEPT, TYPST_PROMPT,
widthText,
} from './lib/settings'
import { clip, drawnAnswers, editedPlans, keep, queue, refresh, running, S, subagentPlans, writesLive, type Env } from './lib/state'
@@ -50,7 +50,7 @@ import {
// The names this module exported before the split (the tests import them).
export {
- BASE_THEME, DEFAULT_CELL, DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_THEME, DEFAULT_WIDTH, heightText, IMAGE_MAX_COLUMNS, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH,
+ BASE_THEME, DEFAULT_CELL, DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_THEME, DEFAULT_WIDTH, gridText, heightText, IMAGE_MAX_COLUMNS, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH,
MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, PICTURE_MAX_ROWS, PICTURE_MIN_ROWS, PICTURE_ROOM_ROWS, SEGMENT_ROWS, TYPST_PROMPT, widthText, type Height, type Width,
COMMIT_MAX_MS, COMMIT_MIN_MS, DESIGNS_KEPT_DAYS, RESIZE_QUIET_MS, RESULTS_KEPT, TOUCH_FLUSH_MS,
} from './lib/settings'
@@ -444,7 +444,7 @@ export const register: Register = on => {
const got = await next(e)
if (!/^\s*\/iui\s/.test(e.text)) return got
if (!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, width: S.width, height: S.height })
+ 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, grid: S.grid })
return mine.length ? { suggestions: [...got.suggestions, ...mine] } : got
})
@@ -488,6 +488,16 @@ export const register: Register = on => {
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 === 'grid') {
+ if (asked.grid === undefined) await setUp($).catch(() => null)
+ else {
+ S.grid = asked.grid
+ beginEpoch($)
+ await storeSet($, 'grid', S.grid)
+ }
+ const head = asked.grid === undefined ? 'The row grid is' : 'The row grid is now'
+ return { text: `${head} ${gridText(S.grid)}. With the grid on, a mouse selection over a picture covers the lines it copies. Use /iui grid on, or /iui grid off (the default).` }
+ }
if (asked.kind === 'setup') {
await setUp($).catch(() => null)
return { text: await runSetup($, asked.remove) }
@@ -534,15 +544,15 @@ export const register: Register = on => {
? `this terminal draws pictures${ready.inline ? ' (over ssh, sent as bytes)' : ''}`
: 'Claude Code draws no pictures here (it does in kitty and Ghostty, in iTerm2 3.6+ and Rio 0.5.27+ with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1, over ssh when TERM names kitty or Ghostty or with that variable; never in tmux, screen or a background session; not in WezTerm, Warp, Konsole or others), so answers stay text'
const auto = `Auto copy: ${autoCopyOf(state === 'on')}`
- return { text: `Intelligent UI is ${state}, theme ${theme}, ${modeLine(S.theme, S.setting, S.settingRaw, S.host)}, text size ${S.size}%, width ${widthText(S.width)}, image and drawing height ${heightText(S.height)}, ${font}. ${typst}; ${terminal}.\n${auto}` }
+ return { text: `Intelligent UI is ${state}, theme ${theme}, ${modeLine(S.theme, S.setting, S.settingRaw, S.host)}, text size ${S.size}%, width ${widthText(S.width)}, image and drawing height ${heightText(S.height)}, row grid ${S.grid ? 'on' : 'off'}, ${font}. ${typst}; ${terminal}.\n${auto}` }
}
// The short state: what is set, and only the problems that keep pictures away.
const sized = (v: number | 'full' | 'half', unit: string) => (typeof v === 'number' ? `${v} ${unit}` : v)
- const lines = [`Intelligent UI is ${state}: theme ${theme}, ${S.theme}, text ${S.size}%, width ${sized(S.width, 'columns')}, height ${sized(S.height, 'rows')}.`]
+ const lines = [`Intelligent UI is ${state}: theme ${theme}, ${S.theme}, text ${S.size}%, width ${sized(S.width, 'columns')}, height ${sized(S.height, 'rows')}, grid ${S.grid ? 'on' : 'off'}.`]
if (S.setupNeeded) lines.push('In iTerm2, run /iui setup once to show pictures.')
else if (!ready.canDraw) lines.push('This terminal shows no pictures, so answers stay text. Pictures show in kitty, Ghostty and iTerm2 3.6+.')
if (!ready.typst) lines.push('Typst is not installed, so answers stay text. Install it: brew install typst')
- lines.push('Change: /iui on | off | size | width | height | theme. More: /iui details')
+ lines.push('Change: /iui on | off | size | width | height | grid | theme. More: /iui details')
return { text: bad + lines.join('\n') }
})
diff --git a/render/md.typ b/render/md.typ
index 4dfb642..27d7563 100644
--- a/render/md.typ
+++ b/render/md.typ
@@ -12,6 +12,7 @@
// top=<pt> the first page's top margin (default 6)
// row=<pt> one terminal row; each page is padded to whole rows
// (default 0 = no padding)
+// grid=1 the row grid (optional; needs row; below)
// code=<fraction> code size as a fraction of the body text (default 0.9)
// term-font=<family> the terminal's font, used first for code (optional)
// height=<pt> the room height of one drawing now (default 0 =
@@ -36,6 +37,13 @@
//
// safe=1: the retry mode after a failed compile. `typst` fences are shown as
// code (no eval), math is shown as code (no mitex), images are alt boxes.
+//
+// grid=1: every line of text lies on the terminal's row grid, so a selection
+// of whole rows covers whole lines. Each line box is a whole number of rows
+// with its text centred, every block starts and ends on a row boundary, and
+// blocks of free height (display math, live drawings, images) are made a
+// whole number of rows. Every page's top margin is 0 (`top` is not used).
+// With row=0, grid=1 does nothing.
#import "@preview/cmarker:0.1.6"
#import "@preview/mitex:0.2.7": mitex-convert, mitex-scope
@@ -57,6 +65,8 @@
// One terminal row in pt: each page is padded to a whole number of rows, so
// its picture fills its box exactly. 0 = no padding.
#let row = float(inp.at("row", default: "0")) * 1pt
+// The row grid (grid=1, only with a row; see the top).
+#let on-grid = row > 0pt and inp.at("grid", default: "0") not in ("", "0", "false", "no", "off")
// Code size as a fraction of the body text (the hooks module sets it so code
// in the terminal's font is the terminal's own size).
#let code-scale = float(inp.at("code", default: "0.9"))
@@ -152,6 +162,27 @@
#set par(leading: E.text.leading-em * 1em, spacing: E.text.paragraph-em * 1em, justify: false)
#set block(spacing: E.text.paragraph-em * 1em)
+// ---------- the row grid (grid=1) ----------
+// Lengths on the grid: `rows-near` the whole rows nearest a length (gaps,
+// padding), `rows-up` the whole rows (at least one) a height needs.
+#let rows-near(x) = calc.round(x / row) * row
+#let rows-up(x) = calc.max(1, calc.ceil(x / row - 0.001)) * row
+// Fixed text edges for the current font and size (needs context) that make
+// one line box exactly `rows` rows, with the ink of a line (the tops of
+// "bdfhkl" to the bottoms of "gjpqy") centred in it: centring the font's
+// ascender-to-descender box instead puts large text visibly low. `rows` is
+// the least number of rows that this ink and a gap of 0.1em need: 1 for the
+// body text at the usual sizes (its ascender-to-descender box is then a
+// little more than the row; only the ink must not touch). With par leading
+// 0, the lines of a paragraph are then exactly `rows` rows apart.
+#let grid-edges() = {
+ let up = measure(text(top-edge: "bounds", bottom-edge: "baseline", "bdfhkl")).height
+ let down = measure(text(top-edge: "baseline", bottom-edge: "bounds", "gjpqy")).height
+ let n = calc.max(1, calc.ceil((up + down + 0.1em.to-absolute()) / row - 0.001))
+ let mid = (up - down) / 2
+ (top: mid + n * row / 2, bottom: mid - n * row / 2, rows: n)
+}
+
// ---------- headings ----------
#set heading(numbering: none)
#show heading: it => {
@@ -160,6 +191,27 @@
let size = at-level(H.size-em, lvl - 1) * 1em
let above = at-level(H.above-em, lvl - 1) * 11pt
let below = at-level(H.below-em, lvl - 1) * 11pt
+ if on-grid {
+ // The grid: a line box of whole rows (3 for h1 and 2 for h2 at the
+ // usual sizes: Typst's own heading rule makes h1 1.4em and h2 1.2em of
+ // the theme's size, so h1 is 30.8pt), whole-row gaps (at least one), and
+ // the rule on the bottom row boundary (no padding under the text: it
+ // would add height).
+ return {
+ set text(size: size, weight: H.weight)
+ context {
+ let g = grid-edges()
+ set text(top-edge: g.top, bottom-edge: g.bottom)
+ show raw: set text(top-edge: g.top, bottom-edge: g.bottom)
+ set par(leading: 0pt)
+ block(
+ width: 100%, above: calc.max(row, rows-near(above)), below: calc.max(row, rows-near(below)), sticky: true,
+ stroke: if lvl <= H.rule-levels { (bottom: px + C.border) },
+ it.body,
+ )
+ }
+ }
+ }
set text(size: size, weight: H.weight)
set par(leading: H.leading-em * 1em)
if lvl <= H.rule-levels {
@@ -222,8 +274,11 @@
let pad-y = IC.pad-y-px * px
// A zero-width strut of the body text: a line with only code (a table
// cell, a list item) gets the body's line box, so its baseline is where
- // the text next to it has its baseline (the code font is smaller).
- text(font: sans, size: text.size, top-edge: "ascender", bottom-edge: "descender", sym.zwj)
+ // the text next to it has its baseline (the code font is smaller). On
+ // the grid, the strut keeps the grid's edges (the line box of one row).
+ if on-grid { text(font: sans, size: text.size, sym.zwj) } else {
+ text(font: sans, size: text.size, top-edge: "ascender", bottom-edge: "descender", sym.zwj)
+ }
h(pad-x)
highlight(
fill: C.inline-code-bg, extent: pad-x, radius: IC.radius-px * px,
@@ -239,6 +294,20 @@
#show raw.where(block: true): it => context {
let fg = if it.lang == none { C.at("code-plain-fg", default: C.code-fg) } else { C.code-fg }
let CB = E.code-block
+ if on-grid {
+ // The grid: each code line exactly one row (the code is the terminal's
+ // font at its size), padding of whole rows (16px is about one row).
+ let g = grid-edges()
+ return {
+ set text(top-edge: g.top, bottom-edge: g.bottom)
+ set par(leading: 0pt, justify: false)
+ block(
+ width: 100%, fill: C.code-bg, stroke: CB.border-px * px + C.code-border,
+ radius: CB.radius-px * px, inset: (x: CB.pad-px * px, y: rows-near(CB.pad-px * px)), above: row, below: row,
+ text(fill: fg, it),
+ )
+ }
+ }
let area = measure(text(top-edge: "ascender", bottom-edge: "descender", "x")).height
set par(leading: calc.max(0pt, CB.line-height * text.size - area), justify: false)
block(
@@ -255,18 +324,25 @@
// every other block.
#show quote.where(block: true): it => {
let Q = E.quote
+ // The grid: whole-row gaps and padding (0.55em is nearer to no row than
+ // to one, so the bar is as tall as the text's rows), and one row between
+ // the blocks in it (Typst's own quote rule gives them 2.4em above and
+ // 1.8em below).
+ let gap = if on-grid { row } else { E.text.paragraph-em * 1em }
block(
width: 100%, fill: C.quote-bg, radius: Q.radius-px * px,
- above: E.text.paragraph-em * 1em, below: E.text.paragraph-em * 1em,
+ above: gap, below: gap,
stroke: (left: Q.bar-px * px + C.quote-border),
- inset: (left: (Q.pad-left-px + Q.bar-px) * px, right: Q.pad-right-px * px, y: Q.pad-y-em * 1em),
- it.body,
+ inset: (left: (Q.pad-left-px + Q.bar-px) * px, right: Q.pad-right-px * px, y: if on-grid { rows-near(Q.pad-y-em * 11pt) } else { Q.pad-y-em * 1em }),
+ if on-grid { set block(spacing: row); it.body } else { it.body },
)
}
// ---------- tables ----------
+// The grid: each table row is whole rows (padding of whole rows: 5px is
+// none), so the rules lie on row boundaries.
#set table(
- inset: (x: E.table.pad-x-px * px, y: E.table.pad-y-px * px),
+ inset: (x: E.table.pad-x-px * px, y: if on-grid { rows-near(E.table.pad-y-px * px) } else { E.table.pad-y-px * px }),
stroke: (x, y) => if y == 1 { (top: E.table.border-px * px + C.th-border) } else if y > 1 { (top: E.table.border-px * px + C.border) },
)
#show table.cell.where(y: 0): set text(weight: E.table.header-weight)
@@ -367,8 +443,10 @@
#let item-mark(prefix, body) = if not probe { body } else { mark("b", kind: "item", prefix: prefix); body }
// ---------- helpers ----------
+// On the grid, the boxes below have no padding above and below (it would
+// make the line taller than its row): the frame is the row, made 1pt smaller.
#let alt-box(alt, why: none) = box(
- stroke: px + C.muted, inset: (x: 4pt, y: 1.5pt), outset: (y: 1pt), radius: 3pt,
+ stroke: px + C.muted, inset: (x: 4pt, y: if on-grid { 0pt } else { 1.5pt }), outset: (y: if on-grid { -1pt } else { 1pt }), radius: 3pt,
text(fill: C.muted, size: 0.9em, {
"🖼 "
if alt == none or alt == "" { if why == none { "image" } else { why } } else { alt }
@@ -410,7 +488,15 @@
let w = if room-h > 0pt and nat.width > 0pt and w * (nat.height / nat.width) > room-h {
room-h * (nat.width / nat.height)
} else { w }
- image(full, width: w, alt: alt)
+ if on-grid {
+ // The grid: the image centred in a box of whole rows, lowered by the
+ // line's descent, so its line is exactly those rows.
+ let h = if nat.width > 0pt { w * (nat.height / nat.width) } else { nat.height }
+ let desc = if type(text.bottom-edge) == length { -text.bottom-edge } else { 0pt }
+ box(height: rows-up(h), baseline: desc, align(horizon, image(full, width: w, alt: alt)))
+ } else {
+ image(full, width: w, alt: alt)
+ }
}))
}
@@ -542,7 +628,13 @@
table(columns: columns, ..args)
}
-#let md-rule() = block(above: E.rule.gap-em * 1em, below: E.rule.gap-em * 1em, line(length: 100%, stroke: E.rule.border-px * px + C.border))
+#let md-rule() = if on-grid {
+ // The grid: one row with the line in its middle, whole-row gaps.
+ let gap = calc.max(row, rows-near(E.rule.gap-em * 11pt))
+ block(height: row, above: gap, below: gap, align(horizon, line(length: 100%, stroke: E.rule.border-px * px + C.border)))
+} else {
+ block(above: E.rule.gap-em * 1em, below: E.rule.gap-em * 1em, line(length: 100%, stroke: E.rule.border-px * px + C.border))
+}
// ---------- task lists: "- [x] done" / "- [ ] todo" ----------
#let checkbox(checked) = box(
@@ -592,26 +684,38 @@
(m.captures.at(0) != " ", kids.slice(n).join())
}
+// A loose list (a blank line between its items or between the blocks of an
+// item): cmarker ends each paragraph of its items with a parbreak, a tight
+// list has none. On the grid, the items of a loose list have one row
+// between them (the items of a tight list touch, as the lines of a
+// paragraph do).
+#let loose(items) = items.any(it => type(it) == content and it.func() == [].func() and it.children.any(c => c.func() == parbreak))
+#let item-gap(items) = if on-grid and loose(items) { (spacing: row) } else { (:) }
+
#let md-list(..args) = {
let items = args.pos()
+ let gap = item-gap(items)
let tasks = items.map(task-split)
if probe {
items = items.zip(tasks).map(((it, t)) => item-mark(if t == none { "- " } else if t.at(0) { "- [x] " } else { "- [ ] " }, it))
tasks = tasks.zip(items).map(((t, it)) => if t == none { none } else { (t.at(0), item-mark(if t.at(0) { "- [x] " } else { "- [ ] " }, t.at(1))) })
}
- if tasks.all(t => t == none) { return list(..args.named(), ..items) }
+ if tasks.all(t => t == none) { return list(..args.named(), ..gap, ..items) }
if tasks.all(t => t != none) {
// GitHub-style: no bullet, the checkbox sits where the bullet would.
+ // The grid: a strut of the text (its line box) beside each checkbox, so
+ // the checkbox sits on its row's baseline, and no gap between rows (one
+ // row in a loose list).
let rows = tasks.map(t => (
- align(right, checkbox(t.at(0))),
+ align(right, if on-grid { [#sym.zwj#checkbox(t.at(0))] } else { checkbox(t.at(0)) }),
t.at(1),
))
pad(left: 0.45em, grid(
- columns: (1.4em, 1fr), column-gutter: 0.55em, row-gutter: 0.38em + 0.15em,
+ columns: (1.4em, 1fr), column-gutter: 0.55em, row-gutter: if on-grid { gap.at("spacing", default: 0pt) } else { 0.38em + 0.15em },
..rows.flatten(),
))
} else {
- list(..args.named(), ..items.zip(tasks).map(((it, t)) => if t == none { it } else {
+ list(..args.named(), ..gap, ..items.zip(tasks).map(((it, t)) => if t == none { it } else {
[#checkbox(t.at(0)) #t.at(1)]
}))
}
@@ -621,12 +725,13 @@
#let md-enum(..args) = {
let start = args.named().at("start", default: 1)
let start = if type(start) == int { start } else { 1 }
+ let gap = item-gap(args.pos())
let items = args.pos().enumerate().map(((i, it)) => {
let t = task-split(it)
let it = if t == none { it } else { [#checkbox(t.at(0)) #t.at(1)] }
item-mark(str(start + i) + ". ", it)
})
- enum(..args.named(), ..items)
+ enum(..args.named(), ..gap, ..items)
}
// ---------- ```typst fences: live Typst ----------
@@ -660,7 +765,7 @@
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 => {
+ std.block(width: 100%, above: if on-grid { row } else { 1.2em }, below: if on-grid { row } else { 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
@@ -675,11 +780,13 @@
// 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))
+ let drawn = scale(k * 100%, origin: top + left, reflow: true, std.block(width: calc.max(w, wide), drawing))
+ // The grid: the drawing centred in whole rows.
+ if on-grid { std.block(height: rows-up(measure(drawn, width: space).height), align(horizon, drawn)) } else { drawn }
}))
} 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,
+ std.block(above: if on-grid { row } else { 1.2em }, below: 0pt, sticky: true,
text(size: 0.85em, fill: C.muted, style: "italic")[Typst source (not drawn: the answer failed to compile)])
raw(src, block: true, lang: "typst")
} else {
@@ -770,10 +877,75 @@
}
#let kbd(attrs, body) = box(
- stroke: px + C.border, inset: (x: 3pt, y: 1pt), outset: (y: 1pt), radius: 3pt,
+ stroke: px + C.border, inset: (x: 3pt, y: if on-grid { 0pt } else { 1pt }), outset: (y: if on-grid { -1pt } else { 1pt }), radius: 3pt,
text(font: mono, size: 0.9em, body),
)
+// ---------- the row grid: the page's rules (grid=1) ----------
+// The rules of a page on the grid, over the rules above (the elements with
+// their own grid branch above: headings, code blocks, quotes, tables, task
+// lists, rules, images, live drawings, alt and kbd boxes).
+#let grid-rules(body) = context {
+ let g = grid-edges()
+ // The line box's height above and below the baseline.
+ let (asc, desc) = (g.top, -g.bottom)
+ // Body text: line boxes of exactly g.rows rows (fixed edges, no leading),
+ // one row between paragraphs and blocks. Any smaller text (inline code,
+ // footnotes, sub- and superscripts) gets the same fixed edges, so it never
+ // makes its line taller.
+ set text(top-edge: g.top, bottom-edge: g.bottom)
+ show raw: set text(top-edge: g.top, bottom-edge: g.bottom)
+ // Raised and lowered text (footnote numbers): x-height to baseline edges,
+ // which stay inside the line box, so it never makes its line taller.
+ show super: set text(top-edge: "x-height", bottom-edge: "baseline")
+ show sub: set text(top-edge: "x-height", bottom-edge: "baseline")
+ set par(leading: 0pt, spacing: row)
+ set block(spacing: row)
+ show table: set par(leading: 0pt)
+ // No gap between list items (a loose list's items set one row: item-gap).
+ set list(spacing: 0pt)
+ set enum(spacing: 0pt)
+ // Footnotes: the separator in the middle of a row of its own (the row
+ // above it is the gap), and each entry is one line. An entry's own rule
+ // gives it a leading of 0.5em; on the grid its lines are as far apart as
+ // the text's (its smaller text has the body's fixed edges, so each of its
+ // lines is g.rows rows too).
+ show footnote.entry: set par(leading: 0pt)
+ set footnote.entry(
+ clearance: 0pt, gap: 0pt,
+ separator: block(height: row, align(horizon, line(length: 30%, stroke: px + C.border))),
+ )
+ // Inline math taller than the line box. The line box is the text's here
+ // (a heading's is not the body's): its fixed edges, or the body's where
+ // the edges are not lengths (raised and lowered text). Math ink at most
+ // 0.15 row over an edge goes out of the line box, which keeps its height
+ // (the ink then comes near the next line, not into its text); more ink
+ // over an edge gives its line whole rows more above or below the text
+ // (the text stays on its row). The math's baseline is always the text's.
+ show math.equation.where(block: false): it => context {
+ let (asc, desc) = if type(text.top-edge) == length and type(text.bottom-edge) == length {
+ (text.top-edge.to-absolute(), -text.bottom-edge.to-absolute())
+ } else { (asc, desc) }
+ let big = 1000pt
+ let a = measure([#text(top-edge: "baseline", bottom-edge: -big, sym.zwj)#box(it)]).height - big
+ let d = measure([#text(top-edge: big, bottom-edge: "baseline", sym.zwj)#box(it)]).height - big
+ if a <= asc and d <= desc { return it }
+ // The line box above and below the baseline: the text's, or whole rows
+ // more for an edge with more than the slack over it.
+ let slack = 0.15 * row
+ let up = if a <= asc + slack { asc } else { asc + calc.ceil((a - asc - slack) / row) * row }
+ let down = if d <= desc + slack { desc } else { desc + calc.ceil((d - desc - slack) / row) * row }
+ // The math with its baseline on the box's (the box's top is `up` over
+ // the baseline, the math's top `a`), so its ink may go out of the box.
+ box(width: measure(box(it)).width, height: up + down, baseline: down, place(top + left, dy: up - a, box(it)))
+ }
+ // Display math: centred in whole rows.
+ show math.equation.where(block: true): it => context {
+ block(width: 100%, height: rows-up(measure(it).height), above: row, below: row, align(horizon, it))
+ }
+ body
+}
+
// ---------- render ----------
// The content of segment `i`; `scope` over the template's own functions.
#let render-md(md, i, math: md-math, scope: (:)) = cmarker.render(
@@ -818,10 +990,15 @@
}).sum(default: 0)
} else { 0 }
+// The grid's rules are over the pages (not only their bodies), so the
+// footnote entries, which a page lays out, have them too.
+#show: body => if on-grid { grid-rules(body) } else { body }
+
#for (i, seg) in segments.enumerate() {
if only > 0 and i + 1 != only { continue }
let md = if type(seg) == str { seg } else { str(seg) }
- let top = if i == 0 { first-top } else { margin-y }
+ // On the grid, every page starts on a row: no top margin.
+ let top = if on-grid { 0pt } else if i == 0 { first-top } else { margin-y }
let body = render-md(md, i)
if notes-before > 0 { body = { counter(footnote).update(notes-before); body } }
// Pad the bottom so the page is a whole number of terminal rows.
diff --git a/render/themes/README.md b/render/themes/README.md
index 9d69aaa..67951d0 100644
--- a/render/themes/README.md
+++ b/render/themes/README.md
@@ -61,6 +61,11 @@ Example: pink inline code, rounder boxes.
| `table.pad-x-px`, `pad-y-px`, `border-px`, `header-weight` | `10`, `5`, `1`, `700` | |
| `rule.border-px`, `gap-em` | `1`, `1.5` | Horizontal rule |
+With `/iui grid on`, the lines of text lie on the terminal's rows. Then some keys change their effect:
+
+- `text.leading-em`, `text.paragraph-em`, `heading.leading-em`, `heading.rule-pad-em`, `list.item-spacing-em` and `code-block.line-height` are not used. Each line is one row (a large heading is two or more rows). The gap between paragraphs and blocks is one row. The items of a tight list have no gap. The items of a loose list (a list with a blank line between its items or in an item) have a gap of one row.
+- `heading.above-em` and `below-em`, `rule.gap-em`, `code-block.pad-px`, `quote.pad-y-em` and `table.pad-y-px` are rounded to the nearest whole number of rows. Gaps above and below headings and rules are one row or more.
+
## Licence
The `vscode` and `vscode-modern` values come from VS Code (MIT, Copyright (c) 2015 - present Microsoft Corporation). Each of those folders has the `LICENSE` file. Their `source` keys name the files the values come from.
diff --git a/tests/command.test.ts b/tests/command.test.ts
index cfaf16c..72247c5 100644
--- a/tests/command.test.ts
+++ b/tests/command.test.ts
@@ -15,6 +15,7 @@ test('the first word completes as a subcommand', () => {
expect(at('/iui t').map(r => r.text)).toEqual(['theme'])
expect(at('/iui w').map(r => r.text)).toEqual(['width'])
expect(at('/iui h').map(r => r.text)).toEqual(['height'])
+ expect(at('/iui g').map(r => r.text)).toEqual(['grid', 'grab'])
expect(at('/iui o').map(r => r.text)).toEqual(['on', 'off'])
expect(at('/iui S').map(r => r.text)).toEqual(['size', 'setup'])
expect(at('/iui x')).toEqual([])
@@ -38,6 +39,10 @@ test('right after theme or size, rows hold the word and its argument', () => {
// half is the default; with no height given, it is current.
expect(heights[0]!.description).toBe('current')
expect(heights[1]!.description).toBe('the terminal height less 16 rows')
+ const grids = at('/iui grid')
+ expect(grids.map(r => r.text)).toEqual(['grid on', 'grid off'])
+ // off is the default; with no grid given, it is current.
+ expect(grids.map(r => r.description)).toEqual([undefined, 'current'])
})
test('a theme name or size completes after its word', () => {
@@ -56,6 +61,11 @@ test('a theme name or size completes after its word', () => {
const tall = (text: string) => commandSuggestions(text, /\S+$/.exec(text)![0], text.lastIndexOf(' ') + 1, { ...o, height: 24 })
expect(tall('/iui height 2')[0]!.description).toBe('current')
expect(tall('/iui height h')[0]!.description).toBe('the default: half the terminal')
+ expect(at('/iui grid o').map(r => r.text)).toEqual(['on', 'off'])
+ expect(at('/iui grid of').map(r => r.label)).toEqual(['off'])
+ const gridded = (text: string) => commandSuggestions(text, /\S+$/.exec(text)![0], text.lastIndexOf(' ') + 1, { ...o, grid: true })
+ expect(gridded('/iui grid o').map(r => r.description)).toEqual(['current', 'the default'])
+ expect(at('/iui grid on extra')).toEqual([])
})
test('other prompts and the command name itself get no rows', () => {
diff --git a/tests/copy.test.ts b/tests/copy.test.ts
index 1b57746..0a1a9c9 100644
--- a/tests/copy.test.ts
+++ b/tests/copy.test.ts
@@ -327,7 +327,7 @@ test('/iui grab and dump are commands with typeahead rows; dump with nothing see
expect(parseCommand('grab')).toEqual({ kind: 'grab' })
expect(parseCommand('dump')).toEqual({ kind: 'dump' })
expect(parseCommand('grab now')).toEqual({ kind: 'bad' })
- const rows = commandSuggestions('/iui g', 'g', 5, { themes: [], active: 'claude-code', size: 100 })
+ const rows = commandSuggestions('/iui gra', 'gra', 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)
diff --git a/tests/draw.test.ts b/tests/draw.test.ts
index 838cc0d..2dfef30 100644
--- a/tests/draw.test.ts
+++ b/tests/draw.test.ts
@@ -1,7 +1,7 @@
import { expect, mock, test } from 'claude-code/testing'
import {
- scaledBulletRow, base64Bytes, canDrawIn, COMMIT_MIN_MS, DEFAULT_CELL, fileHref, fitsInline, INLINE_MAX_BYTES, INLINE_MAX_SIDE, inlineBudget, renderKey,
+ alignFirstLine, scaledBulletRow, base64Bytes, canDrawIn, COMMIT_MIN_MS, DEFAULT_CELL, fileHref, fitsInline, INLINE_MAX_BYTES, INLINE_MAX_SIDE, inlineBudget, renderKey,
RESIZE_QUIET_MS, resolveLinks, SEGMENT_ROWS, WATCH_PL,
} from '../hooks/register'
@@ -311,6 +311,86 @@ test('width with no value shows it; a bad value is refused; a bad kept value is
expect(kept.width).toBe(400)
})
+// ---- The grid setting ---------------------------------------------------------
+
+const boxes = (tree: any): any[] =>
+ tree && typeof tree === 'object' ? [...(tree.type === 'Box' ? [tree] : []), ...(tree.children ?? []).flatMap(boxes)] : []
+// The reply bullet's row: the gutter Box's top margin.
+const bulletRowOf = (tree: any) => boxes(tree).find(b => b.props.width === 2)?.props.marginTop
+
+test('grid on is kept and begins an epoch: another key, compiled with grid=1 and top=0; grid off goes back to the key of before', async ($, on) => {
+ const { clock, kept, compiles, logs } = world(on, { TERM: 'xterm-kitty', IUI_DEBUG: '1' })
+ const ran = await $.command.run({ command: 'iui', args: '' } as any)
+ expect(ran.text).toContain('grid off.')
+ const ui = await $.ui.mount(message('g-1', 'Some **bold** text.'))
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ const [first] = images(await ui.drawn())
+ expect(compiles.length).toBe(1)
+ expect(compiles[0]!.grid).toBe(undefined)
+ const begun = () => logs.filter(l => / epoch \d+ begin/.test(l)).length
+ const before = begun()
+ const set = await $.command.run({ command: 'iui', args: 'grid on' } as any)
+ expect(set.text).toContain('The row grid is now on (each line of text on whole terminal rows)')
+ expect(kept.grid).toBe(true)
+ expect(begun()).toBe(before + 1)
+ await clock.settle()
+ await clock.advance(COMMIT_MIN_MS)
+ await ui.redraw(props('Some **bold** text.'))
+ const [now] = images(await ui.drawn())
+ expect(compiles.length).toBe(2)
+ expect(compiles[1]!.grid).toBe('1')
+ expect(compiles[1]!.top).toBe('0')
+ expect(now.props.source.file).not.toBe(first.props.source.file)
+ const status = await $.command.run({ command: 'iui', args: '' } as any)
+ expect(status.text).toContain('grid on.')
+ const details = await $.command.run({ command: 'iui', args: 'details' } as any)
+ expect(details.text).toContain('row grid on')
+ // Off: the key of before, in memory, so nothing compiles.
+ await $.command.run({ command: 'iui', args: 'grid off' } as any)
+ expect(kept.grid).toBe(false)
+ expect(begun()).toBe(before + 2)
+ await clock.settle()
+ await clock.advance(COMMIT_MIN_MS)
+ await ui.redraw(props('Some **bold** text.'))
+ expect(compiles.length).toBe(2)
+ expect(images(await ui.drawn())[0].props.source.file).toBe(first.props.source.file)
+})
+
+test('a kept grid on draws a heading on the grid, its bullet on row 0; grid with no value shows it', async ($, on) => {
+ const { clock, compiles } = world(on, { TERM: 'xterm-kitty' }, HEAD, { grid: true })
+ const shown = await $.command.run({ command: 'iui', args: 'grid' } as any)
+ expect(shown.text).toContain('The row grid is on (each line of text on whole terminal rows)')
+ const ui = await $.ui.mount(message('g-2', '# Title'))
+ await clock.settle()
+ await ui.redraw(props('# Title'))
+ expect(compiles[0]).toMatchObject({ grid: '1', top: '0' })
+ expect(bulletRowOf(await ui.drawn())).toBe(0)
+})
+
+test('a heading with the grid off keeps its bullet row and top margin', async ($, on) => {
+ const { clock, compiles } = world(on, { TERM: 'xterm-kitty' })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const ui = await $.ui.mount(message('g-3', '# Title'))
+ await clock.settle()
+ await ui.redraw(props('# Title'))
+ expect(compiles[0]!.grid).toBe(undefined)
+ expect(Number(compiles[0]!.top)).not.toBe(0)
+ // An h1 is taller than a row: its bullet is on row 1.
+ const { bulletRow } = alignFirstLine('h1', Number(compiles[0]!.row))
+ expect(bulletRow).toBe(1)
+ expect(bulletRowOf(await ui.drawn())).toBe(bulletRow)
+})
+
+test('a bad kept grid is off; a bad value is refused and not kept', async ($, on) => {
+ const { kept } = world(on, { TERM: 'xterm-kitty' }, HEAD, { grid: 'yes' })
+ const shown = await $.command.run({ command: 'iui', args: 'grid' } as any)
+ expect(shown.text).toContain('The row grid is off (the default)')
+ const bad = await $.command.run({ command: 'iui', args: 'grid maybe' } as any)
+ expect(bad.text).toContain('Not understood: "grid maybe"')
+ expect(kept.grid).toBe(undefined)
+})
+
// ---- The box of a page ---------------------------------------------------------
test('while a new size compiles, the old picture draws at its own box, never stretched', async ($, on) => {
diff --git a/tests/pure.test.ts b/tests/pure.test.ts
index 94e9f77..26ff0ba 100644
--- a/tests/pure.test.ts
+++ b/tests/pure.test.ts
@@ -8,11 +8,12 @@ import {
GHOSTTY_DEFAULT_BG, ghosttyBackgroundOf, ghosttyThemePaths, ghosttyThemesOf, ghosttyValueOf, hexColorOf,
modeLine, modeOfColorFgBg, modeOfGnome, modeOfMacAppearance, resolveMode, settingOf,
BASE_THEME, DEFAULT_THEME, chooseTheme, isSyntaxPath, isThemeName, measureCall, pickThemes, renderKey, themeEntry, themeFiles, themeListing,
- needsRoom, nextJob, pageRowsOf, resultOf, roomInputs, rowsOfBlock, splitInTwo,
+ needsRoom, nextJob, pageRowsOf, resultOf, roomInputs, rowsOfBlock, splitInTwo, typstInputs,
composeFrame, fitBox, pictureColumns, roomColumns, scaledBulletRow,
} from '../hooks/register'
import { DRAWING_ROWS } from '../hooks/lib/settings'
import { wrapPid } from '../hooks/lib/typst'
+import type { Env, Job } from '../hooks/lib/state'
const para = (i: number) => `Paragraph ${i} ${'word '.repeat(40)}`.trim()
const fence = (info: string, lines: number) => ['```' + info, ...Array.from({ length: lines }, (_, i) => `line ${i}`), '```'].join('\n')
@@ -209,6 +210,14 @@ test('the size command takes 80 to 200 percent', () => {
expect(parseCommand('probe 3')).toEqual({ kind: 'bad' })
})
+test('the grid command: on, off, or nothing to show it', () => {
+ expect(parseCommand('grid')).toEqual({ kind: 'grid' })
+ expect(parseCommand('grid on')).toEqual({ kind: 'grid', grid: true })
+ expect(parseCommand('GRID Off')).toEqual({ kind: 'grid', grid: false })
+ expect(parseCommand('grid yes')).toEqual({ kind: 'bad' })
+ expect(parseCommand('grid on off')).toEqual({ kind: 'bad' })
+})
+
test('the first line of an answer is told by how it starts', () => {
expect(firstLineOf('\n\nSome text')).toBe('para')
expect(firstLineOf('# Title')).toBe('h1')
@@ -241,6 +250,15 @@ test('the first line of text is centred on the bullet row', () => {
}
})
+test('with the row grid, the first line box is row 0: no top margin, the bullet on row 0', () => {
+ for (const kind of ['para', 'h1', 'h2', 'h3', 'h4', 'quote', 'code', 'table'] as const) {
+ for (const rowPt of [9, 11, 13.2, 16]) {
+ expect(alignFirstLine(kind, rowPt, true)).toEqual({ topPt: 0, bulletRow: 0 })
+ expect(alignFirstLine(kind, rowPt, false)).toEqual(alignFirstLine(kind, rowPt))
+ }
+ }
+})
+
test('pages are padded to whole rows, so rows round; a page keeps the box it was compiled for', () => {
const px = { width: 16, height: 32 }
expect(pageRowsOf(320, px)).toBe(10)
@@ -285,6 +303,30 @@ test('the room height is in the key only when it is given (a text that needs it)
expect(renderKey({ ...o, room: { ...room, design: { widthPt: 500, heightPt: 300 } } })).not.toBe(roomed)
})
+test('the grid is in the key only when it is on, so the keys with it off stay', () => {
+ const o = {
+ textHash: 'h', columns: 100, cell: DEFAULT_CELL, size: 100, mode: 'dark' as const, termFont: '', columnPt: 6,
+ templateStamp: '1', look: { name: 'vscode', dir: '/t', stamp: '0' },
+ }
+ const plain = renderKey(o)
+ expect(renderKey({ ...o, grid: false })).toBe(plain)
+ expect(renderKey({ ...o, grid: true })).not.toBe(plain)
+})
+
+test('with the grid on, the template gets grid=1 and top=0; with it off, no grid input', () => {
+ const env = { metrics: DEFAULT_METRICS, termFont: '' } as Env
+ const job = { key: 'k', requestId: 'r', text: '# Title', columns: 100, cell: DEFAULT_CELL, theme: 'dark', size: 100, grid: false, themeDir: '/t', env, epoch: 0 } as Job
+ const off = typstInputs(job, ['# Title'], '/c/k', false)
+ expect('grid' in off.inputs).toBe(false)
+ expect(off.inputs.top).toBe(alignFirstLine('h1', sizing(100, DEFAULT_CELL, fontFit(DEFAULT_METRICS).columnPt).rowPt).topPt)
+ const on = typstInputs({ ...job, grid: true }, ['# Title'], '/c/k', false)
+ expect(on.inputs.grid).toBe(1)
+ expect(on.inputs.top).toBe(0)
+ // Only grid and top change; the ppi is the same.
+ expect({ ...on.inputs, grid: undefined, top: off.inputs.top }).toEqual({ ...off.inputs, grid: undefined })
+ expect(on.ppi).toBe(off.ppi)
+})
+
test('the room goes to the template in pt: the design page width and room height', () => {
expect(roomInputs(undefined)).toEqual({})
// A first render: the design is the space now, so the factor is 1 (design-w = width).