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: each line's centre on the middle of a row
razorback16267e0a604a05
diff --git a/docs/limitations.md b/docs/limitations.mdindex eecd5d2..041359b 100644--- a/docs/limitations.md+++ b/docs/limitations.md@@ -14,7 +14,9 @@- **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.+ - At 100% text size, a level-1, level-2 or level-3 heading uses 3 rows. A level-2 or level-3 heading has 2 rows for the text and half a row above and below it. 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%. Then each block of such lines (a paragraph, a list, a table row, a quote or a footnote) is 1 row taller, because the mod moves its lines down by half a row. These values change with the terminal font and the cell size.+ - In a list or a quote with lines of 2 rows, the rules of a table, display math, an image, a Typst drawing and a horizontal rule are half a row down. The text stays in the middle of the rows.+ - If inline math makes the first line of an answer taller, the reply bullet can be one row above the text.- **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.diff --git a/docs/usage.md b/docs/usage.mdindex 961ae00..4ff6dee 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -87,8 +87,10 @@ The terminal draws a mouse selection as full cells, thus a selection covers full`/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 line of body text, a list, a quote or a table uses one row (or more rows if the text is large). The middle of the text is in the middle of a row.- Each heading, each code line and each gap between blocks uses full rows.+- The middle of a line that uses 2 rows (or 4 rows) is on the border between two rows. Thus the mod moves such a line down by half a row, and adds half a row above and below the block that holds it. For example, a level-2 heading uses 3 rows, and its text is in the middle row. Thus a selection of one row covers the full height of the text.+- The reply bullet is on the row that holds the middle of the first line. For example, the bullet is on the second row of a level-1 heading.- 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).diff --git a/hooks/lib/draw.tsx b/hooks/lib/draw.tsxindex 8eac341..e3c13a2 100644--- a/hooks/lib/draw.tsx+++ b/hooks/lib/draw.tsx@@ -5,8 +5,9 @@import type { EngineInterface, RenderComponent, RenderSurface, RenderViewport, ResolveInput } from 'claude-code'import type { IuiTheme } from '../../types'-import { BODY_PT, bulletOf, GUTTER, LINK_FILES_KEPT, MARGIN_TOP, TEMPLATE_VERSION } from './settings'+import { BODY_PT, bulletOf, GRID_VERSION, GUTTER, LINK_FILES_KEPT, MARGIN_TOP, TEMPLATE_VERSION } from './settings'import { INLINE_KEPT, inlined, keep, linkFiles, S, type Cell, type Look, type Metrics, type Result, type Room } from './state'+import { gridFirstRow, type GridMetrics } from './grid'import { FENCE, imagePathOf } from './markdown'import { linksOf, type LinkItem } from './links'import { fitBox, fitsInline, roomColumns } from './terminal'@@ -73,8 +74,8 @@ 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.+ // `/iui grid` on: the lines on the row grid, another picture (with+ // GRID_VERSION). Off adds nothing, so the keys of before stay.grid?: boolean}): string {const { room } = o@@ -83,7 +84,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'] : []),+ ...(o.grid ? ['grid', GRID_VERSION] : []),])}@@ -102,9 +103,10 @@ const FIRST_LINE: Record<FirstLine, { centre: number; inkTop: number }> = {table: { centre: 11.27, inkTop: 6.18 },}+const HEADING = /^ {0,3}(#{1,6})\s/export function firstLineOf(md: string): FirstLine {const line = md.split('\n').find(l => l.trim()) ?? ''- const heading = /^ {0,3}(#{1,6})\s/.exec(line)+ const heading = HEADING.exec(line)if (heading) return (['h1', 'h2', 'h3'] as const)[heading[1]!.length - 1] ?? 'h4'if (/^ {0,3}>/.test(line)) return 'quote'if (FENCE.test(line)) return 'code'@@ -116,15 +118,22 @@ 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.-// 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 }+export function alignFirstLine(kind: FirstLine, rowPt: number): { topPt: number; bulletRow: number } {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 }}+// The first page's top margin and bullet row. With the row grid (the+// fonts' grid numbers and the job's code size): no margin, and the row of+// the first line's ink centre (gridFirstRow).+export function placeFirstLine(md: string, rowPt: number, grid?: { metrics: GridMetrics; code: number }): { topPt: number; bulletRow: number } {+ const kind = firstLineOf(md)+ if (!grid) return alignFirstLine(kind, rowPt)+ const level = HEADING.exec(md.split('\n').find(l => l.trim()) ?? '')?.[1]!.length ?? 0+ return { topPt: 0, bulletRow: gridFirstRow(kind, level, rowPt, grid.metrics, grid.code) }+}+// Over ssh: every page's PNG as base64 for a `{ png }` source, or null when// a page cannot go (over INLINE_MAX_SIDE or INLINE_MAX_BYTES, or not read),// so the message shows as text.diff --git a/hooks/lib/grid.ts b/hooks/lib/grid.tsnew file mode 100644index 0000000..fd36a39--- /dev/null+++ b/hooks/lib/grid.ts@@ -0,0 +1,67 @@+// The row grid (`/iui grid on`): the row of a page's first line, from the+// numbers the template lays it out with, for the reply bullet.+import type { FirstLine } from './draw'+import { BODY_PT } from './settings'++// render/measure.typ `grid` (pt): the height a line box of the body and of+// h1 to h6 needs, the same per pt of the code size, the code size in body+// text (null: the `code` input) and the padding over a first line.+export type GridMetrics = {+ body: number+ heading: number[]+ code: number+ codeSize: number | null+ pad: { quote: number; code: number; table: number }+}+// Measured with Typst on macOS: SF Pro Text and Menlo, the vscode values.+export const DEFAULT_GRID: GridMetrics = {+ body: 11.2836,+ heading: [31.8046, 20.4458, 14.1985, 11.3588, 9.9389, 9.655],+ code: 1.0775,+ codeSize: 1,+ pad: { quote: 6.05, code: 12.5714, table: 3.9286 },+}++// measure.typ's `grid` as GridMetrics; null when it is not one.+export function gridOf(v: unknown): GridMetrics | null {+ const g = v as Record<string, unknown> | null+ const pad = g?.pad as Record<string, unknown> | undefined+ const pt = (x: unknown) => typeof x === 'number' && Number.isFinite(x) && x >= 0+ const size = g?.['code-size']+ if (+ !g || !pt(g.body) || !pt(g.code) || !Array.isArray(g.heading) || g.heading.length !== 6 || !g.heading.every(pt)+ || !(size === null || (pt(size) && (size as number) > 0)) || !pad || !pt(pad.quote) || !pt(pad.code) || !pt(pad.table)+ ) return null+ return {+ body: g.body as number, heading: g.heading as number[], code: g.code as number, codeSize: size as number | null,+ pad: { quote: pad.quote as number, code: pad.code as number, table: pad.table as number },+ }+}++// The template's rounding: grid-edges and rows-near in render/md.typ.+export const gridRowsOf = (needPt: number, rowPt: number) => Math.max(1, Math.ceil(needPt / rowPt - 0.001))+const rowsNear = (pt: number, rowPt: number) => Math.round(pt / rowPt)++// The row of the ink centre of a page's first line: its padding in whole+// rows, then row floor(n / 2) of its line box of n rows (an even box is half+// a row down, so its centre is in row n / 2). `level`: a heading's (1 to 6);+// `code`: the job's code input. A list is a `para`: body lines.+export function gridFirstRow(kind: FirstLine, level: number, rowPt: number, g: GridMetrics, code: number): number {+ const middle = (needPt: number) => Math.floor(gridRowsOf(needPt, rowPt) / 2)+ const body = middle(g.body)+ switch (kind) {+ case 'h1':+ case 'h2':+ case 'h3':+ case 'h4':+ return middle(g.heading[Math.min(6, Math.max(1, level)) - 1] ?? g.body)+ case 'quote':+ return rowsNear(g.pad.quote, rowPt) + body+ case 'code':+ return rowsNear(g.pad.code, rowPt) + middle(g.code * BODY_PT * (g.codeSize ?? code))+ case 'table':+ return rowsNear(g.pad.table, rowPt) + body+ default:+ return body+ }+}diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.tsindex ed8dd63..c3b0192 100644--- a/hooks/lib/settings.ts+++ b/hooks/lib/settings.ts@@ -55,6 +55,9 @@ export const DEFAULT_CELL: Cell = { width: 16, height: 32 }// first compile of the text). Its live Typst blocks scale by// min(content width / design-w, height / design-h).export const TEMPLATE_VERSION = '8'+// Part of the key of a picture with the row grid only: bump it when such a+// picture or its bullet row changes, so the keys with the grid off stay.+export const GRID_VERSION = '2'export const COMPILE_TIMEOUT_MS = 20000export const ALT_CHARS = 200// Where Typst is when the login shell's PATH does not find it. `~` is $HOME.diff --git a/hooks/lib/state.ts b/hooks/lib/state.tsindex 73e677d..ee4d091 100644--- a/hooks/lib/state.ts+++ b/hooks/lib/state.ts@@ -8,6 +8,7 @@ import type { ThemeInfo } from './themes'import type { HostMode, ThemeSetting } from './mode'import type { PlanVerdict } from './plan'import type { Drawn } from './copy'+import type { GridMetrics } from './grid'import { DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_WIDTH, type Height, type Width } from './settings'import { uiInvalidate } from './api'@@ -32,8 +33,9 @@ export type Room = { heightPt: number; design: Design; designKey: string; isNew:// `avg` the mean advance over a lowercase pangram.export type FontMetrics = { adv: number; xh: number; avg: number }// `term` the terminal's font (null when unknown or not installed), `menlo`-// the template's code font, `body` its text font.-export type Metrics = { term: FontMetrics | null; menlo: FontMetrics; body: FontMetrics }+// the template's code font, `body` its text font, `grid` the row grid's+// numbers (DEFAULT_GRID when not given).+export type Metrics = { term: FontMetrics | null; menlo: FontMetrics; body: FontMetrics; grid?: GridMetrics }// Measured with Typst on macOS: Menlo and SF Pro Text.export const DEFAULT_METRICS: Metrics = {term: null,diff --git a/hooks/lib/typst.ts b/hooks/lib/typst.tsindex 095bd89..7c5861d 100644--- a/hooks/lib/typst.ts+++ b/hooks/lib/typst.ts@@ -6,7 +6,8 @@ import { COMPILE_TIMEOUT_MS, MAX_IMAGE_ROWS, NO_NETWORK, SEGMENT_ROWS, TOUCH_FLUimport { DEFAULT_METRICS, type Cell, type FontMetrics, type Job, type Metrics, type Page, type Result } from './state'import { firstLine, imagePathOf, localImages, plainOf, splitInTwo, splitSegments } from './markdown'import { inlineBudget } from './terminal'-import { alignFirstLine, firstLineOf, fontFit, sizing } from './draw'+import { fontFit, placeFirstLine, sizing } from './draw'+import { DEFAULT_GRID, gridOf } from './grid'import { HEADERS_SH } from './host'import { logDebug } from './log'import { positionsOf, type Mark, type Positions } from './copy'@@ -130,7 +131,7 @@ export async function measureFonts($: EngineInterface, typst: string, root: stritry {const m = JSON.parse(got?.stdout ?? '') as Metricsconst ok = (x: FontMetrics | null | undefined) => !!x && x.adv > 0 && x.xh > 0 && x.avg > 0- if (ok(m.menlo) && ok(m.body)) return { term: ok(m.term) ? m.term : null, menlo: m.menlo, body: m.body }+ if (ok(m.menlo) && ok(m.body)) return { term: ok(m.term) ? m.term : null, menlo: m.menlo, body: m.body, grid: gridOf(m.grid) ?? DEFAULT_GRID }} catch {}return DEFAULT_METRICS}@@ -277,12 +278,20 @@ export async function runKillable(return { exitCode: code, stdout, stderr }}+// The first page's top margin and bullet row of a job's text.+export function firstLinePlace(job: Job, segments: readonly string[]) {+ const fit = fontFit(job.env.metrics, job.size)+ const { rowPt } = sizing(job.columns, job.cell, fit.columnPt)+ const grid = job.grid ? { metrics: job.env.metrics.grid ?? DEFAULT_GRID, code: fit.code } : undefined+ return placeFirstLine(segments[0] ?? '', rowPt, grid)+}+// The template's inputs for a job and its ppi (the PNG compile and the// 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, job.grid)+ const { topPt } = firstLinePlace(job, segments)const inputs: Record<string, string | number> = {theme: job.theme,width: widthPt,@@ -439,7 +448,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, job.grid)+ const { bulletRow } = firstLinePlace(job, segments)const result: Result = { pages, bulletRow, ...(note ? { note } : {}) }await fsWrite($, `${dir}/pages.json`, JSON.stringify(result))return resultdiff --git a/render/fonts.typ b/render/fonts.typindex afe0f99..ba8047b 100644--- a/render/fonts.typ+++ b/render/fonts.typ@@ -3,3 +3,12 @@#import "theme.typ": fonts#let sans = fonts.body#let mono-base = fonts.code+// The row grid (md.typ, grid=1): the ink of a line of the current text+// (needs context), "bdfhkl" `up` from the baseline and "gjpqy" `down`, and+// the height its line box `need`s (the ink and 0.1em; md.typ rounds it up+// to whole rows).+#let line-ink() = {+ let up = measure(text(top-edge: "bounds", bottom-edge: "baseline", "bdfhkl")).height+ let down = measure(text(top-edge: "baseline", bottom-edge: "bounds", "gjpqy")).height+ (up: up, down: down, need: up + down + 0.1em.to-absolute())+}diff --git a/render/md.typ b/render/md.typindex 27d7563..b217bcc 100644--- a/render/md.typ+++ b/render/md.typ@@ -42,8 +42,10 @@// 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.+// whole number of rows. A line box of an even number of rows is half a row+// down (phase-pad), so the centre of every line is on the middle of a row.+// 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@@ -100,7 +102,7 @@#import "theme.typ": T, C, syntax, at-level#let px = 11pt / 14// The font lists live in fonts.typ, which render/measure.typ reads too.-#import "fonts.typ": sans, mono-base+#import "fonts.typ": sans, mono-base, line-ink// The terminal's own font first for code, so code looks like the terminal// (unless the theme sets fonts.use-terminal-font to false).#let term-font = inp.at("term-font", default: "")@@ -174,14 +176,35 @@// 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.+// 0, the lines of a paragraph are then exactly `rows` rows apart. The hooks+// module finds the same `rows` from measure.typ (the bullet's row).#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 (up, down, need) = line-ink()+ let n = calc.max(1, calc.ceil(need / row - 0.001))let mid = (up - down) / 2(top: mid + n * row / 2, bottom: mid - n * row / 2, rows: n)}+// The half-row phase: the centre of a line box of an even number of rows+// is on a row boundary. Such lines go half a row down: their block gets+// half a row more above and below (still whole rows). The block marks its+// content with a text cost (no effect here, like the probe's flags), so a+// block in it with lines of the same parity does not move again, and one+// with the other parity moves back.+#let half-cost = 103%+#let is-half(costs) = costs.widow == half-cost+#let half-costs(half) = (widow: if half { half-cost } else { 100% })+// The rows of the line box here, from the grid's fixed edges (needs context).+#let line-rows() = if type(text.top-edge) == length and type(text.bottom-edge) == length {+ calc.max(1, int(calc.round((text.top-edge - text.bottom-edge).to-absolute() / row)))+} else { 1 }+// Half a row when lines of parity `half` are in a flow of the other phase.+#let phase-pad(half) = if half != is-half(text.costs) { row / 2 } else { 0pt }+// `body`, lines of the text here, in their phase.+#let in-phase(body) = context {+ let half = calc.even(line-rows())+ let pad = phase-pad(half)+ if pad == 0pt { body } else { block(inset: (y: pad), { set text(costs: half-costs(half)); body }) }+}// ---------- headings ----------#set heading(numbering: none)@@ -192,21 +215,24 @@let above = at-level(H.above-em, lvl - 1) * 11ptlet below = at-level(H.below-em, lvl - 1) * 11ptif 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).+ // The grid: a line box of whole rows (3 for h1 and 2 for h2 and h3 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). An even number of rows is half a row down+ // (phase-pad): an h2 is then 3 rows, its text in the middle one.return {set text(size: size, weight: H.weight)context {let g = grid-edges()- set text(top-edge: g.top, bottom-edge: g.bottom)+ let half = calc.even(g.rows)+ let pad = phase-pad(half)+ set text(top-edge: g.top, bottom-edge: g.bottom, costs: half-costs(half))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) },+ inset: (y: pad), stroke: if lvl <= H.rule-levels { (bottom: px + C.border) },it.body,)}@@ -296,14 +322,17 @@let CB = E.code-blockif 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).+ // font at its size), padding of whole rows (16px is about one row), and+ // half a row more when its lines are not in the flow's phase (phase-pad).let g = grid-edges()+ let half = calc.even(g.rows)+ let pad = phase-pad(half)return {- set text(top-edge: g.top, bottom-edge: g.bottom)+ set text(top-edge: g.top, bottom-edge: g.bottom, costs: half-costs(half))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,+ radius: CB.radius-px * px, inset: (x: CB.pad-px * px, y: rows-near(CB.pad-px * px) + pad), above: row, below: row,text(fill: fg, it),)}@@ -327,14 +356,24 @@// 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 }+ // 1.8em below). Its lines in their phase (phase-pad).+ if on-grid {+ return context {+ let half = calc.even(line-rows())+ block(+ width: 100%, fill: C.quote-bg, radius: Q.radius-px * px, above: row, below: row,+ 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: rows-near(Q.pad-y-em * 11pt) + phase-pad(half)),+ { set block(spacing: row); set text(costs: half-costs(half)); it.body },+ )+ }+ }block(width: 100%, fill: C.quote-bg, radius: Q.radius-px * px,- above: gap, below: gap,+ above: E.text.paragraph-em * 1em, below: E.text.paragraph-em * 1em,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: 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 },+ inset: (left: (Q.pad-left-px + Q.bar-px) * px, right: Q.pad-right-px * px, y: Q.pad-y-em * 1em),+ it.body,)}@@ -692,7 +731,7 @@#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 list-of(..args) = {let items = args.pos()let gap = item-gap(items)let tasks = items.map(task-split)@@ -722,7 +761,7 @@}// "1. [x] done": keep the number, put the checkbox after it.-#let md-enum(..args) = {+#let enum-of(..args) = {let start = args.named().at("start", default: 1)let start = if type(start) == int { start } else { 1 }let gap = item-gap(args.pos())@@ -734,6 +773,10 @@enum(..args.named(), ..gap, ..items)}+// On the grid, a list with its nested lists is one block in its phase.+#let md-list(..args) = if on-grid { in-phase(list-of(..args)) } else { list-of(..args) }+#let md-enum(..args) = if on-grid { in-phase(enum-of(..args)) } else { enum-of(..args) }+// ---------- ```typst fences: live Typst ----------#let live-langs = ("typst", "typ")// The width that content `c` needs when it is laid out in the width `w`:@@ -761,8 +804,8 @@// segment must stay one page); a column break is dropped.let drawing = {show colbreak: none- // The probe: no marks (see no-marks).- set text(costs: (orphan: 102%)) if probe+ // The probe: no marks (see no-marks). The grid: no half-row phase.+ set text(costs: (orphan: 102%)) if probe or on-grideval(src, mode: "markup", scope: (theme: live-theme))}std.block(width: 100%, above: if on-grid { row } else { 1.2em }, below: if on-grid { row } else { 1.2em }, layout(size => {@@ -911,6 +954,14 @@// 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)+ // Each paragraph and table cell in its phase (phase-pad; a cell's rules+ // stay on row boundaries), not a live drawing's. A footnote entry always+ // starts on a row (under the separator's row), whatever refers to it.+ show par: it => context if no-marks(text.costs) { it } else { in-phase(it) }+ show table.cell: in-phase+ show footnote.entry: it => context if calc.even(line-rows()) {+ block(inset: (y: row / 2), { set text(costs: half-costs(true)); it })+ } else { it }set footnote.entry(clearance: 0pt, gap: 0pt,separator: block(height: row, align(horizon, line(length: 30%, stroke: px + C.border))),diff --git a/render/measure.typ b/render/measure.typindex bbfb403..cf35565 100644--- a/render/measure.typ+++ b/render/measure.typ@@ -3,7 +3,15 @@// Per 1 em: `adv` the width of "0", `xh` the x-height, `avg` the mean// advance over a lowercase pangram. `term` is none when the family is not// installed (Typst would fall back to another font).-#import "fonts.typ": sans, mono-base+//+// `grid`: what the hooks module finds the row of a page's first line from+// (the bullet's, with grid=1). `body` and `heading` (h1 to h6) the `need` of+// a line in pt (line-ink); `code` the code font's per pt of its size, and+// `code-size` that size in body text (none: the `code` input); `pad` the+// padding in pt over the first line of a quote, a code block and a table+// cell (md.typ rounds it to whole rows).+#import "fonts.typ": sans, mono-base, line-ink+#import "theme.typ": T, at-level#let fam = sys.inputs.at("term-font", default: "")#let probe = "the quick brown fox jumps over the lazy dog"#let m(fonts, body, edge) = measure(text(@@ -14,11 +22,31 @@xh: m(fonts, "x", "x-height").height / 100pt,avg: m(fonts, probe, "cap-height").width / 100pt / probe.len(),)+// The text as md.typ sets it: the body, a heading (in Typst's own heading+// rule, which makes h1 1.4em and h2 1.2em) and code (md.typ's `mono`).+#set text(font: sans, size: 11pt)+#show heading: it => {+ set text(size: at-level(T.heading.size-em, calc.min(it.level, 6) - 1) * 1em, weight: T.heading.weight)+ context [#metadata(line-ink().need / 1pt)<mh>]+}+#for level in range(1, 7) { heading(level: level, []) }+#{+ set text(font: if fam != "" and T.fonts.use-terminal-font { (fam,) + mono-base } else { mono-base }, size: 100pt)+ context [#metadata(line-ink().need / 100pt)<mc>]+}#context {let found = fam != "" and m((fam,), "0", "cap-height").width != m(("Nonexistent Font Zz",), "0", "cap-height").width+ let px = 11 / 14[#metadata((term: if found { metrics((fam,)) } else { none },menlo: metrics(mono-base),body: metrics(sans),+ grid: (+ body: line-ink().need / 1pt,+ heading: query(<mh>).map(h => h.value),+ code: query(<mc>).first().value,+ code-size: if type(T.code-block.size) in (int, float) { float(T.code-block.size) } else { none },+ pad: (quote: T.quote.pad-y-em * 11, code: T.code-block.pad-px * px, table: T.table.pad-y-px * px),+ ),)) <m>]}diff --git a/render/themes/README.md b/render/themes/README.mdindex 67951d0..3fd4140 100644--- a/render/themes/README.md+++ b/render/themes/README.md@@ -63,7 +63,7 @@ Example: pink inline code, rounder boxes.With `/iui grid on`, the lines of text lie on the terminal's rows. Then some keys change their effect:-- `text.leading-em`, `text.paragraph-em`, `heading.leading-em`, `heading.rule-pad-em`, `list.item-spacing-em` and `code-block.line-height` are not used. Each line is one row (a large heading is two or more rows). 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.+- `text.leading-em`, `text.paragraph-em`, `heading.leading-em`, `heading.rule-pad-em`, `list.item-spacing-em` and `code-block.line-height` are not used. Each line is one row (a large heading is two or more rows; a line of an even number of rows is half a row down, with half a row more above and below its block). The gap between paragraphs and blocks is one row. The items of a tight list have no gap. The items of a loose list (a list with a blank line between its items or in an item) have a gap of one row.- `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.## Licencediff --git a/tests/draw.test.ts b/tests/draw.test.tsindex 2dfef30..aa0b920 100644--- a/tests/draw.test.ts+++ b/tests/draw.test.ts@@ -357,7 +357,7 @@ test('grid on is kept and begins an epoch: another key, compiled with grid=1 andexpect(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) => {+test('a kept grid on draws a heading on the grid, its bullet on the row of its text; 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)')@@ -365,7 +365,23 @@ test('a kept grid on draws a heading on the grid, its bullet on row 0; grid withawait clock.settle()await ui.redraw(props('# Title'))expect(compiles[0]).toMatchObject({ grid: '1', top: '0' })- expect(bulletRowOf(await ui.drawn())).toBe(0)+ // An h1 of 3 rows: its text in row 1.+ expect(bulletRowOf(await ui.drawn())).toBe(1)+})++test('with the grid on, the bullet row comes from the grid numbers that the font measure gives', async ($, on) => {+ // Body text that needs 2 rows (a large size): its line is half a row down, its text in row 1.+ const measured = (body: number) => JSON.stringify({+ term: null, menlo: { adv: 0.602, xh: 0.547, avg: 0.602 }, body: { adv: 0.63, xh: 0.526, avg: 0.483 },+ grid: { body, heading: [31.8, 20.4, 14.2, 11.4, 9.9, 9.7], code: 1.0775, 'code-size': 1, pad: { quote: 6.05, code: 12.57, table: 3.93 } },+ })+ const { clock, compiles } = world(on, { TERM: 'xterm-kitty' }, HEAD, { grid: true }, undefined, { metrics: () => measured(20) })+ await $.command.run({ command: 'iui', args: '' } as any)+ const ui = await $.ui.mount(message('g-4', 'Some text.'))+ await clock.settle()+ await ui.redraw(props('Some text.'))+ expect(compiles[0]).toMatchObject({ grid: '1', top: '0' })+ expect(bulletRowOf(await ui.drawn())).toBe(1)})test('a heading with the grid off keeps its bullet row and top margin', async ($, on) => {diff --git a/tests/pure.test.ts b/tests/pure.test.tsindex 26ff0ba..053ceed 100644--- a/tests/pure.test.ts+++ b/tests/pure.test.ts@@ -14,6 +14,8 @@ import {import { DRAWING_ROWS } from '../hooks/lib/settings'import { wrapPid } from '../hooks/lib/typst'import type { Env, Job } from '../hooks/lib/state'+import { placeFirstLine } from '../hooks/lib/draw'+import { DEFAULT_GRID, gridFirstRow, gridOf, gridRowsOf } from '../hooks/lib/grid'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')@@ -250,13 +252,62 @@ 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('with the row grid, no top margin and the bullet on the row of the first line\'s ink centre', () => {+ const grid = { metrics: DEFAULT_GRID, code: 0.8785 }+ // The rows of a 36 px cell at /iui size 100, 117, 125, 150 and 200%, and+ // the row of the first line in the template's pictures at those sizes.+ const rowsPt = [13.091, 11.1888, 10.4726, 8.7273, 6.5455]+ const drawn: Record<string, number[]> = {+ '# Title': [1, 1, 2, 2, 2],+ '## Part': [1, 1, 1, 1, 2],+ '### Part': [1, 1, 1, 1, 1],+ '#### Part': [0, 1, 1, 1, 1],+ '##### Part': [0, 0, 0, 1, 1],+ '###### Part': [0, 0, 0, 1, 1],+ 'Some text': [0, 1, 1, 1, 1],+ '- item': [0, 1, 1, 1, 1],+ '> quote': [0, 2, 2, 2, 2],+ '```\ncode\n```': [1, 2, 2, 2, 3],+ '| a | b |\n|---|---|': [0, 1, 1, 1, 2],}+ for (const [md, rows] of Object.entries(drawn)) {+ rowsPt.forEach((rowPt, i) => expect([md, placeFirstLine(md, rowPt, grid)]).toEqual([md, { topPt: 0, bulletRow: rows[i] }]))+ }+ // Grid off: the margin and row of before.+ for (const md of Object.keys(drawn)) expect(placeFirstLine(md, 11)).toEqual(alignFirstLine(firstLineOf(md), 11))+})++test('a line box of n rows has its ink centre on row floor(n / 2), under the padding in whole rows', () => {+ const row = 10+ const g = (body: number, pad = 0) => ({ ...DEFAULT_GRID, body, pad: { quote: pad, code: pad, table: pad } })+ // n = 1, 2, 3, 4: an even box is half a row down, so its centre is in row n / 2.+ expect([9, 19, 29, 39].map(need => gridFirstRow('para', 0, row, g(need), 1))).toEqual([0, 1, 1, 2])+ expect(gridRowsOf(20, row)).toBe(2)+ expect(gridRowsOf(20.005, row)).toBe(2)+ expect(gridRowsOf(20.02, row)).toBe(3)+ // Padding rounds to the nearest whole rows.+ expect(gridFirstRow('quote', 0, row, g(19, 14), 1)).toBe(1 + 1)+ expect(gridFirstRow('table', 0, row, g(9, 4), 1)).toBe(0)+ // Code: the code font's need per pt at the theme's size, or at `code` for "terminal".+ const code = { ...DEFAULT_GRID, code: 1.5, pad: { ...DEFAULT_GRID.pad, code: 0 } }+ expect(gridFirstRow('code', 0, row, code, 0.5)).toBe(1)+ expect(gridFirstRow('code', 0, row, { ...code, codeSize: null }, 0.5)).toBe(0)+})++test('the grid numbers of the font measure are read, and a bad one is refused', () => {+ const measured = {+ body: 11.2836, heading: [31.8, 20.4, 14.2, 11.4, 9.9, 9.7], code: 1.0775, 'code-size': null,+ pad: { quote: 6.05, code: 12.57, table: 3.93 },+ }+ expect(gridOf(measured)).toEqual({+ body: 11.2836, heading: [31.8, 20.4, 14.2, 11.4, 9.9, 9.7], code: 1.0775, codeSize: null, pad: { quote: 6.05, code: 12.57, table: 3.93 },+ })+ expect(gridOf({ ...measured, 'code-size': 1 })?.codeSize).toBe(1)+ expect(gridOf(undefined)).toBe(null)+ expect(gridOf({ ...measured, heading: [1, 2] })).toBe(null)+ expect(gridOf({ ...measured, body: '11' })).toBe(null)+ expect(gridOf({ ...measured, pad: { quote: 1 } })).toBe(null)+ expect(gridOf({ ...measured, 'code-size': 'terminal' })).toBe(null)})test('pages are padded to whole rows, so rows round; a page keeps the box it was compiled for', () => {