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
Terminal fonts in pictures; fake bold; plan picture after an Edit
razorback161f727986c878
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 96a6a11..1ed588e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,13 @@ All releases of Intelligent UI for Claude Code (`cc-intelligent-ui`). Claude Cod### Fixed+- **Rio:** the pictures use Rio's own font, Cascadia Code NF. This font is inside the Rio program, so Typst did not have it and drew the theme's fonts. Now the mod copies the font from the program, as it does for Ghostty's JetBrains Mono. A font in Rio's config that is not installed also gives Rio's own font, because Rio draws that font.+- The terminal font is the font that the terminal draws, also when its config names a font that is not installed: Ghostty and cmux on macOS draw their JetBrains Mono, Ghostty and kitty on Linux draw the nearest font of fontconfig, kitty on macOS draws Menlo (also for a font that is not fixed-pitch), iTerm2 draws the user's fixed-pitch font. For a Ghostty `font-family` list, the first font of the list that is installed. kitty on macOS with no `font_family` now gives Menlo for body text too.+- The font folder that the mod gives Typst goes after your own `TYPST_FONT_PATHS`. Before, it replaced it.+- iTerm2: a profile font with font settings after its size (for example, ligatures off) is read. Before, the terminal font was not known.+- cmux: a `font-family` in cmux's own config (`config.ghostty` in its Application Support folder) is read.+- `/iui details` tells you when Typst does not have the terminal font.+- **Bold text in a terminal font with no bold face** (for example, Monaco in iTerm2): the pictures draw a fake bold, as the terminal does. Before, bold text in that font was drawn regular, because Typst does not make a bold face. Text in other fonts does not change.- Picture select: a push of the button on a page that had just gone off the screen no longer waits for ever (no highlight until a reload).- Picture select: two tall pages on the screen no longer make each other ready again and again (the page cache keeps the pages on the screen, and the page of the selection).- Picture select: a drawing drawn again with new page files (a stream, a resize, a theme or size change) no longer keeps its old pages in the queue.diff --git a/docs/development.md b/docs/development.mdindex fcf5bfc..e1084e5 100644--- a/docs/development.md+++ b/docs/development.md@@ -11,6 +11,8 @@ claude --plugin-dir . # once: Claude Code writes the API types to .claunpx -p typescript tsc -p . # type checkclaude plugin test . # testssh tests/cache-sh-test.sh # the cache folder sweep (CACHE_SH) in sh, dash and bash --posix+sh tests/fonts-sh-test.sh # the copy of a font out of a terminal's program (PROGRAM_FONTS_SH and _PL) with perl+sh tests/bold-sh-test.sh # the fake bold of md.typ (term-bold=0) with the real Typst and Monaco (skips with no Monaco)claude plugin validate .```diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 170b0e5..678a86f 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -7,7 +7,7 @@1. A `ui.render` hook on `AssistantMessage` gets each block of the answer as Markdown.2. While Claude writes a block, Claude Code shows its own text: Claude Code gives the hook the text of a block only when the block is complete (versions 2.1.299 to 2.1.303 at least). The block is final when the model request starts its next block (a tool call, more text) or ends. If the mod did not see the request, the block is final after its text stops changing for 400 ms. Then the mod writes the block to a JSON file and runs `typst compile` with `render/md.typ`. For plain text, Typst loads only some fonts (refer to [The lean font set](#the-lean-font-set)). Long answers are cut at block boundaries into pages. One page is one PNG.3. The hook draws one `Image` per PNG, in place of the text.-4. Text size: the mod finds the terminal font (iTerm2 profile, Ghostty, kitty or Rio config; on Linux, else fontconfig's `monospace` font; else the metrics of the theme's code font, Menlo on macOS) and the cell size in pixels. Typst then measures both fonts so that 100% looks as large as the terminal text. Body text and code use the terminal font, so at 100% they are exactly the terminal's size. Ghostty and cmux draw their own JetBrains Mono when their config names no font. This font is not a file: it is inside the Ghostty program. The first time, the mod copies it to `~/.cache/cc-intelligent-ui/fonts/` (approximately 0.1 s, once for each Ghostty version), so that Typst can draw it. In Ghostty and cmux, the mod also removes the window padding from the cell size, because Ghostty adds the padding to the pixel size that it reports.+4. Text size: the mod finds the terminal font (iTerm2 profile, Ghostty, kitty or Rio config; on Linux, else fontconfig's `monospace` font; else the metrics of the theme's code font, Menlo on macOS) and the cell size in pixels. Typst then measures both fonts so that 100% looks as large as the terminal text. Body text and code use the terminal font, so at 100% they are exactly the terminal's size. The mod uses the font that the terminal draws: if the config names a font that is not installed, the terminal draws a different font, and the mod uses that font too (Ghostty and cmux on macOS, and Rio: their own font; Ghostty on Linux and kitty on Linux: the nearest font of fontconfig; kitty on macOS: Menlo; iTerm2: the user's fixed-pitch font, Menlo if you did not change it). If Ghostty's `font-family` is a list, the mod uses the first font of the list that is installed. Ghostty and cmux draw their own JetBrains Mono when their config names no font. Rio draws its own Cascadia Code NF when its config names no font (or `cascadiacode`). These fonts are not files: they are inside the program of the terminal. The first time, the mod copies the font to `~/.cache/cc-intelligent-ui/fonts/` (approximately 0.1 s for Ghostty and 0.5 s for Rio, once for each version of the terminal), so that Typst can draw it. If you set the `TYPST_FONT_PATHS` variable, Typst gets your folders and the copy. If the mod cannot copy Rio's font, it uses Cascadia Code if it is installed. If Typst does not have the terminal font, `/iui details` tells you, and the pictures use the theme's fonts. If the terminal font has no bold face (for example, Monaco), the pictures draw its bold text with a thin outline in the text colour (a fake bold, as a terminal draws it). The mod finds this with `typst fonts --variants` when it measures the fonts. In Ghostty and cmux, the mod also removes the window padding from the cell size, because Ghostty adds the padding to the pixel size that it reports.5. If a compile fails (a bad Typst block or an unknown LaTeX command), the mod compiles once more in safe mode: Typst blocks and math show as code. A dim line under the picture names the error. If that also fails, the normal text shows.6. Pictures are kept in `${TMPDIR}/cc-intelligent-ui-<uid>/` (`/tmp` when `TMPDIR` is not set). Folders older than 2 days are deleted at start. The drawing space of each answer at its first compile is kept in `~/.cache/cc-intelligent-ui/designs`, so that its Typst drawings keep the same share of the screen in later sessions.7. Links: the mod finds the web links, file paths and commands in the Markdown (not in code blocks or math). It draws one dim row for each under the pages, with a `Link` (an OSC 8 link) for a web link or a file, and a `Button` that copies a command (`$.ui.copy`). It keeps a file row only when the file exists (`$.fs.exists`, kept in memory for 512 paths). Each row is one terminal row, cut at its end. The copy (step 9) counts these rows under the pages, so it still finds the page that you select.diff --git a/docs/install.md b/docs/install.mdindex 293c994..0c69c4c 100644--- a/docs/install.md+++ b/docs/install.md@@ -56,7 +56,7 @@ The mod finds Typst on the `PATH` of your login shell. It also looks in `/usr/loThe mod works on Linux with X11 and with Wayland. It uses these tools. Most Linux systems have the first three.- **perl** (perl 5): reads the terminal size and its cell size, and watches for a change of the size. It also writes the frame files of the highlight for picture select (with `MIME::Base64`, a core module). On macOS, `/usr/bin/perl` also watches the clipboard for the `/iui grab` toast, with Apple's PerlObjCBridge (macOS has it).-- **fontconfig** (`fc-match`, `fc-list`): finds the terminal font when the terminal's config does not name one. kitty and most terminals use fontconfig's `monospace` font. Ghostty uses its own JetBrains Mono when its config names no font. If fontconfig does not have JetBrains Mono, the mod copies the font from the Ghostty program (refer to [How it works](how-it-works.md)).+- **fontconfig** (`fc-match`, `fc-list`): finds the terminal font when the terminal's config does not name one. kitty and most terminals use fontconfig's `monospace` font. Ghostty uses its own JetBrains Mono when its config names no font. If fontconfig does not have JetBrains Mono, the mod copies the font from the Ghostty program (refer to [How it works](how-it-works.md)). The mod also uses `fc-list` to find if the font that the terminal config names is installed.- **The light or dark mode of the desktop** (for the `auto` theme): the freedesktop portal (`org.freedesktop.appearance color-scheme`, through `gdbus` or `busctl`). GNOME, KDE Plasma and most desktops have the portal. If the portal does not answer, the mod reads GNOME's `color-scheme` (`gsettings`).- **The clipboard** (only for the `/iui grab` toast and for `/iui grab` on the main screen, refer to [Picture cells on the clipboard](usage.md#picture-cells-on-the-clipboard)). The mod uses the first of these that it finds:1. **Wayland, not GNOME:** `wl-paste` from `wl-clipboard`. `wl-paste --watch` tells the mod about each clipboard change. It needs the data-control protocol of the compositor (KDE Plasma, Sway, Hyprland and other wlroots compositors have it).diff --git a/hooks/lib/answer.ts b/hooks/lib/answer.tsindex a6a5f04..96593f5 100644--- a/hooks/lib/answer.ts+++ b/hooks/lib/answer.ts@@ -6,7 +6,7 @@import type { EngineInterface } from 'claude-code'import { BLANK_AFTER_LIVE_MS, BLANK_RESUMED_MS, DEFAULT_THEME, LIVE_STILL_MS, RESULTS_KEPT, SETTLE_MS } from './settings'-import { epochOpen, finalized, keep, lastKey, lastText, live, pending, results, S, type Env, type Frame, type Job, type Result, type Room } from './state'+import { epochOpen, fauxBoldOf, finalized, keep, lastKey, lastText, live, pending, results, S, type Env, type Frame, type Job, type Result, type Room } from './state'import { fontFit, hashOf, inlineOf, renderKey, sizing } from './draw'import { needsRoom } from './markdown'import { pictureColumns } from './frame'@@ -107,7 +107,7 @@ export async function pagesOf($: EngineInterface, o: PagesInput): Promise<Drawinconst 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, grid: S.grid,+ columnPt, templateStamp: env.stamp, look: active, inline: env.inline, base, room, grid: S.grid, fauxBold: fauxBoldOf(env.metrics),})const seen = lastText.get(id)const changed = seen !== textdiff --git a/hooks/lib/api.ts b/hooks/lib/api.tsindex bd873ef..b878bd8 100644--- a/hooks/lib/api.ts+++ b/hooks/lib/api.ts@@ -16,7 +16,7 @@ export type EnvName =| 'GHOSTTY_RESOURCES_DIR' | 'HOME'| 'ITERM_PROFILE' | 'ITERM_SESSION_ID' | 'IUI_DEBUG' | 'IUI_FORCE' | 'KITTY_CONFIG_DIRECTORY' | 'KITTY_PID'| 'KITTY_WINDOW_ID' | 'LC_TERMINAL' | 'RIO_CONFIG_HOME' | 'SHELL' | 'SSH_CONNECTION' | 'SSH_TTY' | 'STY'- | 'TERM' | 'TERM_PROGRAM' | 'TMUX' | 'WAYLAND_DISPLAY' | 'XDG_CONFIG_HOME' | 'XDG_CURRENT_DESKTOP' | 'ZDOTDIR'+ | 'TERM' | 'TERM_PROGRAM' | 'TMUX' | 'TYPST_FONT_PATHS' | 'WAYLAND_DISPLAY' | 'XDG_CONFIG_HOME' | 'XDG_CURRENT_DESKTOP' | 'ZDOTDIR'export function clockAfter($: EngineInterface, ms: number, fn: () => void) {return $.clock.after(ms, fn)@@ -73,6 +73,7 @@ export function envGet($: EngineInterface, name: EnvName): Promise<string | undecase 'TERM': return $.env.get('TERM')case 'TERM_PROGRAM': return $.env.get('TERM_PROGRAM')case 'TMUX': return $.env.get('TMUX')+ case 'TYPST_FONT_PATHS': return $.env.get('TYPST_FONT_PATHS')case 'WAYLAND_DISPLAY': return $.env.get('WAYLAND_DISPLAY')case 'XDG_CONFIG_HOME': return $.env.get('XDG_CONFIG_HOME')case 'XDG_CURRENT_DESKTOP': return $.env.get('XDG_CURRENT_DESKTOP')diff --git a/hooks/lib/draw.tsx b/hooks/lib/draw.tsxindex dbc3054..19cc468 100644--- a/hooks/lib/draw.tsx+++ b/hooks/lib/draw.tsx@@ -79,6 +79,8 @@ export function renderKey(o: {// `/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+ // The fake bold of a terminal font with no bold face (fauxBoldOf).+ fauxBold?: boolean}): string {const { room } = oreturn hashOf([@@ -87,6 +89,7 @@ export function renderKey(o: {...(o.base ? ['base', o.base] : []),...(room ? ['room', room.heightPt, room.design.widthPt, room.design.heightPt] : []),...(o.grid ? ['grid', GRID_VERSION] : []),+ ...(o.fauxBold ? ['faux-bold'] : []),])}diff --git a/hooks/lib/env.ts b/hooks/lib/env.tsindex b1d950c..e26e1b7 100644--- a/hooks/lib/env.ts+++ b/hooks/lib/env.ts@@ -84,6 +84,7 @@ export function setUp($: EngineInterface): Promise<Env> {if (S.setupNeeded) void offerSetup($).catch(() => undefined)S.isCmux = !!(await envGet($, 'CMUX_SURFACE_ID')) || !!(await envGet($, 'CMUX_WORKSPACE_ID')) || !!(await envGet($, 'CMUX_SOCKET_PATH'))S.colorFgBg = (await envGet($, 'COLORFGBG')) ?? ''+ S.userFontPaths = (await envGet($, 'TYPST_FONT_PATHS')) ?? ''if (S.setting === 'auto') S.host = (await readHostMode($).catch(() => null)) ?? S.hostS.theme = resolveMode(S.setting, S.host)watchHost($)diff --git a/hooks/lib/fonts.ts b/hooks/lib/fonts.tsindex 8dee1d7..00b8765 100644--- a/hooks/lib/fonts.ts+++ b/hooks/lib/fonts.ts@@ -46,6 +46,26 @@ export function fontListOf(stdout: string): Map<string, Face[]> {return families}+// Whether `typst fonts --variants` lists a bold face of a family: a weight+// of 600 or more (a variable font: its top weight). Null when the family is+// not listed.+export function hasBoldFace(stdout: string, family: string): boolean | null {+ const want = family.trim().toLowerCase()+ let inFamily = false+ let seen = false+ let bold = false+ for (const line of stdout.split('\n')) {+ if (line && !/^\s/.test(line)) {+ inFamily = line.trim().toLowerCase() === want+ seen ||= inFamily+ continue+ }+ const m = inFamily ? /Weight:\s*(\d+)(?:-(\d+))?/.exec(line) : null+ if (m && Number(m[2] ?? m[1]) >= 600) bold = true+ }+ return seen ? bold : null+}+// The font files of the lean set, in the order of the list: the faces of// the terminal font and of each body and code font that is not skipped.// Null when the lean set can draw differently: the first font of a listdiff --git a/hooks/lib/host.ts b/hooks/lib/host.tsindex e00ec4e..52adf9e 100644--- a/hooks/lib/host.ts+++ b/hooks/lib/host.ts@@ -9,11 +9,11 @@ import { S } from './state'import { beginEpoch } from './epoch'import { luminanceOf, modeOfColorFgBg, modeOfLuminance, modeOfMacAppearance, parseOsc11, resolveMode, schemeOfPortal, type HostMode } from './mode'import {- cmuxAppearanceOf, cmuxConfigOf, cmuxGhosttyConfigPath, cmuxSettingsOf, familyOfFc, GHOSTTY_DEFAULT_FONT, ghosttyBackgroundOf, ghosttyFontOf, ghosttyHasColors,+ cmuxAppearanceOf, cmuxConfigOf, cmuxGhosttyConfigPath, cmuxSettingsOf, familyOfFc, GHOSTTY_DEFAULT_FONT, ghosttyBackgroundOf, ghosttyFontsOf, ghosttyHasColors,ghosttyThemePaths, ghosttyThemesOf,ghosttyValueOf, hexColorOf, itermAppearanceOf, itermFontOf, itermModeOf, jsoncOf, kittyAutoFileOf, kittyBackgroundOf,- kittyConfigDirsOf, kittyEntriesOf, kittyFontOf, kittySchemeOfGnome, kittyValueOf, parseFontSpec, rioBackgroundOf,- rioConfigDirOf, rioFontOf, rioForcedOf, rioThemeNamesOf, rioThemePath, tomlStringsOf, type CmuxAppearance, type KittyEntries,+ kittyConfigDirsOf, kittyEntriesOf, kittyFontOf, kittySchemeOfGnome, kittyValueOf, KITTY_MAC_FONT, parseFontSpec, rioBackgroundOf,+ rioConfigDirOf, RIO_DEFAULT_FONT, RIO_OLD_FONT, rioFontOf, rioForcedOf, rioThemeNamesOf, rioThemePath, tomlStringsOf, type CmuxAppearance, type KittyEntries,} from './terminals'import { firstLine } from './markdown'import { isGhosttyHere } from './terminal'@@ -84,28 +84,48 @@ export const WATCH_PL = [export const perlFor = (isMac: boolean) => (isMac ? '/usr/bin/perl' : 'perl')const ITERM_BOOKMARKS_SH = `defaults export com.googlecode.iterm2 - | plutil -extract "New Bookmarks" json -o - -`const ITERM_DEFAULT_SH = `defaults read com.googlecode.iterm2 "Default Bookmark Guid"`-// A PostScript name (argv[0]) to its family name.-const FAMILY_JXA = 'function run(argv) { ObjC.import("AppKit"); var f = $.NSFont.fontWithNameSize(argv[0], 12); return f.isNil() ? "" : f.familyName.js }'+// A PostScript name (argv[0]) to its family name; with argv[1] `user`, a+// name that is not installed gives the user's fixed-pitch font (iTerm2 then+// draws it: Menlo, unless it was changed).+const FAMILY_JXA = 'function run(argv) { ObjC.import("AppKit"); var f = argv[0] ? $.NSFont.fontWithNameSize(argv[0], 12) : null; if ((!f || f.isNil()) && argv[1] === "user") f = $.NSFont.userFixedPitchFontOfSize(12); return !f || f.isNil() ? "" : f.familyName.js }'+// Whether a family (argv[0]) is installed, as CoreText finds it by name:+// yes or no; with argv[1] `mono`, `proportional` when no style of it is fixed-pitch.+const HAS_FAMILY_JXA = 'function run(argv) { ObjC.import("AppKit"); var m = $.NSFontManager.sharedFontManager.availableMembersOfFontFamily(argv[0]); if (m.isNil()) return "no"; if (argv[1] !== "mono") return "yes"; for (var i = 0; i < m.count; i++) if (m.objectAtIndex(i).objectAtIndex(3).js & 0x400) return "yes"; return "proportional" }'// iTerm2's appearance, the default profile's GUID and the profiles, split by "@" lines.const ITERM_MODE_SH = `defaults read com.googlecode.iterm2 TabStyleWithAutomaticOption 2>/dev/null; echo @; ${ITERM_DEFAULT_SH} 2>/dev/null; echo @; ${ITERM_BOOKMARKS_SH}`const GHOSTTY_SH = `"\${GHOSTTY_BIN_DIR:+\$GHOSTTY_BIN_DIR/}ghostty" +show-config`-// Copies the JetBrains Mono that Ghostty carries in its program (no font-// files: the TrueType data is inside it) to a folder that Typst can read,-// once per Ghostty build: the variable Regular and Italic (an `fvar` table-// and the family in the `name` table), each size once (a universal program-// has a copy per CPU). The folder is in the user cache, by the program's-// path, size and mtime; it prints the folder, and exit 1 when no font was-// found. Made in a temporary folder first, so a compile never sees half.-export const GHOSTTY_FONTS_PL = [+// Copies the font that a terminal carries in its program (no font files:+// the TrueType data is inside it; Ghostty's JetBrains Mono, Rio's Cascadia+// Code NF) to a folder that Typst can read, once per build: the variable+// Regular and Italic (an `fvar` table and the family, argument 2, in the+// `name` table), each size once (a universal program has a copy per CPU).+// The folder is in the user cache, by the tag (argument 1) and the+// program's path, size and mtime; it prints the folder. Exit 3 when the+// program has no such font (kept as a `.none` marker, so the next run does+// not read the program again); exit 1 for other failures. Made in a+// temporary folder first, so a compile never sees half. Each new copy or+// marker removes the tag's temporary folders of 1 day and its other folders+// and markers of 7 days (an older build's).+export const PROGRAM_FONTS_PL = ['use strict;',- 'my $f = shift or exit 1;',+ 'my ($tag, $family, $f) = @ARGV; $f or exit 1;','my @st = stat($f) or exit 1;','my $base = ($ENV{XDG_CACHE_HOME} || "$ENV{HOME}/.cache") . "/cc-intelligent-ui/fonts";','my $key = unpack("%32C*", $f) . "-$st[7]-$st[9]";',- 'my $d = "$base/ghostty-$key";',+ 'my $d = "$base/$tag-$key";','if (-d $d) { utime(undef, undef, $d); print "$d\\n"; exit 0 }',+ 'exit 3 if -e "$d.none";',+ 'sub sweep {',+ ' opendir(my $dh, $base) or return;',+ ' for my $e (readdir $dh) {',+ ' next unless index($e, "$tag-") == 0; my $p = "$base/$e";',+ ' next if $p eq $d || $p eq "$d.none"; my $age = -M $p; next unless defined $age;',+ ' next unless $e =~ /\\.\\d+$/ ? $age > 1 : $age > 7;',+ ' if (-d $p) { system("rm", "-rf", $p) } else { unlink $p }',+ ' }',+ '}','open(my $h, "<:raw", $f) or exit 1; my $b = do { local $/; <$h> }; close $h;',- 'my $want = "\\0" . join("\\0", split(//, "JetBrains Mono"));',+ 'my $want = "\\0" . join("\\0", split(//, $family));','system("mkdir", "-p", $base) == 0 or exit 1;','my $t = "$d.$$"; mkdir($t) or exit 1;','my (%seen, $n);',@@ -114,32 +134,39 @@ export const GHOSTTY_FONTS_PL = [' next if $k < 4 || $k > 40;',' my ($end, $fvar, $name, $bad) = (0, 0, "", 0);',' for my $i (0 .. $k - 1) {',- ' my ($tag, $cs, $off, $len) = unpack("a4NNN", substr($b, $o + 12 + 16 * $i, 16));',- ' if ($tag !~ m{^[A-Za-z0-9/ ]{4}$} || $off + $len > 20000000) { $bad = 1; last }',+ ' my ($tt, $cs, $off, $len) = unpack("a4NNN", substr($b, $o + 12 + 16 * $i, 16));',+ ' if ($tt !~ m{^[A-Za-z0-9/ ]{4}$} || $off + $len > 20000000) { $bad = 1; last }',' $end = $off + $len if $off + $len > $end;',- ' $fvar = 1 if $tag eq "fvar";',- ' $name = substr($b, $o + $off, $len) if $tag eq "name";',+ ' $fvar = 1 if $tt eq "fvar";',+ ' $name = substr($b, $o + $off, $len) if $tt eq "name";',' }',' next if $bad || !$fvar || index($name, $want) < 0 || $seen{$end}++;',- ' open(my $w, ">:raw", "$t/JetBrainsMono-" . ++$n . ".ttf") or next;',+ ' open(my $w, ">:raw", "$t/$tag-" . ++$n . ".ttf") or next;',' print $w substr($b, $o, $end); close $w;','}',- 'if (!$n) { rmdir $t; exit 1 }',+ 'if (!$n) { rmdir $t; if (open(my $m, ">", "$d.none")) { close $m } sweep(); exit 3 }','rename($t, $d) or system("rm", "-rf", $t);',- '-d $d or exit 1; print "$d\\n";',+ '-d $d or exit 1; sweep(); print "$d\\n";',].join('\n')-// Runs GHOSTTY_FONTS_PL (with the perl of perlFor) on the first Ghostty-// program found: the one of GHOSTTY_BIN_DIR, the PATH's, then each other-// argument (the apps' places).-export const GHOSTTY_FONTS_SH = [- 'perl=$1; pl=$2; shift 2',- 'for f in "${GHOSTTY_BIN_DIR:+$GHOSTTY_BIN_DIR/ghostty}" "$(command -v ghostty)" "$@"; do',- ' [ -n "$f" ] && [ -f "$f" ] && exec "$perl" -e "$pl" "$f"',+// Runs PROGRAM_FONTS_PL (with the perl of perlFor) with a tag and a family+// on the first program found: for ghostty the one of GHOSTTY_BIN_DIR, then+// the PATH's command of that name, then each other path (the apps' places).+// Exit 2 when no program is found.+export const PROGRAM_FONTS_SH = [+ 'perl=$1; pl=$2; tag=$3; family=$4; name=$5; shift 5',+ 'first=; [ "$name" = ghostty ] && first=${GHOSTTY_BIN_DIR:+$GHOSTTY_BIN_DIR/ghostty}',+ 'for f in "$first" "$(command -v "$name")" "$@"; do',+ ' [ -n "$f" ] && [ -f "$f" ] && exec "$perl" -e "$pl" "$tag" "$family" "$f"','done',- 'exit 1',+ 'exit 2',].join('\n')// Where the apps keep their Ghostty program.const GHOSTTY_PROGRAMS = ['/Applications/cmux.app/Contents/Resources/bin/ghostty', '/Applications/Ghostty.app/Contents/MacOS/ghostty']+// Where Rio's program can be (after the PATH's): the macOS app (rio.app), cargo's, Flatpak's.+const rioProgramsOf = (home: string) => [+ '/Applications/rio.app/Contents/MacOS/rio', `${home}/Applications/rio.app/Contents/MacOS/rio`, `${home}/.cargo/bin/rio`,+ '/var/lib/flatpak/app/com.rioterm.Rio/current/active/files/bin/rio', `${home}/.local/share/flatpak/app/com.rioterm.Rio/current/active/files/bin/rio`,+]// Asks the terminal for its background (OSC 11) and prints the answer. It// opens the tty itself, non-blocking, changes no tty mode, and waits 300 ms at// most. Claude Code reads the same tty, so the answer may go to it instead.@@ -164,8 +191,10 @@ export const HEADERS_SH = `for f in "$@"; do head -c 24 "$f" | od -An -v -tx1; e// The terminal's font family: iTerm2's profile font, Ghostty's font-family,// kitty's font_family, Rio's [fonts] family; '' elsewhere or when it can't-// be read. On Linux, when the terminal's config names none: fontconfig's-// monospace font (fc-match), which kitty and most terminals use.+// be read. A family that the terminal does not find is the one it draws in+// its place (its own font, Menlo, or fontconfig's nearest). On Linux, when+// the terminal's config names none: fontconfig's monospace font (fc-match),+// which kitty and most terminals use.export async function termFontOf($: EngineInterface, isMac: boolean): Promise<string> {// Over ssh, a config here is not the one of the user's terminal.if (S.isRemote) return ''@@ -174,6 +203,9 @@ export async function termFontOf($: EngineInterface, isMac: boolean): Promise<streturn fcFamily($, 'monospace')}+// A family as a fontconfig pattern: its `-`, `:`, `,` and `\` escaped.+export const fcPatternOf = (family: string) => family.replace(/[\\\-:,]/g, '\\$&')+// A family fontconfig gives for a pattern (the first of its names), '' when// fc-match fails. `fc-match` always gives a font, the nearest one.async function fcFamily($: EngineInterface, pattern: string): Promise<string> {@@ -181,17 +213,86 @@ async function fcFamily($: EngineInterface, pattern: string): Promise<string> {return got?.exitCode === 0 ? familyOfFc(got.stdout) : ''}-// Ghostty draws its own JetBrains Mono when no font-family is set. Typst-// draws it from the system's fonts when fontconfig has it (Linux), else-// from a copy of the one in Ghostty's program (S.fontPaths).+// The family of the first font that fontconfig lists for a pattern (only+// fonts that match it), '' for none.+async function fcListFamily($: EngineInterface, pattern: string): Promise<string> {+ const got = await processRun($, ['fc-list', pattern, 'family'], { timeoutMs: 5000 }).catch(() => null)+ return got?.exitCode === 0 ? familyOfFc(firstLine(got.stdout)) : ''+}++// What CoreText says of a family (HAS_FAMILY_JXA), '' when it can't be read.+async function macFamily($: EngineInterface, family: string, mono = false): Promise<string> {+ const got = await processRun($, ['osascript', '-l', 'JavaScript', '-e', HAS_FAMILY_JXA, family, ...(mono ? ['mono'] : [])], { timeoutMs: 5000 }).catch(() => null)+ return got?.exitCode === 0 ? firstLine(got.stdout) : ''+}++// Whether a family is installed: CoreText on macOS, fontconfig on Linux+// (`exact`: the name as is, as Rio's font database matches it; else in+// any case and spacing). Null when that can't be read (then the family is+// taken as is).+async function hasFamily($: EngineInterface, isMac: boolean, family: string, exact = false): Promise<boolean | null> {+ if (isMac) {+ const seen = await macFamily($, family)+ return seen ? seen === 'yes' : null+ }+ if (exact) {+ const got = await processRun($, ['fc-list', ':', 'family'], { timeoutMs: 5000 }).catch(() => null)+ if (got?.exitCode !== 0) return null+ // Each line is a family's names, split by commas, with `\` escapes.+ return got.stdout.split('\n').some(line => line.split(/(?<!\\),/).some(name => name.replace(/\\(.)/g, '$1').trim() === family))+ }+ const got = await processRun($, ['fc-list', '-q', fcPatternOf(family)], { timeoutMs: 5000 }).catch(() => null)+ return got?.exitCode === 0 ? true : got?.exitCode === 1 ? false : null+}++// Copies the font a terminal carries in its program (PROGRAM_FONTS_PL) and+// gives it to Typst (S.fontPaths): 'copied', 'none' (the program has no+// such font) or 'failed' (no program, or the copy failed).+async function programFont($: EngineInterface, isMac: boolean, o: { tag: string; family: string; name: string; paths: readonly string[] }): Promise<'copied' | 'none' | 'failed'> {+ const argv = ['sh', '-c', PROGRAM_FONTS_SH, 'sh', perlFor(isMac), PROGRAM_FONTS_PL, o.tag, o.family, o.name, ...o.paths]+ const made = await processRun($, argv, { timeoutMs: 10000 }).catch(() => null)+ if (made?.exitCode === 3) return 'none'+ const dir = made?.exitCode === 0 ? firstLine(made.stdout) : ''+ if (!dir) return 'failed'+ S.fontPaths = dir+ return 'copied'+}++// Ghostty draws its own JetBrains Mono when no font-family is set (and on+// macOS when it finds none of them). Typst draws it from the system's fonts+// when fontconfig has it (Linux), else from a copy of the one in Ghostty's+// program (S.fontPaths).async function ghosttyDefaultFont($: EngineInterface, isMac: boolean): Promise<string> {const got = await processRun($, ['fc-list', '-q', GHOSTTY_DEFAULT_FONT], { timeoutMs: 5000 }).catch(() => null)if (got?.exitCode === 0) return GHOSTTY_DEFAULT_FONT- const made = await processRun($, ['sh', '-c', GHOSTTY_FONTS_SH, 'sh', perlFor(isMac), GHOSTTY_FONTS_PL, ...GHOSTTY_PROGRAMS], { timeoutMs: 10000 }).catch(() => null)- const dir = made?.exitCode === 0 ? firstLine(made.stdout) : ''- if (!dir) return ''- S.fontPaths = dir- return GHOSTTY_DEFAULT_FONT+ const o = { tag: 'ghostty', family: GHOSTTY_DEFAULT_FONT, name: 'ghostty', paths: GHOSTTY_PROGRAMS }+ return (await programFont($, isMac, o)) === 'copied' ? GHOSTTY_DEFAULT_FONT : ''+}++// Ghostty's font: the first family of its font-family list that it finds.+// None found: on macOS its own JetBrains Mono; on Linux fontconfig's+// nearest font for the first family (Ghostty takes the first font of+// fontconfig's sorted list). No list: its own JetBrains Mono.+async function ghosttyFont($: EngineInterface, isMac: boolean, names: readonly string[]): Promise<string> {+ if (!names.length) return ghosttyDefaultFont($, isMac)+ for (const name of names) if ((await hasFamily($, isMac, name)) !== false) return name+ if (isMac) return ghosttyDefaultFont($, isMac)+ return (await fcFamily($, fcPatternOf(names[0]!))) || names[0]!+}++// Rio draws its own Cascadia Code NF when the config names no font (or+// `cascadiacode`, or one it does not find by its exact name): a copy of+// the one in Rio's program. A Rio up to 0.4 carries a Cascadia Code with+// no `fvar` (none found): Cascadia Code. No program: the system's Cascadia+// Code (the same letters) when it is installed.+async function rioFont($: EngineInterface, isMac: boolean): Promise<string> {+ const named = rioFontOf((await readRioConfig($)).config)+ if (named !== RIO_DEFAULT_FONT && (await hasFamily($, isMac, named, true)) !== false) return named+ const home = (await envGet($, 'HOME')) ?? ''+ const copy = await programFont($, isMac, { tag: 'rio', family: RIO_DEFAULT_FONT, name: 'rio', paths: rioProgramsOf(home) })+ if (copy === 'copied') return RIO_DEFAULT_FONT+ if (copy === 'none') return RIO_OLD_FONT+ return (await hasFamily($, isMac, RIO_OLD_FONT)) ? RIO_OLD_FONT : RIO_DEFAULT_FONT}// The font that the terminal's own config or profile names.@@ -202,29 +303,40 @@ async function configFontOf($: EngineInterface, isMac: boolean): Promise<string>processRun($, ['sh', '-c', ITERM_BOOKMARKS_SH], { timeoutMs: 5000 }).catch(() => null),processRun($, ['sh', '-c', ITERM_DEFAULT_SH], { timeoutMs: 5000 }).catch(() => null),])- const spec = parseFontSpec(itermFontOf(marks?.stdout ?? '', profile, guid?.stdout ?? '') ?? '')- if (!spec) return ''- const named = await processRun($, ['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, spec.name], { timeoutMs: 5000 }).catch(() => null)+ // A read that failed or no profile: not known.+ const font = marks?.exitCode === 0 ? itermFontOf(marks.stdout, profile, guid?.stdout ?? '') : null+ if (font === null) return ''+ // An empty or bad profile font, or one that is not installed: iTerm2 draws the user's fixed-pitch font.+ const named = await processRun($, ['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, parseFontSpec(font)?.name ?? '', 'user'], { timeoutMs: 5000 }).catch(() => null)return named?.exitCode === 0 ? firstLine(named.stdout) : ''}if (isGhosttyHere()) {const shown = await processRun($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: 5000 }).catch(() => null)- return ghosttyFontOf(shown?.stdout ?? '') ?? (await ghosttyDefaultFont($, isMac))+ // cmux loads its own config after Ghostty's; +show-config does not read it.+ const own = S.isCmux ? ((await readText($, cmuxGhosttyConfigPath((await envGet($, 'HOME')) ?? ''))) ?? '') : ''+ return ghosttyFont($, isMac, ghosttyFontsOf(cmuxConfigOf(shown?.stdout ?? '', own)))}if (S.isKitty) {- // A family name as is; a PostScript name to its family (macOS: AppKit;- // Linux: fontconfig); the system's monospace from fontconfig (Linux,- // termFontOf; on macOS it is Menlo).+ // As kitty finds a font: a family name, else a full or PostScript name+ // (macOS: AppKit; Linux: fontconfig), else the nearest font (macOS:+ // Menlo; Linux: fontconfig's monospace match). kitty looks only at+ // fixed-pitch fonts. No font_family: the system's monospace (macOS:+ // Menlo; Linux: fontconfig's, in termFontOf).const font = kittyFontOf(kittyValueOf((await readKittyConfig($)).entries, 'font_family'))- if (font && 'family' in font) return font.family- if (font && isMac) {- const named = await processRun($, ['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, font.postscript], { timeoutMs: 5000 }).catch(() => null)- return named?.exitCode === 0 ? firstLine(named.stdout) : ''+ if (!font) return isMac ? KITTY_MAC_FONT : ''+ const name = 'family' in font ? font.family : font.postscript+ if (isMac) {+ const seen = 'family' in font ? await macFamily($, name, true) : 'no'+ if (seen === 'yes' || seen === '') return name+ if (seen === 'proportional') return KITTY_MAC_FONT+ const named = await processRun($, ['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, name], { timeoutMs: 5000 }).catch(() => null)+ return named?.exitCode === 0 ? firstLine(named.stdout) || KITTY_MAC_FONT : ''}- if (font) return fcFamily($, `:postscriptname=${font.postscript}`)- return ''+ if ('family' in font && (await hasFamily($, isMac, name)) !== false) return name+ const exact = (await fcListFamily($, `:postscriptname=${fcPatternOf(name)}`)) || (await fcListFamily($, `:fullname=${fcPatternOf(name)}`))+ return exact || (await fcFamily($, `${'family' in font ? fcPatternOf(name) : `:postscriptname=${fcPatternOf(name)}`}:spacing=mono`))}- if (isRioHere()) return rioFontOf((await readRioConfig($)).config)+ if (isRioHere()) return rioFont($, isMac)return ''}diff --git a/hooks/lib/plan.tsx b/hooks/lib/plan.tsxindex 79e6dda..36a1085 100644--- a/hooks/lib/plan.tsx+++ b/hooks/lib/plan.tsx@@ -85,16 +85,15 @@ export function planFileOf(input: unknown): string {return typeof file === 'string' && file.startsWith('/') ? file : ''}-// The plan a row of the call shows: the text edited in the mod's flow, else-// the result's, else the call's; '' for none and for a subagent's or a-// teammate's result.+// The plan a row of the call shows: '' for a subagent's or a teammate's+// result; else the result's (the approved text, also an edit in the+// engine's dialog), else the text the mod read or edited, else the call's.export function planShownOf(edited: string | undefined, output: unknown, input: unknown): string {- if (edited?.trim()) return editedif (output && typeof output === 'object') {const o = output as { isAgent?: unknown; awaitingLeaderApproval?: unknown }if (o.isAgent === true || o.awaitingLeaderApproval === true) return ''}- return planOf(output) ?? planInputOf(input)+ return planOf(output) ?? (edited?.trim() ? edited : planInputOf(input))}// A path as the person reads it: `~/...` under the home folder.@@ -252,6 +251,7 @@ export async function decidePlan(// The plan file's text once no Write or Edit of it is still running (at most// PLAN_WRITE_WAIT_MS): Claude may write the plan and call ExitPlanMode in one// message, and the call then carries the file as it was before the write.+// 2.1.306 reads it again for the call, but the row's input stays the streamed copy.// `fallback` when the file can't be read.export async function currentPlan($: EngineInterface, file: string, fallback: string): Promise<string> {if (!file) return fallbackdiff --git a/hooks/lib/state.ts b/hooks/lib/state.tsindex 7f30cf6..5c3e414 100644--- a/hooks/lib/state.ts+++ b/hooks/lib/state.ts@@ -41,8 +41,11 @@ export type LeanFonts = { body: string[]; code: string[]; plain: boolean }// `term` the terminal's font (null when unknown or not installed), `menlo`// the template's code font, `body` its text font, `grid` the row grid's// numbers (DEFAULT_GRID when not given), `fonts` the theme's font lists-// (none: no lean font set).-export type Metrics = { term: FontMetrics | null; menlo: FontMetrics; body: FontMetrics; grid?: GridMetrics; fonts?: LeanFonts }+// (none: no lean font set), `termBold` whether Typst has a bold face of the+// terminal's font (none: not known).+export type Metrics = { term: FontMetrics | null; menlo: FontMetrics; body: FontMetrics; grid?: GridMetrics; fonts?: LeanFonts; termBold?: boolean }+// The terminal's font is known and has no bold face: md.typ draws a fake bold (term-bold=0).+export const fauxBoldOf = (m: Metrics) => !!m.term && m.termBold === false// Measured with Typst on macOS: Menlo and SF Pro Text.export const DEFAULT_METRICS: Metrics = {term: null,@@ -173,9 +176,11 @@ export const S = {// iTerm2 (isItermIn) and cmux (Ghostty inside, with its CMUX_* variables), set in setUp.isIterm: false,isCmux: false,- // A font folder for Typst (TYPST_FONT_PATHS): the fonts Ghostty carries in- // its program, when it draws them (no font-family set). '' for none.+ // A font folder for Typst (TYPST_FONT_PATHS): the font a terminal carries+ // in its program (Ghostty's, Rio's), when it draws it. '' for none.fontPaths: '',+ // The user's own TYPST_FONT_PATHS (set in setUp); fontPaths goes after it.+ userFontPaths: '',// Over ssh (set in setUp): the terminal's config and the OS appearance here// are the remote computer's, not those of the user's screen.isRemote: false,diff --git a/hooks/lib/terminals.ts b/hooks/lib/terminals.tsindex 61df508..fbcb4db 100644--- a/hooks/lib/terminals.ts+++ b/hooks/lib/terminals.ts@@ -53,14 +53,17 @@ export function itermModeOf(bookmarks: string, profile: string | undefined, defa}// "MesloLGS-NF-Regular 14" (iTerm2's Normal Font) → PostScript name and size.+// As iTerm2 reads it: the name to the first space, the size, then any+// settings (`{"featureSettings":…}`), which are skipped.export function parseFontSpec(spec: string): { name: string; size: number } | null {- const m = /^\s*(\S.*?)\s+(\d+(?:\.\d+)?)\s*$/.exec(spec)+ const m = /^\s*(\S+) +(\d+(?:\.\d+)?)(?:\s|$)/.exec(spec)return m ? { name: m[1]!, size: Number(m[2]) } : null}// The Normal Font of the iTerm2 profile in use: the bookmark named// ITERM_PROFILE, else the default bookmark. `bookmarks` is the JSON of the-// plist's "New Bookmarks" array.+// plist's "New Bookmarks" array. Null when that is not JSON or has no such+// profile; '' when the profile has no font.export function itermFontOf(bookmarks: string, profile: string | undefined, defaultGuid: string): string | null {let list: unknowntry {@@ -69,8 +72,10 @@ export function itermFontOf(bookmarks: string, profile: string | undefined, defareturn null}if (!Array.isArray(list)) return null- const font = pickProfile(list, profile, defaultGuid)?.['Normal Font']- return typeof font === 'string' && font.trim() ? font.trim() : null+ const mark = pickProfile(list, profile, defaultGuid)+ if (!mark) return null+ const font = mark['Normal Font']+ return typeof font === 'string' ? font.trim() : ''}// Ghostty's background when its config sets none and no theme.@@ -142,16 +147,25 @@ export const GHOSTTY_DEFAULT_FONT = 'JetBrains Mono'// can be a list (`Noto Sans Mono,Noto Sans Mono Regular`).export const familyOfFc = (stdout: string) => (stdout.split(',')[0] ?? '').trim()-// The first `font-family = X` of `ghostty +show-config`.-export function ghosttyFontOf(config: string): string | null {+// Ghostty's `font-family` list: `ghostty +show-config` (with cmux's own+// config after it). An empty value clears the list.+export function ghosttyFontsOf(config: string): string[] {+ let list: string[] = []for (const line of config.split('\n')) {const m = /^\s*font-family\s*=\s*(.*?)\s*$/.exec(line)- const family = m?.[1]?.replace(/^"(.*)"$/, '$1').trim()- if (family) return family+ if (!m) continue+ const family = m[1]!.replace(/^"(.*)"$/, '$1').trim()+ list = family ? [...list, family] : []}- return null+ return list}+// The first font of Ghostty's `font-family` list, or null.+export const ghosttyFontOf = (config: string): string | null => ghosttyFontsOf(config)[0] ?? null++// The font kitty draws on macOS for `monospace` and for a font it does not find.+export const KITTY_MAC_FONT = 'Menlo'+// kitty's background when no config or auto theme sets one.export const KITTY_DEFAULT_BG = '#000000'// At most this many kitty config files are read (kitty.conf and its includes).@@ -256,8 +270,11 @@ export function kittyBackgroundOf(conf: KittyEntries, auto: { file: string; entr// Rio's background when neither its config nor a theme sets one.export const RIO_DEFAULT_BG = '#0f0d0e'-// Rio's font when the config names none (the Cascadia Code it carries).-export const RIO_DEFAULT_FONT = 'Cascadia Code'+// The font Rio carries and draws when the config names none (or one that+// it does not find): Cascadia Code NF, by its family name.+export const RIO_DEFAULT_FONT = 'Cascadia Code NF'+// The font a Rio up to 0.4 carries (no `fvar`, so it is not copied out).+export const RIO_OLD_FONT = 'Cascadia Code'// The string values of a TOML file by dotted path (`[fonts.regular]` then// `family = "X"` is `fonts.regular.family`). Only what Rio's few keys need:@@ -345,10 +362,11 @@ export function rioBackgroundOf(config: Readonly<Record<string, string>>, appear}// Rio's font: `[fonts] family` (it sets every style), else `[fonts.regular]-// family`, else the one Rio carries.+// family`, else the one Rio carries (also for `cascadiacode`, its default+// name, in any case and spacing: Rio then never looks in the system).export function rioFontOf(config: Readonly<Record<string, string>>): string {const family = (config['fonts.family'] || config['fonts.regular.family'] || '').trim()- return !family || family.replace(/\s/g, '').toLowerCase() === 'cascadiacode' ? RIO_DEFAULT_FONT : family+ return !family || family.replace(/ /g, '').toLowerCase() === 'cascadiacode' ? RIO_DEFAULT_FONT : family}// iTerm2: TERM_PROGRAM says so; with no TERM_PROGRAM (it is not alwaysdiff --git a/hooks/lib/typst.ts b/hooks/lib/typst.tsindex 5024a1f..adf05c6 100644--- a/hooks/lib/typst.ts+++ b/hooks/lib/typst.ts@@ -3,7 +3,7 @@import type { EngineInterface } from 'claude-code'import { COMPILE_TIMEOUT_MS, MAX_IMAGE_ROWS, NO_NETWORK, SEGMENT_ROWS, TOUCH_FLUSH_MS, TYPST_FALLBACKS } from './settings'-import { DEFAULT_METRICS, S, type Cell, type FontMetrics, type Job, type LeanFonts, type Metrics, type Page, type Result } from './state'+import { DEFAULT_METRICS, fauxBoldOf, S, type Cell, type FontMetrics, type Job, type LeanFonts, type Metrics, type Page, type Result } from './state'import { firstLine, imagePathOf, localImages, plainOf, splitInTwo, splitSegments } from './markdown'import { inlineBudget } from './terminal'import { fontFit, placeFirstLine, sizing } from './draw'@@ -11,7 +11,7 @@ import { DEFAULT_GRID, gridOf } from './grid'import { HEADERS_SH } from './host'import { logDebug } from './log'import { positionsOf, type Mark, type Positions } from './copy'-import { leanFontsFor } from './fonts'+import { hasBoldFace, leanFontsFor } from './fonts'import { clockAfter, envGet, fsExists, fsList, fsRead, fsWrite, processRun, spawn } from './api'// The typst command and its environment. Network off (see NO_NETWORK) and a@@ -86,7 +86,8 @@ export function noNetworkEnv(cache: string): Record<string, string> {NO_PROXY: '',no_proxy: '',TYPST_PACKAGE_CACHE_PATH: `${cache}/pkg-cache`,- ...(S.fontPaths ? { TYPST_FONT_PATHS: S.fontPaths } : {}),+ // The user's own folders stay (':' is the separator on macOS and Linux).+ ...(S.fontPaths ? { TYPST_FONT_PATHS: [S.userFontPaths, S.fontPaths].filter(Boolean).join(':') } : {}),}}@@ -144,15 +145,24 @@ export function leanFontsOf(v: unknown): LeanFonts | undefined {return f && names(f.body) && names(f.code) && typeof f.plain === 'boolean' ? { body: f.body, code: f.code, plain: f.plain } : undefined}-// The fonts' metrics from render/measure.typ; the macOS defaults when that fails.+// The fonts' metrics from render/measure.typ; the macOS defaults when that+// fails. With the font list (in the same time): whether the terminal's font+// has a bold face.export async function measureFonts($: EngineInterface, typst: string, root: string, cache: string, family: string, themeDir: string): Promise<Metrics> {const argv = measureCall(typst, root, family, themeDir)- const got = await processRun($, argv, { timeoutMs: 10000, env: noNetworkEnv(cache) }).catch(() => null)+ const env = noNetworkEnv(cache)+ const [got, listed] = await Promise.all([+ processRun($, argv, { timeoutMs: 10000, env }).catch(() => null),+ family ? processRun($, [typst, 'fonts', '--variants'], { timeoutMs: 10000, env }).catch(() => null) : null,+ ])try {const m = JSON.parse(got?.stdout ?? '') as Metricsconst ok = (x: FontMetrics | null | undefined) => !!x && x.adv > 0 && x.xh > 0 && x.avg > 0const fonts = leanFontsOf(m.fonts)- 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, ...(fonts ? { fonts } : {}) }+ const bold = listed?.exitCode === 0 ? hasBoldFace(listed.stdout, family) : null+ 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, ...(fonts ? { fonts } : {}), ...(bold === null ? {} : { termBold: bold }) }+ }} catch {}return DEFAULT_METRICS}@@ -322,6 +332,7 @@ export function typstInputs(job: Job, segments: readonly string[], dir: string,...(job.grid ? { grid: 1 } : {}),code: fit.code,...(job.env.termFont ? { 'term-font': job.env.termFont } : {}),+ ...(fauxBoldOf(job.env.metrics) ? { 'term-bold': 0 } : {}),'theme-dir': job.themeDir,doc: `${dir}/doc.json`,...roomInputs(job.room),diff --git a/hooks/register.tsx b/hooks/register.tsxindex ad10dbc..f278dc9 100644--- a/hooks/register.tsx+++ b/hooks/register.tsx@@ -24,7 +24,7 @@ import {DEFAULT_THEME, gridText, heightText, IMAGE_MAX_COLUMNS, MARGIN_TOP, MAX_HEIGHT, MAX_WIDTH, MIN_HEIGHT, MIN_WIDTH, RESULTS_KEPT, TYPST_PROMPT,SELECT_SINCE, selectText, typstHintOf, widthText,} from './lib/settings'-import { clip, drawnAnswers, editedPlans, keep, queue, refresh, running, S, subagentPlans, writesLive, type Env, type Job } from './lib/state'+import { clip, DEFAULT_METRICS, drawnAnswers, editedPlans, keep, queue, refresh, running, S, subagentPlans, writesLive, type Env, type Job } from './lib/state'import { beginEpoch } from './lib/epoch'import { escapeControls, luminanceOf, modeLine, modeOfLuminance, parseOsc11, settingOf } from './lib/mode'import { applyTheme, themeListing, userThemesOf } from './lib/themes'@@ -80,7 +80,7 @@ export {} from './lib/themes'export { commandSuggestions, parseCommand, type Command, type Suggestion } from './lib/command'export { hasSetup, SETUP_END, SETUP_NOT_MAC, SETUP_START, setupBlock, shellRcOf, withoutSetup, withSetup, type ShellRc } from './lib/setup'-export { OSC11_PL, perlFor, WATCH_PL } from './lib/host'+export { fcPatternOf, OSC11_PL, perlFor, PROGRAM_FONTS_PL, PROGRAM_FONTS_SH, WATCH_PL } from './lib/host'export {convertCall, isSafePage, measureCall, noNetworkEnv, pageRowsOf, parseOd, pngSize, probeCall, resultOf, roomInputs, shouldRetrySafe, typstCall, typstInputs,} from './lib/typst'@@ -736,7 +736,11 @@ export const register: Register = on => {const bad = asked.kind === 'bad' ? `Not understood: "${e.args.trim()}".\n` : ''const theme = S.look?.name ?? DEFAULT_THEMEif (asked.kind === 'details') {- const font = ready.termFont ? `terminal font ${ready.termFont}` : `terminal font not known (${ready.isMac ? 'Menlo' : "the theme's code font"} assumed)`+ // A measure with no term metrics: Typst does not have the font (it would fall back).+ const missing = !!ready.typst && ready.metrics !== DEFAULT_METRICS && !ready.metrics.term+ const font = !ready.termFont+ ? `terminal font not known (${ready.isMac ? 'Menlo' : "the theme's code font"} assumed)`+ : `terminal font ${ready.termFont}${missing ? " (Typst does not have this font, so the pictures use the theme's fonts)" : ''}`const typst = ready.typst ? `Typst: ${ready.typst}` : `Typst: not found (${typstHintOf(ready.isMac)})`const terminal = S.cacheProblem? `Intelligent UI draws no pictures: ${S.cacheProblem} (it never uses a shared folder instead)`@@ -989,9 +993,10 @@ export const register: Register = on => {const row = await next(e)if (e.surface !== 'terminal' || e.props.isErrored || e.props.isInterrupted || subagentPlans.has(e.props.tool_use_id)) return rowtry {- const plan = planShownOf(editedPlans.get(e.props.tool_use_id), e.props.output, e.props.input)- const ready = plan ? await answerEnv($, e) : null- if (!ready) return row+ // `done` first: a plan set (and refreshed) after this read draws the row again.+ const ready = await answerEnv($, e)+ const plan = ready ? planShownOf(editedPlans.get(e.props.tool_use_id), e.props.output, e.props.input) : ''+ if (!ready || !plan) return rowconst { drawing, links } = await planDrawing($, e, e.props.tool_use_id, plan, ready)// Its pages can be copied as an answer's, by the call's id (the row's// requestId can be an answer's own). The engine's row is above them:@@ -1078,10 +1083,9 @@ export const register: Register = on => {const id = e.tool_use_idconst file = planFileOf(e)const plan = await currentPlan($, file, callPlan)- if (plan !== callPlan) {- editedPlans.set(id, plan)- refresh($)- }+ // Always: the row's input is the message's copy, read before an Edit in the same message.+ editedPlans.set(id, plan)+ refresh($)const outcome = await decidePlan($, {plan, callPlan, file, isMac: ready.isMac, isRemote: S.isRemote,onEdited: text => {diff --git a/render/md.typ b/render/md.typindex 30bab3a..7c98dbe 100644--- a/render/md.typ+++ b/render/md.typ@@ -15,6 +15,7 @@// 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)+// term-bold=0 the terminal font has no bold face: a fake bold (optional)// height=<pt> the room height of one drawing now (default 0 =// unknown: no height limit and no height factor)// design-w=<pt> the design page width: the `width` at the first@@ -166,6 +167,33 @@#set par(leading: E.text.leading-em * 1em, spacing: E.text.paragraph-em * 1em, justify: false)#set block(spacing: E.text.paragraph-em * 1em)+// ---------- a fake bold for a terminal font with no bold face ----------+// term-bold=0: Typst has no bold face of the terminal font (Monaco, for+// one), so its bold text would draw regular. As a terminal does, bold+// text in that font gets a stroke of its own fill (0.04em: as thick as+// Menlo's and DejaVu Sans Mono's bold). Text in other fonts stays.+#let faux-bold = term-font != "" and inp.at("term-bold", default: "1") == "0"+#let faux-stroke = 0.04em+#let weight-num = (thin: 100, extralight: 200, light: 300, regular: 400, medium: 500, semibold: 600, bold: 700, extrabold: 800, black: 900)+#let weight-of(w) = if type(w) == int { w } else { weight-num.at(w, default: 400) }+// The first font of the current list, lower case (needs context).+#let first-font() = {+ let f = text.font+ let x = if type(f) == array { f.at(0, default: "") } else { f }+ lower(if type(x) == dictionary { x.name } else { x })+}+#show: doc => if not faux-bold { doc } else {+ let term = lower(term-font)+ // strong adds its delta when it is shaped; as a weight, the text rule sees it.+ show strong: it => context if first-font() != term { it } else {+ text(weight: calc.min(weight-of(text.weight) + it.delta, 900), it.body)+ }+ show text: it => context if weight-of(text.weight) < 600 or first-font() != term { it } else {+ text(stroke: faux-stroke + text.fill, it)+ }+ doc+}+// ---------- 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.diff --git a/tests/bold-sh-test.sh b/tests/bold-sh-test.shnew file mode 100644index 0000000..c315fc4--- /dev/null+++ b/tests/bold-sh-test.sh@@ -0,0 +1,49 @@+#!/bin/sh+# Renders render/md.typ with the real Typst in a terminal font that has no+# bold face (Monaco), with and without term-bold=0 (the fake bold): the+# flag changes a page with bold text, and does not change a page with no+# bold text or a page with no terminal font. It keeps the PNGs in+# $IUI_BOLD_OUT when that is set, to look at.+# Usage: sh tests/bold-sh-test.sh (exit 0 when all pass; skips with no+# typst or no Monaco)+set -u+here=$(cd "$(dirname "$0")/.." && pwd)+tmp=$(mktemp -d "${TMPDIR:-/tmp}/iui-bold-test.XXXXXX")+trap 'rm -rf "$tmp"' EXIT+pass=0+fail=0+ok() { pass=$((pass + 1)); }+bad() { fail=$((fail + 1)); echo "FAIL: $*"; }++command -v typst >/dev/null 2>&1 || { echo "bold-sh-test: skipped (no typst)"; exit 0; }+typst fonts | grep -qx Monaco || { echo "bold-sh-test: skipped (Typst has no Monaco)"; exit 0; }+# Monaco has no bold face, so the hooks give the theme term-bold=0.+typst fonts --variants | sed -n '/^Monaco$/,/^[^ ]/p' | grep -q 'Weight: [6-9]00' && bad "Monaco has a bold face here"++# A doc JSON of one page of Markdown (argument 1) at $tmp/<name>.json.+doc() { perl -e 'local $/; my $m = <STDIN>; $m =~ s/(["\\])/\\$1/g; $m =~ s/\n/\\n/g; print "{\"base\": \"\", \"segments\": [\"$m\"]}"' > "$tmp/$1.json"; }+# Renders doc $1 in theme $2 (a warning for a font that is not installed is not a fail) with term-font $3 and the flag $4 (0 or 1) to $tmp/$1-$2-$4.png.+render() {+ typst compile "$here/render/md.typ" "$tmp/$1-$2-$4.png" --root / --ppi 144 --input theme=dark --input width=420 \+ --input "term-font=$3" --input "term-bold=$4" --input "theme-dir=$here/render/themes/$2" --input "doc=$tmp/$1.json" 2> "$tmp/err" \+ && ! grep -q '^error' "$tmp/err" && ok || bad "$1 in $2 ($3, term-bold=$4): $(head -3 "$tmp/err")"+}+same() { cmp -s "$tmp/$1-$2-0.png" "$tmp/$1-$2-1.png"; }++printf '## A heading\n\nText with **bold words**, a [**bold link**](https://x.y), *italic* and `code`.\n\n| Name | **Value** |\n|---|---|\n| a | **b** |\n' | doc bold+printf 'Text with *italic*, a [link](https://x.y) and `code`.\n\n```ts\nconst x = 1 // code\n```\n' | doc plain+for theme in claude-code vscode; do+ for b in 0 1; do render bold $theme Monaco $b; render plain $theme Monaco $b; done+ same bold $theme && bad "$theme: the fake bold does not change bold text" || ok+ same plain $theme && ok || bad "$theme: the fake bold changes a page with no bold text"+done+# With no terminal font, the flag does nothing.+for b in 0 1; do+ typst compile "$here/render/md.typ" "$tmp/bold-none-$b.png" --root / --ppi 144 --input theme=dark --input width=420 \+ --input "term-bold=$b" --input "theme-dir=$here/render/themes/claude-code" --input "doc=$tmp/bold.json" 2>/dev/null && ok || bad "no terminal font, term-bold=$b: no page"+done+same bold none && ok || bad "with no terminal font the flag changes the page"++[ -n "${IUI_BOLD_OUT:-}" ] && mkdir -p "$IUI_BOLD_OUT" && cp "$tmp"/*.png "$IUI_BOLD_OUT"/+echo "bold-sh-test: $pass passed, $fail failed"+[ "$fail" = 0 ]diff --git a/tests/copy.test.ts b/tests/copy.test.tsindex 6158593..553240e 100644--- a/tests/copy.test.ts+++ b/tests/copy.test.ts@@ -1624,29 +1624,29 @@ test('picture select: /iui select off and /iui off let the page cache go', async})test('picture select: a frame of a page file the row no longer draws is not blitted; the new file gets its own frame', async ($, on) => {- let redraw: (() => Promise<void>) | null = null+ let release = () => {}+ let isHeld = falseconst w = world(on, {tty: TTY,- // The row is drawn again with a new page file while the first frame is written.- beforeWrite: async () => {- const r = redraw- redraw = null- await r?.()- },+ // The first frame write is held; the test draws the row again meanwhile (one clock mover at a time).+ beforeWrite: () => (isHeld ? Promise.resolve() : ((isHeld = true), new Promise<void>(r => (release = r)))),})await $.command.run({ command: 'iui', args: '' } as any)const ui = await drawAnswer($, w)const other = `${SMALL_MD}\n\nOne more line.`- redraw = async () => {- await ui.redraw(props(other))- await w.clock.settle()- await w.clock.advance(1000)- await w.clock.settle()- await ui.redraw(props(other))- await w.clock.settle()- }await drag(ui)await settle(w)+ expect(w.writes).toBe(1)+ expect(w.frames).toEqual([])+ // The row is drawn again with a new page file while the first frame is written.+ await ui.redraw(props(other))+ await w.clock.settle()+ await w.clock.advance(1000)+ await w.clock.settle()+ await ui.redraw(props(other))+ await w.clock.settle()+ release()+ await settle(w)expect(w.compiles.length).toBe(2)const stale = w.frames[0]!.pathexpect(w.blits.some(b => b.source.file === stale)).toBe(false)diff --git a/tests/draw.test.ts b/tests/draw.test.tsindex e5cd95f..fc08f25 100644--- a/tests/draw.test.ts+++ b/tests/draw.test.ts@@ -66,6 +66,15 @@ test('pages cut for ssh have keys of their own; local keys do not change', () =>expect(renderKey({ ...o, inline: true })).not.toBe(renderKey(o))})+test('a fake bold has keys of its own; the other keys do not change', () => {+ const o = {+ textHash: 'h', columns: 100, cell: DEFAULT_CELL, size: 100, mode: 'dark' as const, termFont: 'Monaco', columnPt: 6,+ templateStamp: '1', look: { name: 'vscode', dir: '/t', stamp: '0' },+ }+ expect(renderKey({ ...o, fauxBold: false })).toBe(renderKey(o))+ expect(renderKey({ ...o, fauxBold: true })).not.toBe(renderKey(o))+})+// ---- The Image source -------------------------------------------------------const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: exitCode ? 'error: boom' : '', isStdoutTruncated: false, isStderrTruncated: false } })diff --git a/tests/fonts-sh-test.sh b/tests/fonts-sh-test.shnew file mode 100644index 0000000..2e9f694--- /dev/null+++ b/tests/fonts-sh-test.sh@@ -0,0 +1,94 @@+#!/bin/sh+# Runs the copy of a font out of a terminal's program (PROGRAM_FONTS_SH and+# PROGRAM_FONTS_PL in hooks/lib/host.ts) with the real perl, in sh, dash and+# bash: on a fake program that holds small sfnt fonts (with `fvar` and+# `name` tables), it checks the folder and its files, a second run from+# the cache, the `.none` marker, the sweep of old folders, two runs at the+# same time, and no program.+# Usage: sh tests/fonts-sh-test.sh (exit 0 when all pass)+set -u+here=$(cd "$(dirname "$0")/.." && pwd)+tmp=$(mktemp -d "${TMPDIR:-/tmp}/iui-fonts-test.XXXXXX")+trap 'chmod -R u+rwx "$tmp" 2>/dev/null; rm -rf "$tmp"' EXIT+pass=0+fail=0+ok() { pass=$((pass + 1)); }+bad() { fail=$((fail + 1)); echo "FAIL: $*"; }++# The TypeScript arrays as text: each '...' line, the escapes undone.+part() {+ perl -e 'local $/; $_ = <STDIN>; /export const $ARGV[0] = \[\n(.*?)\n\]\.join/s or exit 1;+ print join("\n", map { s/^\s*\x27//; s/\x27,?\s*$//; s/\\\\/\\/g; $_ } split /\n/, $1)' "$1" < "$here/hooks/lib/host.ts"+}+pl=$(part PROGRAM_FONTS_PL) && [ -n "$pl" ] && ok || bad "PROGRAM_FONTS_PL: not found in host.ts"+sh_text=$(part PROGRAM_FONTS_SH) && [ -n "$sh_text" ] && ok || bad "PROGRAM_FONTS_SH: not found in host.ts"+perl=$(command -v perl)++# A small sfnt: 4 tables (fvar, head, maxp, name); the name table holds the+# family in UTF-16BE. Argument 1: the family; 2: the filler size (so two+# fonts differ in size); 3: the file to write.+cat > "$tmp/font.pl" <<'EOF'+my ($family, $pad, $out) = @ARGV;+my %t = (fvar => "\0" x 16, head => "\0" x 54, maxp => "\0" x (6 + $pad), name => "\0\0\0\1\0\x12" . "\0" x 12 . join("", map { "\0$_" } split //, $family));+my @tags = sort keys %t; my $off = 12 + 16 * @tags; my ($dir, $data) = ("", "");+for my $tag (@tags) { my $d = $t{$tag}; $d .= "\0" x ((4 - length($d) % 4) % 4); $dir .= pack("a4NNN", $tag, 0, $off + length($data), length($t{$tag})); $data .= $d; }+open(my $o, ">:raw", $out) or die; print $o pack("Nnnnn", 0x00010000, scalar(@tags), 64, 2, 0) . $dir . $data; close $o;+EOF+"$perl" "$tmp/font.pl" "Test Mono" 0 "$tmp/regular.ttf"+"$perl" "$tmp/font.pl" "Test Mono" 8 "$tmp/italic.ttf"+"$perl" "$tmp/font.pl" "Other Font" 4 "$tmp/other.ttf"+# A program: filler, the fonts (the regular one twice, as in a universal+# program), and another family's font.+program() {+ { head -c 3000 /dev/urandom; cat "$tmp/regular.ttf"; head -c 500 /dev/urandom; cat "$tmp/italic.ttf" "$tmp/other.ttf"; head -c 700 /dev/urandom; cat "$tmp/regular.ttf"; } > "$1"+ chmod 755 "$1"+}+same() { cmp -s "$1" "$2"; }++shells=+for s in sh dash bash; do command -v "$s" >/dev/null 2>&1 && shells="$shells $s"; done+for s in $shells; do+ [ "$s" = bash ] && s='bash --posix'+ k=$(echo "$s" | tr -d ' -')+ xdg=$tmp/xdg-$k; base=$xdg/cc-intelligent-ui/fonts; bin=$tmp/bin-$k+ mkdir -p "$bin"; program "$bin/term"+ run() { XDG_CACHE_HOME=$xdg PATH=$bin:/usr/bin:/bin $s -c "$sh_text" sh "$perl" "$pl" "$@"; }+ # Old folders of the tag: a temporary one of 2 days and a key folder of+ # 8 days go; a key folder of today and another tag's old folder stay.+ mkdir -p "$base/test-old" "$base/test-1-2-3.999" "$base/test-new" "$base/other-old"+ touch -t 202001010000 "$base/test-old" "$base/test-1-2-3.999" "$base/other-old"+ # The first run: the folder, one file for each size of the family.+ out=$(run test "Test Mono" term /nowhere); code=$?+ dir=$(echo "$out" | sed -n 1p)+ [ "$code" = 0 ] && case $dir in "$base"/test-*) true ;; *) false ;; esac && ok || bad "$s: exit $code, folder '$dir'"+ [ "$(ls "$dir" | tr '\n' ' ')" = "test-1.ttf test-2.ttf " ] && ok || bad "$s: the files are $(ls "$dir" | tr '\n' ' ')"+ same "$dir/test-1.ttf" "$tmp/regular.ttf" && same "$dir/test-2.ttf" "$tmp/italic.ttf" && ok || bad "$s: a copied font is not the same"+ [ ! -e "$base/test-old" ] && [ ! -e "$base/test-1-2-3.999" ] && [ -d "$base/test-new" ] && [ -d "$base/other-old" ] && ok || bad "$s: the sweep is wrong ($(ls "$base" | tr '\n' ' '))"+ # The second run reads the cache, not the program.+ chmod 000 "$bin/term"+ out=$(run test "Test Mono" term "$bin/term"); code=$?+ [ "$code" = 0 ] && [ "$out" = "$dir" ] && ok || bad "$s: the second run gave exit $code, '$out'"+ chmod 755 "$bin/term"+ # A family the program does not have: exit 3 and a marker, then exit 3+ # from the marker (the program is not read again).+ out=$(run none "Missing Font" term); code=$?+ [ "$code" = 3 ] && [ -z "$out" ] && ls "$base"/none-*.none >/dev/null 2>&1 && ok || bad "$s: no font gave exit $code, '$out', no marker"+ ls -d "$base"/none-* 2>/dev/null | grep -qv '\.none$' && bad "$s: a folder for no font" || ok+ chmod 000 "$bin/term"+ run none "Missing Font" term "$bin/term" >/dev/null; code=$?+ [ "$code" = 3 ] && ok || bad "$s: the marker was not used (exit $code)"+ chmod 755 "$bin/term"+ # Two runs at the same time (a new build: a new key): one folder, no temporary folder left.+ program "$bin/term2"+ run two "Test Mono" term2 > "$tmp/a-$k" & a=$!+ run two "Test Mono" term2 > "$tmp/b-$k" & b=$!+ wait $a; ca=$?; wait $b; cb=$?+ [ "$ca" = 0 ] && [ "$cb" = 0 ] && [ "$(cat "$tmp/a-$k")" = "$(cat "$tmp/b-$k")" ] && ok || bad "$s: two runs gave $ca/$cb, '$(cat "$tmp/a-$k")' and '$(cat "$tmp/b-$k")'"+ [ "$(ls -d "$base"/two-* | wc -l | tr -d ' ')" = 1 ] && [ "$(ls "$(cat "$tmp/a-$k")" | wc -l | tr -d ' ')" = 2 ] && ok || bad "$s: two runs left $(ls -d "$base"/two-* | tr '\n' ' ')"+ # No program: exit 2.+ run test "Test Mono" nothing-here /nowhere/term > /dev/null; code=$?+ [ "$code" = 2 ] && ok || bad "$s: no program gave exit $code"+done++echo "fonts-sh-test: $pass passed, $fail failed (shells:$shells)"+[ "$fail" = 0 ]diff --git a/tests/fonts.test.ts b/tests/fonts.test.tsindex 1a18a0d..443c58d 100644--- a/tests/fonts.test.ts+++ b/tests/fonts.test.ts@@ -1,8 +1,8 @@import { expect, test } from 'claude-code/testing'-import { fontListOf, isPlain, LEAN_SH, leanDirOf, leanFiles, leanFontsFor } from '../hooks/lib/fonts'-import { compile, forgetTouches, leanFontsOf, probeCall, typstCall } from '../hooks/lib/typst'-import { DEFAULT_METRICS, leanDirs, type Env, type Job, type LeanFonts } from '../hooks/lib/state'+import { fontListOf, hasBoldFace, isPlain, LEAN_SH, leanDirOf, leanFiles, leanFontsFor } from '../hooks/lib/fonts'+import { compile, forgetTouches, leanFontsOf, measureFonts, probeCall, typstCall } from '../hooks/lib/typst'+import { DEFAULT_METRICS, fauxBoldOf, leanDirs, type Env, type Job, type LeanFonts } from '../hooks/lib/state'import { DEFAULT_CELL } from '../hooks/lib/settings'// `typst fonts --variants` as Typst 0.15 prints it.@@ -83,6 +83,60 @@ test('a variable font is read by its file, without the (Variable) mark', () => {expect(leanFiles(both, 'JetBrains Mono', FONTS)?.slice(0, 2)).toEqual(['/c/fonts/ghostty-1/JetBrainsMono-1.ttf', '/c/fonts/ghostty-1/JetBrainsMono-2.ttf'])})+// Monaco has one face (no bold); a variable font has a range of weights.+const MONACO = ['Monaco', ' └ /System/Library/Fonts/Monaco.ttf', ' Style: Normal, Weight: 400, Stretch: 100%', ''].join('\n')+const VARIABLE = (top: number) => ['Cascadia Code NF', ' └ /c/fonts/rio-1/rio-1.ttf (Variable)', ' Style: Normal', ' Stretch: 100%', ` Weight: 200-${top} (Default: 400)`, ''].join('\n')++test('a bold face is a weight of 600 or more; null when Typst does not list the family', () => {+ expect(hasBoldFace(LISTING, 'Menlo')).toBe(true)+ expect(hasBoldFace(LISTING, 'dejavu sans mono')).toBe(true)+ expect(hasBoldFace(LISTING, 'Helvetica')).toBe(false)+ expect(hasBoldFace(LISTING + MONACO, 'Monaco')).toBe(false)+ expect(hasBoldFace(VARIABLE(700), 'Cascadia Code NF')).toBe(true)+ expect(hasBoldFace(VARIABLE(500), 'Cascadia Code NF')).toBe(false)+ expect(hasBoldFace(LISTING, 'Monaco')).toBe(null)+ expect(hasBoldFace('', 'Menlo')).toBe(null)+})++const METRICS = JSON.stringify({ term: { adv: 0.6, xh: 0.55, avg: 0.6 }, menlo: { adv: 0.6, xh: 0.55, avg: 0.6 }, body: { adv: 0.6, xh: 0.52, avg: 0.48 } })+// The measure and the font list in the same time, with the same font paths.+const measured = async (family: string, listing: string | null) => {+ const ran: { argv: string[]; env?: Record<string, string> }[] = []+ const run = (stdout: string, exitCode = 0) => ({ exitCode, stdout, stderr: '' })+ const $ = {+ process: {+ run: async (argv: string[], init?: { env?: Record<string, string> }) => {+ ran.push({ argv, env: init?.env })+ if (argv[1] === 'eval') return run(METRICS)+ if (argv[1] === 'fonts') return listing === null ? run('', 1) : run(listing)+ return run('', 1)+ },+ },+ }+ return { m: await measureFonts($ as any, '/usr/bin/typst', '/r', '/c', family, '/t'), ran }+}++test('the measure keeps whether the terminal font has a bold face; a fake bold only when it has none', async () => {+ const monaco = await measured('Monaco', LISTING + MONACO)+ expect(monaco.m.termBold).toBe(false)+ expect(fauxBoldOf(monaco.m)).toBe(true)+ // The list sees the same fonts as the measure (the same font paths).+ const [measure, list] = [monaco.ran.find(r => r.argv[1] === 'eval')!, monaco.ran.find(r => r.argv[1] === 'fonts')!]+ expect(list.argv).toEqual(['/usr/bin/typst', 'fonts', '--variants'])+ expect(list.env).toEqual(measure.env)+ expect((await measured('Menlo', LISTING)).m.termBold).toBe(true)+ // Not listed, or the list fails: not known, so no fake bold.+ for (const listing of [LISTING, null]) {+ const m = (await measured('Monaco', listing)).m+ expect('termBold' in m).toBe(false)+ expect(fauxBoldOf(m)).toBe(false)+ }+ // No terminal font: no list.+ expect((await measured('', LISTING)).ran.some(r => r.argv[1] === 'fonts')).toBe(false)+ // Typst does not have the font (no term metrics): no fake bold.+ expect(fauxBoldOf({ ...DEFAULT_METRICS, term: null, termBold: false })).toBe(false)+})+test('the lean set has the terminal font and the Latin fonts, not the CJK and emoji fonts', () => {expect(leanFiles(fontListOf(LISTING), 'MesloLGS NF', FONTS)).toEqual(['/Users/me/Library/Fonts/MesloLGS NF Regular.ttf',diff --git a/tests/plan.test.ts b/tests/plan.test.tsindex 099e1da..19b2349 100644--- a/tests/plan.test.ts+++ b/tests/plan.test.ts@@ -37,8 +37,14 @@ test('the plan of an ExitPlanMode result: a non-empty one of the main loop only'expect(planOf(undefined)).toBe(null)})-test('the plan a row shows: the edited text, else the result, else the call', () => {- expect(planShownOf('# Edited', { plan: '# Done', isAgent: false }, { plan: '# Asked' })).toBe('# Edited')+test('the plan a row shows: the result, else the edited text, else the call', () => {+ // The result is the approved text: an edit in the engine's dialog wins over the text read at the call.+ expect(planShownOf('# Edited', { plan: '# Done', isAgent: false }, { plan: '# Asked' })).toBe('# Done')+ expect(planShownOf('# Edited', undefined, { plan: '# Asked' })).toBe('# Edited')+ expect(planShownOf('# Edited', { plan: '', isAgent: false }, { plan: '# Asked' })).toBe('# Edited')+ // A subagent's or a teammate's plan: never drawn, also with a text kept for its call.+ expect(planShownOf('# Edited', { plan: '# Done', isAgent: true }, { plan: '# Asked' })).toBe('')+ expect(planShownOf('# Edited', { plan: '# Done', isAgent: false, awaitingLeaderApproval: true }, { plan: '# Asked' })).toBe('')expect(planShownOf(undefined, { plan: '# Done', isAgent: false }, { plan: '# Asked' })).toBe('# Done')expect(planShownOf(undefined, undefined, { plan: '# Asked' })).toBe('# Asked')expect(planShownOf(undefined, { plan: '# Done', isAgent: true }, { plan: '# Asked' })).toBe('')@@ -430,6 +436,42 @@ test('a plan written in the same message waits for the write, then the new textexpect(w.compiled).toEqual([EDITED])})+test("an Edit in the same message: the row draws the file, not the message's older copy", async ($, on) => {+ const w = world($, on, { answers: [PLAN_AUTO] })+ await ready($)+ // The Edit has run; the engine reads the file again for the call, but the row keeps the streamed input.+ w.files.set(FILE, EDITED)+ const got: any = await exitPlan($, { plan: EDITED })+ expect(w.decisions).toMatchObject([{ behavior: 'allow', updatedInput: { plan: EDITED } }])+ expect(got.result.plan).toBe(EDITED)+ await $.ui.mount(use({ input: { plan: PLAN, planFilePath: FILE } }))+ await w.clock.settle()+ expect(w.compiled).toEqual([EDITED])+})++test("a teammate's or a subagent's result draws no plan, also after a call kept its text", async ($, on) => {+ const w = world($, on, { answers: [PLAN_AUTO, PLAN_AUTO] })+ await ready($)+ await exitPlan($, { tool_use_id: 'tu-a' })+ await exitPlan($, { tool_use_id: 'tu-b' })+ const rows = [+ use({ id: 'tu-a', output: { plan: PLAN, isAgent: false, awaitingLeaderApproval: true }, isRunning: false }),+ use({ id: 'tu-b', output: { plan: PLAN, isAgent: true }, isRunning: false }),+ ]+ for (const row of rows) expect(await (await $.ui.mount(row)).drawn()).toMatchObject(ENGINE)+ await w.clock.settle()+ expect(w.compiled).toEqual([])+})++test("the result's plan wins over the text read at the call (an edit in the engine's dialog)", async ($, on) => {+ const w = world($, on, { answers: [PLAN_AUTO] })+ await ready($)+ await exitPlan($)+ await $.ui.mount(use({ output: { plan: EDITED, isAgent: false, filePath: FILE }, isRunning: false }))+ await w.clock.settle()+ expect(w.compiled).toEqual([EDITED])+})+test('the plan waits at most 5 s for a write that does not end', async ($, on) => {const w = world($, on, { answers: [PLAN_AUTO] })on('tool.call', { tool: 'Write' }, async () => new Promise(() => undefined))diff --git a/tests/pure.test.ts b/tests/pure.test.tsindex 698282e..a3d82c8 100644--- a/tests/pure.test.ts+++ b/tests/pure.test.ts@@ -1,7 +1,7 @@import { expect, test } from 'claude-code/testing'import {- alignFirstLine, DEFAULT_METRICS, DEFAULT_SIZE, firstLineOf, fontFit, ghosttyFontOf, itermFontOf, parseFontSpec, typstCall,+ alignFirstLine, cmuxConfigOf, DEFAULT_METRICS, DEFAULT_SIZE, firstLineOf, fontFit, ghosttyFontOf, ghosttyFontsOf, itermFontOf, parseFontSpec, typstCall,blocksOf, canDrawIn, columnsFor, DEFAULT_CELL, hashOf, imagePathOf, isSet, localImages, DEFAULT_WIDTH, IMAGE_MAX_COLUMNS,parseOd, plainOf, pngSize, shouldRetrySafe, sizeOf, sizing, splitSegments, themeOf, TYPST_PROMPT,escapeControls, luminanceOf, modeOfLuminance, OSC11_PL, parseOsc11, pickProfile, itermAppearanceOf, itermModeOf,@@ -360,6 +360,16 @@ test('with the grid on, the template gets grid=1 and top=0; with it off, no gridexpect(on.ppi).toBe(off.ppi)})+test('a terminal font with no bold face gives the template term-bold=0; any other font no input', () => {+ const term = { adv: 0.6, xh: 0.55, avg: 0.6 }+ const inputsOf = (metrics: Env['metrics']) =>+ typstInputs({ key: 'k', requestId: 'r', text: 'x', columns: 100, cell: DEFAULT_CELL, theme: 'dark', size: 100, grid: false, themeDir: '/t', env: { metrics, termFont: 'Monaco' } as Env, epoch: 0 } as Job, ['x'], '/c/k', false).inputs+ expect(inputsOf({ ...DEFAULT_METRICS, term, termBold: false })['term-bold']).toBe(0)+ expect('term-bold' in inputsOf({ ...DEFAULT_METRICS, term, termBold: true })).toBe(false)+ expect('term-bold' in inputsOf({ ...DEFAULT_METRICS, term })).toBe(false)+ expect('term-bold' in inputsOf({ ...DEFAULT_METRICS, term: null, termBold: false })).toBe(false)+})+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).@@ -425,6 +435,9 @@ test('the terminal font is read from iTerm2 and Ghostty settings', () => {expect(parseFontSpec('MesloLGS-NF-Regular 14')).toEqual({ name: 'MesloLGS-NF-Regular', size: 14 })expect(parseFontSpec('Menlo-Regular 12.5')).toEqual({ name: 'Menlo-Regular', size: 12.5 })expect(parseFontSpec('nosize')).toBe(null)+ // iTerm2 saves the font's settings after the size; it reads the name to the first space.+ expect(parseFontSpec('JetBrainsMono-Regular 13 {"featureSettings":[{"CTFeatureTypeIdentifier":35}]}')).toEqual({ name: 'JetBrainsMono-Regular', size: 13 })+ expect(parseFontSpec('Monaco 12')).toEqual({ name: 'Monaco', size: 12 })const marks = JSON.stringify([{ Name: 'Default', Guid: 'G1', 'Normal Font': 'MesloLGS-NF-Regular 14' },{ Name: 'Work', Guid: 'G2', 'Normal Font': 'Menlo-Regular 12' },@@ -433,8 +446,17 @@ test('the terminal font is read from iTerm2 and Ghostty settings', () => {expect(itermFontOf(marks, undefined, 'G1\n')).toBe('MesloLGS-NF-Regular 14')expect(itermFontOf(marks, 'Gone', 'G1')).toBe('MesloLGS-NF-Regular 14')expect(itermFontOf('not json', 'Work', 'G1')).toBe(null)+ // No profile: null (not known); a profile with no font: '' (iTerm2 draws its default).+ expect(itermFontOf(marks, 'Gone', 'G9')).toBe(null)+ expect(itermFontOf(JSON.stringify([{ Name: 'Default', Guid: 'G1' }]), undefined, 'G1')).toBe('')+ expect(ghosttyFontsOf('font-family = Nope\nfont-family = "Iosevka"\nfont-size = 13')).toEqual(['Nope', 'Iosevka'])+ expect(ghosttyFontsOf('font-family = Nope\nfont-family = \nfont-family = Menlo')).toEqual(['Menlo'])expect(ghosttyFontOf('theme = x\nfont-family = \nfont-family = "JetBrains Mono"\nfont-family = Menlo')).toBe('JetBrains Mono')expect(ghosttyFontOf('font-size = 13')).toBe(null)+ // An empty value clears the list; cmux's own config comes after +show-config.+ expect(ghosttyFontOf('font-family = Menlo\nfont-family = \nfont-family = Iosevka\nfont-family = Menlo')).toBe('Iosevka')+ expect(ghosttyFontOf(cmuxConfigOf('font-size = 13\n', 'font-family = "Fira Code"\n'))).toBe('Fira Code')+ expect(ghosttyFontOf(cmuxConfigOf('font-family = Menlo\n', 'font-family = "Fira Code"\n'))).toBe('Menlo')})test('typst also reads the font folder of the font that Ghostty carries, when there is one', () => {@@ -1050,7 +1072,11 @@ test('typst gets no network in either case of the proxy variables, and its packaexpect('TYPST_FONT_PATHS' in env).toBe(false)S.fontPaths = '/f1:/f2'expect(noNetworkEnv('/c').TYPST_FONT_PATHS).toBe('/f1:/f2')+ // The user's own TYPST_FONT_PATHS stays, first.+ S.userFontPaths = '/u/fonts'+ expect(noNetworkEnv('/c').TYPST_FONT_PATHS).toBe('/u/fonts:/f1:/f2')} finally {S.fontPaths = saved+ S.userFontPaths = ''}})diff --git a/tests/termfont.test.ts b/tests/termfont.test.tsnew file mode 100644index 0000000..47a61a6--- /dev/null+++ b/tests/termfont.test.ts@@ -0,0 +1,273 @@+import { expect, mock, test } from 'claude-code/testing'++import { fcPatternOf, KITTY_MAC_FONT, PROGRAM_FONTS_PL, PROGRAM_FONTS_SH, RIO_DEFAULT_FONT, RIO_OLD_FONT } from '../hooks/register'+import { S } from '../hooks/lib/state'++// The terminal font that the pictures use: the one the terminal draws. A+// font that a terminal carries in its program is copied out for Typst; a+// font that it does not find is the one it draws in its place.++const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: exitCode ? 'error' : '', isStdoutTruncated: false, isStderrTruncated: false } })+const FONTS_DIR = '/h/.cache/cc-intelligent-ui/fonts/rio-1'+// render/measure.typ's answer when Typst does not have the terminal font.+const NO_TERM = JSON.stringify({ term: null, menlo: { adv: 0.6, xh: 0.55, avg: 0.6 }, body: { adv: 0.6, xh: 0.52, avg: 0.48 } })+// fontconfig's loose match: no case, no spaces.+const loose = (s: string) => s.replace(/\\(.)/g, '$1').replace(/\s/g, '').toLowerCase()+// The argument after the one that holds `marker` (a script's first argument).+const argAfter = (argv: string[], marker: string) => argv[argv.findIndex(a => a.includes(marker)) + 1] ?? ''++type World = { ran: string[][]; fontPaths: string[]; copies: () => string[][] }+// A Mac or Linux with Typst. `run` answers a command first (undefined: the+// world's answer); `families` are the installed ones (CoreText or+// fontconfig), `proportional` those of them with no fixed-pitch style,+// `names` the families of full or PostScript names; `nearest` is+// fontconfig's nearest font; `files` are under /h; `copied` is the folder+// of a copy out of a program, 'none' when the program has no such font+// (unset: no program).+function world(on: any, o: {+ isMac: boolean+ env: Record<string, string>+ families?: string[]+ proportional?: string[]+ names?: Record<string, string>+ nearest?: string+ files?: Record<string, string>+ copied?: string+ measure?: string+ run?: (argv: string[]) => ReturnType<typeof ok> | undefined+}): World {+ S.fontPaths = ''+ mock.store(on)+ mock.clock(on)+ mock.env(on, { HOME: '/h', ...o.env })+ const ran: string[][] = []+ const fontPaths: string[] = []+ const families = o.families ?? []+ const nearest = o.nearest ?? 'DejaVu Sans Mono'+ on('process.run', async ($: any, e: any) => {+ const argv: string[] = e.argv+ const cmd = argv.join(' ')+ ran.push(argv)+ const own = o.run?.(argv)+ if (own) return own+ if (/cc-intelligent-ui-/.test(cmd)) return ok(`/c\n${o.isMac ? 'Darwin' : 'Linux'}\n/h/.cache/cc-intelligent-ui/designs\n`)+ if (cmd.includes('command -v typst')) return ok('/usr/bin/typst\n')+ if (argv[0] === '/usr/bin/typst' && argv[1] === 'eval') {+ // The fonts Typst gets besides the system's.+ fontPaths.push(e.init?.env?.TYPST_FONT_PATHS ?? '')+ return ok(o.measure ?? '{}')+ }+ if (argv.includes(PROGRAM_FONTS_SH)) return o.copied === 'none' ? ok('', 3) : o.copied ? ok(`${o.copied}\n`) : ok('', 2)+ if (argv[0] === 'osascript' && cmd.includes('availableMembersOfFontFamily')) {+ const family = argAfter(argv, 'availableMembersOfFontFamily')+ if (!families.some(f => f.toLowerCase() === family.toLowerCase())) return ok('no\n')+ return ok(argv.includes('mono') && o.proportional?.includes(family) ? 'proportional\n' : 'yes\n')+ }+ if (argv[0] === 'osascript' && cmd.includes('fontWithNameSize')) return ok(`${o.names?.[argAfter(argv, 'fontWithNameSize')] ?? ''}\n`)+ if (argv[0] === 'fc-list' && argv[1] === ':') return ok(families.map(f => fcPatternOf(f)).join('\n'))+ if (argv[0] === 'fc-list' && argv.at(-1) === 'family') return ok(o.names?.[argv[1]!.replace(/^:\w+=/, '').replace(/\\(.)/g, '$1')] ?? '')+ if (argv[0] === 'fc-list' && argv[1] === '-q') return ok('', families.some(f => loose(f) === loose(argv[2]!)) ? 0 : 1)+ if (argv[0] === 'fc-match' && argv[1] === 'monospace') return ok('DejaVu Sans Mono')+ if (argv[0] === 'fc-match') {+ const asked = argv[1]!.replace(/:spacing=mono$/, '')+ return ok(families.find(f => loose(f) === loose(asked)) ?? nearest)+ }+ return ok('', 1)+ })+ const files = o.files ?? {}+ on('fs.read', async ($: any, e: any, next: any) => (e.path in files ? { value: files[e.path] } : e.path.startsWith('/h/') || e.path.startsWith('/c/') ? { deny: 'ENOENT' } : next(e)))+ on('fs.exists', async ($: any, e: any, next: any) => (e.path.startsWith('/h/') ? { value: e.path in files } : e.path === '/usr/bin/typst' ? { value: true } : next(e)))+ return { ran, fontPaths, copies: () => ran.filter(argv => argv.includes(PROGRAM_FONTS_SH)) }+}+const details = async ($: any) => (await $.command.run({ command: 'iui', args: 'details' } as any)).text as string+// A test that leaves S.fontPaths empty after it (pure.test.ts expects it so).+const fontTest = (name: string, fn: ($: any, on: any) => Promise<void>) =>+ test(name, async ($, on) => {+ try {+ await fn($, on)+ } finally {+ S.fontPaths = ''+ }+ })++// ---- Rio ----------------------------------------------------------------------++for (const isMac of [true, false]) {+ const os = isMac ? 'macOS' : 'Linux'+ fontTest(`Rio on ${os} with no font in its config: a copy of the Cascadia Code NF in its program`, async ($, on) => {+ const w = world(on, { isMac, env: { TERM_PROGRAM: 'rio' }, copied: FONTS_DIR, families: ['Cascadia Code'] })+ expect(await details($)).toContain(`terminal font ${RIO_DEFAULT_FONT}.`)+ expect(w.fontPaths.at(-1)).toBe(FONTS_DIR)+ const [argv] = w.copies()+ expect(argv).toContain(PROGRAM_FONTS_PL)+ expect(argv).toContain('Cascadia Code NF')+ // The app's bundle is rio.app (lowercase).+ expect(argv).toContain('/Applications/rio.app/Contents/MacOS/rio')+ expect(argv).toContain(isMac ? '/usr/bin/perl' : 'perl')+ })++ fontTest(`Rio on ${os} with a font that is not installed: Rio draws its own font`, async ($, on) => {+ world(on, { isMac, env: { TERM_PROGRAM: 'rio' }, copied: FONTS_DIR, files: { '/h/.config/rio/config.toml': '[fonts]\nfamily = "Iosevka"\n' } })+ expect(await details($)).toContain(`terminal font ${RIO_DEFAULT_FONT}.`)+ })++ fontTest(`Rio on ${os} with a font that is installed: that font, and no copy`, async ($, on) => {+ const w = world(on, { isMac, env: { TERM_PROGRAM: 'rio' }, copied: FONTS_DIR, families: ['Iosevka'], files: { '/h/.config/rio/config.toml': '[fonts.regular]\nfamily = "Iosevka"\n' } })+ expect(await details($)).toContain('terminal font Iosevka.')+ expect(w.copies()).toEqual([])+ expect(w.fontPaths.every(p => p === '')).toBe(true)+ })+}++fontTest("Rio on Linux finds a family by its exact name only (its font database), not by fontconfig's loose match", async ($, on) => {+ world(on, { isMac: false, env: { TERM_PROGRAM: 'rio' }, copied: FONTS_DIR, families: ['IoSevka Term'], files: { '/h/.config/rio/config.toml': '[fonts]\nfamily = "iosevkaterm"\n' } })+ expect(await details($)).toContain(`terminal font ${RIO_DEFAULT_FONT}.`)+})++fontTest('Rio with no Cascadia Code NF in its program (a Rio up to 0.4): Cascadia Code', async ($, on) => {+ world(on, { isMac: true, env: { TERM_PROGRAM: 'rio' }, copied: 'none' })+ expect(RIO_OLD_FONT).toBe('Cascadia Code')+ expect(await details($)).toContain('terminal font Cascadia Code.')+})++fontTest("Rio with no program found: the system's Cascadia Code (the same letters)", async ($, on) => {+ world(on, { isMac: false, env: { TERM_PROGRAM: 'rio' }, families: ['Cascadia Code'] })+ expect(await details($)).toContain('terminal font Cascadia Code.')+})++fontTest("the copied font goes after the user's own TYPST_FONT_PATHS", async ($, on) => {+ const w = world(on, { isMac: false, env: { TERM_PROGRAM: 'rio', TYPST_FONT_PATHS: '/u/fonts' }, copied: FONTS_DIR })+ await details($)+ expect(w.fontPaths.at(-1)).toBe(`/u/fonts:${FONTS_DIR}`)+})++fontTest('a terminal font that Typst does not have: /iui details says so', async ($, on) => {+ world(on, { isMac: false, env: { TERM_PROGRAM: 'rio' }, measure: NO_TERM })+ expect(await details($)).toContain(`terminal font ${RIO_DEFAULT_FONT} (Typst does not have this font, so the pictures use the theme's fonts)`)+})++fontTest('a terminal font that Typst has: no note', async ($, on) => {+ world(on, { isMac: false, env: { TERM_PROGRAM: 'rio' }, copied: FONTS_DIR, measure: JSON.stringify({ ...JSON.parse(NO_TERM), term: { adv: 0.6, xh: 0.5, avg: 0.6 } }) })+ const text = await details($)+ expect(text).toContain(`terminal font ${RIO_DEFAULT_FONT}.`)+ expect(text).not.toContain('Typst does not have')+})++// ---- Ghostty and cmux ---------------------------------------------------------++const shows = (config: string) => (argv: string[]) => (argv.join(' ').includes('+show-config') ? ok(config) : undefined)++fontTest('Ghostty on macOS with a font-family that is not installed: its own JetBrains Mono', async ($, on) => {+ const w = world(on, { isMac: true, env: { TERM_PROGRAM: 'ghostty' }, copied: '/h/.cache/cc-intelligent-ui/fonts/ghostty-1', run: shows('font-family = Iosevka\n') })+ expect(await details($)).toContain('terminal font JetBrains Mono.')+ expect(w.copies()[0]).toContain('JetBrains Mono')+})++fontTest("Ghostty on Linux with a font-family that is not installed: fontconfig's nearest font, as Ghostty draws", async ($, on) => {+ const w = world(on, { isMac: false, env: { TERM_PROGRAM: 'ghostty' }, nearest: 'Noto Sans Mono', copied: '/h/f', run: shows('font-family = Iosevka\n') })+ expect(await details($)).toContain('terminal font Noto Sans Mono.')+ expect(w.copies()).toEqual([])+})++for (const isMac of [true, false]) {+ fontTest(`Ghostty on ${isMac ? 'macOS' : 'Linux'} with a font-family list: the first family of it that is installed`, async ($, on) => {+ world(on, { isMac, env: { TERM_PROGRAM: 'ghostty' }, families: ['Iosevka', 'Menlo'], run: shows('font-family = Nope\nfont-family = Iosevka\nfont-family = Menlo\n') })+ expect(await details($)).toContain('terminal font Iosevka.')+ })+}++fontTest('Ghostty with a font-family that is installed: that font', async ($, on) => {+ world(on, { isMac: true, env: { TERM_PROGRAM: 'ghostty' }, families: ['Iosevka'], run: shows('font-family = Iosevka\n') })+ expect(await details($)).toContain('terminal font Iosevka.')+})++fontTest("cmux: a font-family in cmux's own config counts", async ($, on) => {+ world(on, {+ isMac: true,+ env: { TERM_PROGRAM: 'ghostty', CMUX_SURFACE_ID: 'S1' },+ families: ['Fira Code'],+ files: { '/h/Library/Application Support/com.cmuxterm.app/config.ghostty': 'font-family = "Fira Code"\n' },+ run: shows('font-size = 13\n'),+ })+ expect(await details($)).toContain('terminal font Fira Code.')+})++// ---- kitty ----------------------------------------------------------------------++const kittyConf = (line: string) => ({ '/h/.config/kitty/kitty.conf': `${line}\n` })++fontTest('kitty on macOS with no font_family: Menlo, as kitty draws', async ($, on) => {+ world(on, { isMac: true, env: { TERM: 'xterm-kitty' } })+ expect(KITTY_MAC_FONT).toBe('Menlo')+ expect(await details($)).toContain('terminal font Menlo.')+})++fontTest('kitty on macOS with a font_family that is not installed: Menlo', async ($, on) => {+ world(on, { isMac: true, env: { TERM: 'xterm-kitty' }, files: kittyConf('font_family Iosevka') })+ expect(await details($)).toContain('terminal font Menlo.')+})++fontTest('kitty on macOS with a font_family that is not fixed-pitch: Menlo (kitty looks only at fixed-pitch fonts)', async ($, on) => {+ world(on, { isMac: true, env: { TERM: 'xterm-kitty' }, families: ['Helvetica'], proportional: ['Helvetica'], files: kittyConf('font_family Helvetica') })+ expect(await details($)).toContain('terminal font Menlo.')+})++fontTest("kitty on Linux with a font_family that is not installed: fontconfig's monospace match, as kitty draws", async ($, on) => {+ const w = world(on, { isMac: false, env: { TERM: 'xterm-kitty' }, files: kittyConf('font_family Iosevka') })+ expect(await details($)).toContain('terminal font DejaVu Sans Mono.')+ expect(w.ran.some(argv => argv[0] === 'fc-match' && argv.includes('Iosevka:spacing=mono'))).toBe(true)+})++for (const isMac of [true, false]) {+ fontTest(`kitty on ${isMac ? 'macOS' : 'Linux'} with a full name in font_family: its family, as kitty finds it`, async ($, on) => {+ world(on, { isMac, env: { TERM: 'xterm-kitty' }, names: { 'JetBrains Mono Light': 'JetBrains Mono' }, files: kittyConf('font_family JetBrains Mono Light') })+ expect(await details($)).toContain('terminal font JetBrains Mono.')+ })+}++test('a family as a fontconfig pattern: its special characters escaped', () => {+ expect(fcPatternOf('JetBrains Mono')).toBe('JetBrains Mono')+ expect(fcPatternOf('M+ 1m-x:y,z\\')).toBe('M+ 1m\\-x\\:y\\,z\\\\')+})++// ---- iTerm2 -----------------------------------------------------------------------++const itermWorld = (on: any, o: { marks: string | null; names?: Record<string, string> }) =>+ world(on, {+ isMac: true,+ env: { TERM_PROGRAM: 'iTerm.app', ITERM_PROFILE: 'Default' },+ ...(o.names ? { names: o.names } : {}),+ run: argv => {+ const cmd = argv.join(' ')+ if (cmd.includes('TabStyle')) return undefined+ if (cmd.includes('"New Bookmarks"')) return o.marks === null ? ok('', 1) : ok(o.marks)+ if (cmd.includes('Default Bookmark Guid')) return ok('G1\n')+ return undefined+ },+ })+const profile = (font?: string) => JSON.stringify([{ Name: 'Default', Guid: 'G1', ...(font === undefined ? {} : { 'Normal Font': font }) }])+const fontAsks = (w: World) => w.ran.filter(argv => argv[0] === 'osascript' && argv.join(' ').includes('fontWithNameSize'))++fontTest('iTerm2: a Normal Font with settings after its size is read as iTerm2 reads it', async ($, on) => {+ const w = itermWorld(on, { marks: profile('JetBrainsMono-Regular 13 {"featureSettings":[]}'), names: { 'JetBrainsMono-Regular': 'JetBrains Mono' } })+ expect(await details($)).toContain('terminal font JetBrains Mono.')+ expect(fontAsks(w)[0]!.slice(-2)).toEqual(['JetBrainsMono-Regular', 'user'])+})++for (const font of ['Gone-Regular 12', '', 'nosize', undefined]) {+ fontTest(`iTerm2: a profile font that is not installed, empty or bad (${JSON.stringify(font)}) gives the user's fixed-pitch font, as iTerm2 draws`, async ($, on) => {+ // The script gives the user's font for a name it does not find.+ const w = itermWorld(on, { marks: profile(font), names: { 'Gone-Regular': 'Menlo', '': 'Menlo' } })+ expect(await details($)).toContain('terminal font Menlo.')+ expect(fontAsks(w)[0]!.join(' ')).toContain('userFixedPitchFontOfSize')+ expect(fontAsks(w)[0]!.at(-1)).toBe('user')+ })+}++for (const [why, marks] of [['the read fails', null], ['not JSON', 'not json'], ['no profile', JSON.stringify([{ Name: 'Other', Guid: 'G2', 'Normal Font': 'Monaco 12' }])]] as const) {+ fontTest(`iTerm2: its settings can not be used (${why}): the font is not known`, async ($, on) => {+ const w = itermWorld(on, { marks, names: { '': 'Menlo' } })+ expect(await details($)).toContain('terminal font not known (Menlo assumed)')+ expect(fontAsks(w)).toEqual([])+ })+}diff --git a/tests/terminals.test.ts b/tests/terminals.test.tsindex e435608..ff144c7 100644--- a/tests/terminals.test.ts+++ b/tests/terminals.test.ts@@ -184,11 +184,15 @@ test("Rio's background: adaptive theme (force-theme, else the OS), else theme, eexpect(rioBackgroundOf({}, 'light', themes)).toEqual({ bg: RIO_DEFAULT_BG, detail: 'default background' })})-test("Rio's font: [fonts] family, else [fonts.regular] family, else Cascadia Code", () => {+test("Rio's font: [fonts] family, else [fonts.regular] family, else the Cascadia Code NF it carries", () => {expect(rioFontOf({ 'fonts.family': 'Iosevka', 'fonts.regular.family': 'JetBrains Mono' })).toBe('Iosevka')expect(rioFontOf({ 'fonts.regular.family': 'JetBrains Mono' })).toBe('JetBrains Mono')+ // The family name of the font in Rio's program, as Typst lists it.+ expect(RIO_DEFAULT_FONT).toBe('Cascadia Code NF')expect(rioFontOf({})).toBe(RIO_DEFAULT_FONT)- expect(rioFontOf({ 'fonts.family': 'cascadiacode' })).toBe('Cascadia Code')+ // Rio's default name, in any case and spacing, is always its own font.+ for (const family of ['cascadiacode', 'Cascadia Code', 'CASCADIA CODE ']) expect(rioFontOf({ 'fonts.family': family })).toBe(RIO_DEFAULT_FONT)+ expect(rioFontOf({ 'fonts.family': 'Cascadia Mono' })).toBe('Cascadia Mono')})// ---- iTerm2 and cmux ------------------------------------------------------------