Skip to content

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

TypeScript claude-code-mod

Add /md-preview width; pictures use the full terminal width by default

razorback168f162bab825f
diff --git a/README.md b/README.md
index d0e2d11..bb15a2e 100644
--- a/README.md
+++ b/README.md
@@ -69,10 +69,13 @@ To try it from a clone without installing: `claude --plugin-dir /path/to/claude-
| Command | What it does |
|---|---|
-| `/md-preview` | Shows the state, the text size and the terminal font that the mod found |
+| `/md-preview` | Shows the state, the text size, the width and the terminal font that the mod found |
| `/md-preview on` / `off` | Turns the pictures on or off (kept for later sessions) |
| `/md-preview setup` / `setup remove` | iTerm2: adds or removes the shell line that turns pictures on (then close the tab and open a new one) |
| `/md-preview size <80–200>` | Text size in percent. 100 is the same visual size as your terminal text. |
+| `/md-preview width` | Shows the width: the most columns that a picture can use |
+| `/md-preview width <40–400>` | Sets the most columns that a picture can use (kept for later sessions) |
+| `/md-preview width full` | Pictures use the full width of the terminal, the same as the text of Claude Code (kept for later sessions). This is the default. A picture is never wider than 255 columns. |
| `/md-preview theme` | Lists the themes, shows which one is in use, and shows the folder for your own themes |
| `/md-preview theme <name>` | Changes to that theme (kept for later sessions) |
diff --git a/hooks/lib/command.ts b/hooks/lib/command.ts
index 9ea11a9..5b4981f 100644
--- a/hooks/lib/command.ts
+++ b/hooks/lib/command.ts
@@ -2,13 +2,15 @@
// its registration.
import type { EngineInterface } from 'claude-code'
-import { DEFAULT_SIZE, MAX_SIZE, MIN_SIZE } from './settings'
+import { DEFAULT_SIZE, DEFAULT_WIDTH, IMAGE_MAX_COLUMNS, MAX_SIZE, MAX_WIDTH, MIN_SIZE, MIN_WIDTH, type Width } from './settings'
import { isThemeName, type ThemeInfo } from './themes'
-// `/md-preview` arguments: on, off, size <80-200>, or nothing (show state).
+// `/md-preview` arguments: on, off, size <80-200>, width [40-400|full], or
+// nothing (show state). A `width` with no value shows the width.
export type Command =
| { kind: 'on' | 'off' | 'show' | 'probe' }
| { kind: 'size'; percent: number }
+ | { kind: 'width'; width?: Width }
| { kind: 'theme'; name?: string }
| { kind: 'setup'; remove: boolean }
| { kind: 'bad' }
@@ -28,27 +30,36 @@ export function parseCommand(args: string): Command {
const percent = Number.parseInt(words[1]!, 10)
if (percent >= MIN_SIZE && percent <= MAX_SIZE) return { kind: 'size', percent }
}
+ if (words[0] === 'width' && words.length === 1) return { kind: 'width' }
+ if (words[0] === 'width' && words.length === 2 && words[1] === 'full') return { kind: 'width', width: 'full' }
+ if (words[0] === 'width' && words.length === 2 && /^\d+$/.test(words[1]!)) {
+ const width = Number.parseInt(words[1]!, 10)
+ if (width >= MIN_WIDTH && width <= MAX_WIDTH) return { kind: 'width', width }
+ }
return { kind: 'bad' }
}
-// The /md-preview arguments, and the sizes the typeahead offers.
+// The /md-preview arguments, and the sizes and widths the typeahead offers.
const SUBCOMMANDS = [
{ name: 'on', description: 'draw answers as pictures' },
{ name: 'off', description: 'show answers as text' },
{ name: 'size', description: `text size, ${MIN_SIZE}-${MAX_SIZE}%` },
+ { name: 'width', description: `the most columns a picture takes, ${MIN_WIDTH}-${MAX_WIDTH} or full` },
{ name: 'theme', description: 'list the themes, or switch to one' },
{ name: 'setup', description: 'iTerm2: add the shell line that turns pictures on' },
] as const
const SIZES = [80, 90, 100, 110, 120, 125, 150, 175, 200]
+const WIDTHS: readonly Width[] = [80, 100, 120, 160, 200, 'full']
// Typeahead rows for `/md-preview` arguments: the word at the cursor (`token`,
-// starting at `start` in `text`) completed as a subcommand, a theme name or a
-// size. Right after `theme` or `size`, rows hold the word and its argument,
-// since the typeahead asks only while a word is at the cursor.
+// starting at `start` in `text`) completed as a subcommand, a theme name, a
+// size or a width. Right after `theme`, `size` or `width`, rows hold the word
+// and its argument, since the typeahead asks only while a word is at the
+// cursor.
export type Suggestion = { text: string; label?: string; description?: string }
export function commandSuggestions(
text: string, token: string, start: number,
- o: { themes: readonly ThemeInfo[]; active: string; size: number },
+ o: { themes: readonly ThemeInfo[]; active: string; size: number; width?: Width },
): Suggestion[] {
const head = /^\s*\/md-preview\s+/.exec(text)
if (!head || start < head[0].length) return []
@@ -65,13 +76,23 @@ export function commandSuggestions(
const sizeRows = (prefix: string, lead: string) => SIZES
.filter(n => String(n).startsWith(prefix))
.map(n => ({ text: `${lead}${n}`, label: `${n}%`, description: n === o.size ? 'current' : n === DEFAULT_SIZE ? 'the terminal text size' : undefined }))
+ const width = o.width ?? DEFAULT_WIDTH
+ const widthRows = (prefix: string, lead: string) => WIDTHS
+ .filter(w => String(w).startsWith(prefix))
+ .map(w => ({
+ text: `${lead}${w}`,
+ label: w === 'full' ? 'full' : `${w} columns`,
+ description: w === width ? 'current' : w === DEFAULT_WIDTH ? 'the default' : w === 'full' ? `the terminal width (${IMAGE_MAX_COLUMNS} at most)` : undefined,
+ }))
if (before.length === 0) {
if (word === 'theme') return themeRows('', 'theme ')
if (word === 'size') return sizeRows('', 'size ')
+ if (word === 'width') return widthRows('', 'width ')
return SUBCOMMANDS.filter(c => c.name.startsWith(word)).map(c => ({ text: c.name, description: c.description }))
}
if (before.length === 1 && before[0] === 'theme') return themeRows(word, '')
if (before.length === 1 && before[0] === 'size') return sizeRows(word.replace(/%$/, ''), '')
+ if (before.length === 1 && before[0] === 'width') return widthRows(word, '')
return []
}
@@ -80,7 +101,7 @@ export function commandSuggestions(
export async function registerCommand($: EngineInterface) {
await $.command.register({
name: 'md-preview',
- description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), theme [name] (list or switch themes)",
- argumentHint: '[on|off|size <percent>|theme [name]]',
+ description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), width [40-400|full] (the most columns a picture takes), theme [name] (list or switch themes)",
+ argumentHint: '[on|off|size <percent>|width [columns|full]|theme [name]]',
}).catch(() => undefined)
}
diff --git a/hooks/lib/env.ts b/hooks/lib/env.ts
index b3a9e55..5d2fca5 100644
--- a/hooks/lib/env.ts
+++ b/hooks/lib/env.ts
@@ -4,7 +4,7 @@
import { atom, update } from 'claude-code'
import type { EngineInterface } from 'claude-code'
-import { BASE_THEME, DEFAULT_SIZE, DEFAULT_THEME, MAX_SIZE, MIN_SIZE, NO_TYPST } from './settings'
+import { BASE_THEME, DEFAULT_SIZE, DEFAULT_THEME, DEFAULT_WIDTH, MAX_SIZE, MAX_WIDTH, MIN_SIZE, MIN_WIDTH, NO_TYPST } from './settings'
import { DEFAULT_METRICS, refresh, S, type Env } from './state'
import { resolveMode, settingOf } from './mode'
import { isItermIn } from './terminals'
@@ -73,6 +73,8 @@ export function setUp($: EngineInterface): Promise<Env> {
watchHost($)
const kept = Number(await $.store.get('size').catch(() => undefined))
S.size = kept >= MIN_SIZE && kept <= MAX_SIZE ? kept : DEFAULT_SIZE
+ const width = await $.store.get('width').catch(() => undefined)
+ S.width = width === 'full' ? 'full' : Number.isInteger(width) && Number(width) >= MIN_WIDTH && Number(width) <= MAX_WIDTH ? Number(width) : DEFAULT_WIDTH
if ((await $.store.get('enabled').catch(() => undefined)) === false) await update($, isOn, () => false).catch(() => undefined)
const isMac = os.trim() === 'Darwin'
S.cell = await measureCell($)
diff --git a/hooks/lib/pictures.tsx b/hooks/lib/pictures.tsx
index 6321253..4e0ed8c 100644
--- a/hooks/lib/pictures.tsx
+++ b/hooks/lib/pictures.tsx
@@ -74,7 +74,7 @@ export async function shownOf($: EngineInterface, e: RowInput, ready: Env, files
export async function shownOne($: EngineInterface, e: RowInput, ready: Env, file: string, alt = nameOf(file)): Promise<Shown | null> {
const p = await pictureOf($, file)
if (!p) return null
- const fit = pictureCells(p, columnsFor(e.viewport?.columns), pictureRowsFor(e.viewport?.rows), S.cell ?? DEFAULT_CELL)
+ const fit = pictureCells(p, columnsFor(e.viewport?.columns, S.width), pictureRowsFor(e.viewport?.rows), S.cell ?? DEFAULT_CELL)
if (ready.inline) {
const png = await pictureBytes($, p)
return png ? { source: { png }, ...fit, alt } : null
@@ -172,7 +172,8 @@ export async function sentTextOf($: EngineInterface, file: string): Promise<stri
export async function sentOf(
$: EngineInterface, e: RowInput, o: { ready: Env; markdown: Env | null; files: readonly SentFile[]; id: string },
): Promise<Under[]> {
- const columns = columnsFor(e.viewport?.columns)
+ // Over ssh a Markdown file's page must stay INLINE_MAX_SIDE pixels wide at most.
+ const columns = columnsFor(e.viewport?.columns, S.width, o.ready.inline ? (S.cell ?? DEFAULT_CELL) : null)
// The space a picture takes (as in shownOne), which a JPEG or WebP is made to fit.
const box = convertBox(columns, pictureRowsFor(e.viewport?.rows), S.cell ?? DEFAULT_CELL)
const under: Under[] = []
diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.ts
index 0c81e15..4f20022 100644
--- a/hooks/lib/settings.ts
+++ b/hooks/lib/settings.ts
@@ -4,8 +4,17 @@ import type { Cell } from './state'
// ---- Settings -------------------------------------------------------------
-// The widest picture, in terminal columns.
-export const MAX_COLUMNS = 120
+// `/md-preview width`: the most columns a picture takes (in this range), or
+// `full`, the default: the terminal width less the bullet, as Claude Code's
+// own text. An Image is at most IMAGE_MAX_COLUMNS wide, so no width goes
+// past it.
+export type Width = number | 'full'
+export const DEFAULT_WIDTH: Width = 'full'
+export const MIN_WIDTH = 40
+export const MAX_WIDTH = 400
+export const IMAGE_MAX_COLUMNS = 255
+// The width setting as words: "160 columns", or "full (the terminal width)".
+export const widthText = (width: Width) => (width === 'full' ? 'full (the terminal width)' : `${width} columns`)
// The bullet column to the left of an answer.
export const GUTTER = 2
// Claude Code's own reply bullet: ⏺ on macOS, ● elsewhere.
diff --git a/hooks/lib/state.ts b/hooks/lib/state.ts
index 1801576..70675e5 100644
--- a/hooks/lib/state.ts
+++ b/hooks/lib/state.ts
@@ -7,7 +7,7 @@ import type { MdPreviewTheme } from '../../types'
import type { ThemeInfo } from './themes'
import type { HostMode, ThemeSetting } from './mode'
import type { PlanVerdict } from './plan'
-import { DEFAULT_SIZE } from './settings'
+import { DEFAULT_SIZE, DEFAULT_WIDTH, type Width } from './settings'
// The `done` atom (see types/index.d.ts) for refresh. The state scan of
// `claude plugin validate` reads an atom only from a const in the file that
@@ -73,6 +73,8 @@ export const S = {
cell: null as Cell | null,
theme: 'dark' as MdPreviewTheme,
size: DEFAULT_SIZE,
+ // `/md-preview width`: the most columns a picture takes, or full.
+ width: DEFAULT_WIDTH as Width,
look: null as Look | null,
// The usable themes the last scan found, for the typeahead.
themeChoices: [] as ThemeInfo[],
diff --git a/hooks/lib/terminal.ts b/hooks/lib/terminal.ts
index 5a0bba6..4b23584 100644
--- a/hooks/lib/terminal.ts
+++ b/hooks/lib/terminal.ts
@@ -1,11 +1,15 @@
// What the terminal can draw: its columns and cell size, whether the engine
// draws pictures there, and how large a picture sent as bytes (over ssh) can be.
import type { Cell } from './state'
-import { GUTTER, MAX_COLUMNS, SEGMENT_ROWS } from './settings'
+import { GUTTER, IMAGE_MAX_COLUMNS, SEGMENT_ROWS, type Width } from './settings'
-// The columns a picture takes: the viewport less the bullet, MAX_COLUMNS at most.
-export function columnsFor(viewportColumns: number | undefined): number {
- return Math.max(20, Math.min(MAX_COLUMNS, (viewportColumns ?? 80) - GUTTER))
+// The columns a picture takes: the viewport less the bullet, at most `width`
+// (`/md-preview width`; full: no cap) and IMAGE_MAX_COLUMNS, at least 20.
+// `inlineCell`: over ssh, the cell, so a page stays INLINE_MAX_SIDE pixels
+// wide at most (a wider page can not go as bytes).
+export function columnsFor(viewportColumns: number | undefined, width: Width, inlineCell?: Cell | null): number {
+ const caps = [IMAGE_MAX_COLUMNS, ...(width === 'full' ? [] : [width]), ...(inlineCell ? [Math.floor(INLINE_MAX_SIDE / inlineCell.width)] : [])]
+ return Math.max(20, Math.min(...caps, (viewportColumns ?? 80) - GUTTER))
}
// The cell in device pixels from `rows cols xpixel ypixel` (TIOCGWINSZ).
diff --git a/hooks/register.tsx b/hooks/register.tsx
index 2633027..aec2ec4 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -18,7 +18,7 @@
import { atom, read, update } from 'claude-code'
import type { EngineInterface, Register, RenderElement, RenderViewport } from 'claude-code'
-import { DEFAULT_THEME, MAX_SIZE, MIN_SIZE, TYPST_PROMPT } from './lib/settings'
+import { DEFAULT_CELL, DEFAULT_THEME, IMAGE_MAX_COLUMNS, MAX_SIZE, MAX_WIDTH, MIN_SIZE, MIN_WIDTH, TYPST_PROMPT, widthText } from './lib/settings'
import { editedPlans, refresh, S, subagentPlans, writesLive, type Env } from './lib/state'
import { columnsFor } from './lib/terminal'
import { escapeControls, luminanceOf, modeLine, modeOfLuminance, parseOsc11, settingOf } from './lib/mode'
@@ -40,7 +40,8 @@ import {
// The names this module exported before the split (the tests import them).
export {
- BASE_THEME, DEFAULT_CELL, DEFAULT_SIZE, DEFAULT_THEME, MAX_COLUMNS, MAX_SIZE, MIN_SIZE, PICTURE_MAX_ROWS, SEGMENT_ROWS, TYPST_PROMPT,
+ BASE_THEME, DEFAULT_CELL, DEFAULT_SIZE, DEFAULT_THEME, DEFAULT_WIDTH, IMAGE_MAX_COLUMNS, MAX_SIZE, MAX_WIDTH, MIN_SIZE, MIN_WIDTH,
+ PICTURE_MAX_ROWS, SEGMENT_ROWS, TYPST_PROMPT, widthText, type Width,
} from './lib/settings'
export { DEFAULT_METRICS, type Cell, type FontMetrics, type Look, type Metrics } from './lib/state'
export {
@@ -121,7 +122,7 @@ export const register: Register = on => {
const got = await next(e)
if (!/^\s*\/md-preview\s/.test(e.text)) return got
if (!S.themeChoices.length) await setUp($).catch(() => null)
- const mine = commandSuggestions(e.text, e.token, e.start, { themes: S.themeChoices, active: S.look?.name ?? DEFAULT_THEME, size: S.size })
+ const mine = commandSuggestions(e.text, e.token, e.start, { themes: S.themeChoices, active: S.look?.name ?? DEFAULT_THEME, size: S.size, width: S.width })
return mine.length ? { suggestions: [...got.suggestions, ...mine] } : got
})
@@ -138,6 +139,17 @@ export const register: Register = on => {
refresh($)
return { text: `md-preview draws text at ${S.size}% of the terminal's text size (100% matches it).` }
}
+ if (asked.kind === 'width') {
+ if (asked.width === undefined) await setUp($).catch(() => null)
+ else {
+ S.width = asked.width
+ await $.store.set('width', S.width)
+ refresh($)
+ }
+ const most = typeof S.width === 'number' && S.width > IMAGE_MAX_COLUMNS ? ` (a picture is ${IMAGE_MAX_COLUMNS} columns at most)` : ''
+ const head = asked.width === undefined ? 'The most columns a picture takes' : 'md-preview pictures now take at most'
+ return { text: `${head}: ${widthText(S.width)}${most}. Use /md-preview width <${MIN_WIDTH}-${MAX_WIDTH}> for a cap, or /md-preview width full (the default) for no cap.` }
+ }
if (asked.kind === 'setup') {
await setUp($).catch(() => null)
return { text: await runSetup($, asked.remove) }
@@ -181,9 +193,9 @@ export const register: Register = on => {
? `this terminal draws pictures${ready.inline ? ' (over ssh, sent as bytes)' : ''}`
: 'Claude Code draws no pictures here (it does in kitty and Ghostty, in iTerm2 3.6+ and Rio 0.5.27+ with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1, over ssh when TERM names kitty or Ghostty or with that variable; never in tmux, screen or a background session; not in WezTerm, Warp, Konsole or others), so answers stay text'
const tried = S.setupNeeded ? ' In iTerm2, run /md-preview setup once to show pictures.' : ''
- const usage = `Use /md-preview on, /md-preview off, /md-preview size <${MIN_SIZE}-${MAX_SIZE}>, or /md-preview theme [name].`
+ const usage = `Use /md-preview on, /md-preview off, /md-preview size <${MIN_SIZE}-${MAX_SIZE}>, /md-preview width <${MIN_WIDTH}-${MAX_WIDTH}|full>, or /md-preview theme [name].`
const bad = asked.kind === 'bad' ? `Not understood: "${e.args.trim()}". ` : ''
- return { text: `${bad}md-preview is ${state}, theme ${S.look?.name ?? DEFAULT_THEME}, ${modeLine(S.theme, S.setting, S.settingRaw, S.host)}, text size ${S.size}%, ${font}. ${typst}; ${terminal}.${tried} ${usage}` }
+ return { text: `${bad}md-preview is ${state}, theme ${S.look?.name ?? DEFAULT_THEME}, ${modeLine(S.theme, S.setting, S.settingRaw, S.host)}, text size ${S.size}%, width ${widthText(S.width)}, ${font}. ${typst}; ${terminal}.${tried} ${usage}` }
})
on('config.set', { key: 'theme' }, async ($, e, next) => {
@@ -264,7 +276,7 @@ export const register: Register = on => {
if (e.surface !== 'terminal' || e.props.isSummary || !e.props.text.trim()) return next(e)
const ready = await answerEnv($, e)
if (!ready) return next(e)
- const columns = columnsFor(e.viewport?.columns)
+ const columns = columnsFor(e.viewport?.columns, S.width, ready.inline ? (S.cell ?? DEFAULT_CELL) : null)
const drawing = await pagesOf($, { id: e.requestId, text: e.props.text, columns, env: ready, canStream: true })
if (drawing.kind === 'pages') return drawPages($, e, drawing.result, columns, drawing.px, drawing.bytes, { bullet: !!e.props.isFirstOfReply })
if (drawing.kind === 'text') return next(e)
@@ -339,7 +351,7 @@ export const register: Register = on => {
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
- const columns = columnsFor(e.viewport?.columns)
+ const columns = columnsFor(e.viewport?.columns, S.width, ready.inline ? (S.cell ?? DEFAULT_CELL) : null)
const drawing = await pagesOf($, { id: `plan:${e.props.tool_use_id}`, text: plan, columns, env: ready, canStream: false })
return drawPlanUse($, e, row, drawing, columns)
} catch {
@@ -357,7 +369,7 @@ export const register: Register = on => {
try {
const plan = planOf(e.props.output) ? planShownOf(editedPlans.get(e.props.tool_use_id), e.props.output, undefined) : ''
const ready = plan ? await answerEnv($, e) : null
- const columns = columnsFor(e.viewport?.columns)
+ const columns = columnsFor(e.viewport?.columns, S.width, ready?.inline ? (S.cell ?? DEFAULT_CELL) : null)
const drawing = ready ? await pagesOf($, { id: `plan:${e.props.tool_use_id}`, text: plan, columns, env: ready, canStream: false }) : null
const filePath = (e.props.output as { filePath?: unknown }).filePath
if (drawing && drawing.kind !== 'text') drawn = drawPlanResult($, e, typeof filePath === 'string' ? filePath : undefined)
diff --git a/tests/command.test.ts b/tests/command.test.ts
index 71fff92..2c17004 100644
--- a/tests/command.test.ts
+++ b/tests/command.test.ts
@@ -13,6 +13,7 @@ const at = (text: string) => {
test('the first word completes as a subcommand', () => {
expect(at('/md-preview t').map(r => r.text)).toEqual(['theme'])
+ expect(at('/md-preview w').map(r => r.text)).toEqual(['width'])
expect(at('/md-preview o').map(r => r.text)).toEqual(['on', 'off'])
expect(at('/md-preview S').map(r => r.text)).toEqual(['size', 'setup'])
expect(at('/md-preview x')).toEqual([])
@@ -26,6 +27,10 @@ test('right after theme or size, rows hold the word and its argument', () => {
expect(rows[3]!.description).toBe('built-in, active: default look')
expect(rows[1]!.description).toBe('user: my nord')
expect(at('/md-preview size').map(r => r.text)).toContain('size 150')
+ const widths = at('/md-preview width')
+ expect(widths.map(r => r.text)).toEqual(['width 80', 'width 100', 'width 120', 'width 160', 'width 200', 'width full'])
+ // full is the default; with no width given, it is current.
+ expect(widths.at(-1)!.description).toBe('current')
})
test('a theme name or size completes after its word', () => {
@@ -34,6 +39,11 @@ test('a theme name or size completes after its word', () => {
expect(at('/md-preview size 1').map(r => r.text)).toEqual(['100', '110', '120', '125', '150', '175'])
expect(at('/md-preview size 10')[0]!.description).toBe('current')
expect(at('/md-preview theme nord extra')).toEqual([])
+ expect(at('/md-preview width 1').map(r => r.text)).toEqual(['100', '120', '160'])
+ expect(at('/md-preview width f').map(r => r.label)).toEqual(['full'])
+ const set = (text: string) => commandSuggestions(text, /\S+$/.exec(text)![0], text.lastIndexOf(' ') + 1, { ...o, width: 160 })
+ expect(set('/md-preview width 16')[0]!.description).toBe('current')
+ expect(set('/md-preview width f')[0]!.description).toBe('the default')
})
test('other prompts and the command name itself get no rows', () => {
diff --git a/tests/draw.test.ts b/tests/draw.test.ts
index f2dfd9b..90073d7 100644
--- a/tests/draw.test.ts
+++ b/tests/draw.test.ts
@@ -69,8 +69,17 @@ const TALL = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 06 40 00 00
// The first 33 bytes of the 1600 x 64 PNG, base64.
const PNG = 'iVBORw0KGgoAAAANSUhEUgAABkAAAABACAYAAAAAAAAA'
-function world(on: any, vars: Record<string, string>, head = HEAD) {
- mock.store(on)
+// `stored`: what md-preview kept in its store before (a setting).
+function world(on: any, vars: Record<string, string>, head = HEAD, stored: Record<string, unknown> = {}) {
+ // md-preview's store in memory (as mock.store), and its writes by key.
+ const store = new Map(Object.entries(stored))
+ const kept: Record<string, unknown> = {}
+ on('store.get', async ($: any, e: any) => ({ value: store.get(e.key) }))
+ on('store.set', async ($: any, e: any) => {
+ store.set(e.key, e.value)
+ kept[e.key] = e.value
+ return { value: undefined }
+ })
const clock = mock.clock(on)
mock.env(on, { HOME: '/h', ...vars })
const reads: string[] = []
@@ -99,7 +108,7 @@ function world(on: any, vars: Record<string, string>, head = HEAD) {
on('fs.list', async ($: any, e: any, next: any) => (e.path.startsWith('/c/') ? { value: [{ name: 'a-1.png', kind: 'file', size: 1, mtimeMs: 1, isLink: false }] } : next(e)))
on('ui.toast', async () => ({ value: undefined }))
on('ui.render', () => ENGINE as any)
- return { clock, reads }
+ return { clock, reads, kept }
}
const ENGINE = { type: 'Text', props: {}, children: ['engine drawing'] }
@@ -158,3 +167,39 @@ test('in tmux with the engine forced, answers stay text', async ($, on) => {
await ui.redraw(props('Some **bold** text.'))
expect(await ui.drawn()).toMatchObject(ENGINE)
})
+
+// ---- The width setting --------------------------------------------------------
+
+const wide = (requestId: string, text: string) => ({ ...message(requestId, text), viewport: { columns: 300, rows: 40 } })
+
+test('a kept width caps the pictures; width full draws at the terminal width at once, 255 columns at most', async ($, on) => {
+ const { clock, kept } = world(on, { TERM: 'xterm-kitty' }, HEAD, { width: 160 })
+ const ran = await $.command.run({ command: 'md-preview', args: '' } as any)
+ expect(ran.text).toContain('width 160 columns')
+ const ui = await $.ui.mount(wide('w-1', 'Some **bold** text.'))
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ const [first] = images(await ui.drawn())
+ expect(first.props.columns).toBe(160)
+ const set = await $.command.run({ command: 'md-preview', args: 'width full' } as any)
+ expect(set.text).toContain('full (the terminal width)')
+ expect(kept.width).toBe('full')
+ // Another key (the columns are in it): compiled again, then drawn wider.
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ const [now] = images(await ui.drawn())
+ expect(now.props.columns).toBe(255)
+ expect(now.props.source.file).not.toBe(first.props.source.file)
+})
+
+test('width with no value shows it; a bad value is refused; a bad kept value is the default', async ($, on) => {
+ const { kept } = world(on, { TERM: 'xterm-kitty' }, HEAD, { width: 20 })
+ const shown = await $.command.run({ command: 'md-preview', args: 'width' } as any)
+ expect(shown.text).toContain('The most columns a picture takes: full (the terminal width)')
+ const bad = await $.command.run({ command: 'md-preview', args: 'width 39' } as any)
+ expect(bad.text).toContain('Not understood: "width 39"')
+ expect(kept.width).toBe(undefined)
+ const set = await $.command.run({ command: 'md-preview', args: 'width 400' } as any)
+ expect(set.text).toContain('400 columns (a picture is 255 columns at most)')
+ expect(kept.width).toBe(400)
+})
diff --git a/tests/pure.test.ts b/tests/pure.test.ts
index 1455c46..1900151 100644
--- a/tests/pure.test.ts
+++ b/tests/pure.test.ts
@@ -2,7 +2,7 @@ import { expect, test } from 'claude-code/testing'
import {
alignFirstLine, DEFAULT_METRICS, DEFAULT_SIZE, firstLineOf, fontFit, ghosttyFontOf, itermFontOf, parseCommand, parseFontSpec, typstCall,
- blocksOf, canDrawIn, cellOf, columnsFor, DEFAULT_CELL, hashOf, imagePathOf, isSet, localImages, MAX_COLUMNS,
+ blocksOf, canDrawIn, cellOf, columnsFor, DEFAULT_CELL, hashOf, imagePathOf, isSet, localImages, DEFAULT_WIDTH, IMAGE_MAX_COLUMNS,
parseOd, plainOf, pngSize, rowsFor, shouldRetrySafe, sizing, splitSegments, themeOf, TYPST_PROMPT,
escapeControls, luminanceOf, modeOfLuminance, OSC11_PL, parseOsc11, pickProfile, itermAppearanceOf, itermModeOf,
GHOSTTY_DEFAULT_BG, ghosttyBackgroundOf, ghosttyThemePaths, ghosttyThemesOf, ghosttyValueOf, hexColorOf,
@@ -116,9 +116,8 @@ test('the body font is matched to the terminal font by x-height and width', () =
})
test('size math: the PNG is exactly as wide as the box', () => {
- expect(columnsFor(100)).toBe(98)
- expect(columnsFor(300)).toBe(MAX_COLUMNS)
- expect(columnsFor(undefined)).toBe(78)
+ expect(columnsFor(100, 'full')).toBe(98)
+ expect(columnsFor(undefined, 'full')).toBe(78)
const s = sizing(100, { width: 16, height: 32 }, 6.6)
expect(s.widthPt).toBe(660)
expect(s.widthPx).toBe(1600)
@@ -130,6 +129,39 @@ test('size math: the PNG is exactly as wide as the box', () => {
expect(sizing(120, { width: 17, height: 34 }, 5.82).widthPx).toBe(2040)
})
+test('the width: full by default (the viewport less the bullet), a cap when set, 20 to 255 columns', () => {
+ expect(DEFAULT_WIDTH).toBe('full')
+ expect(columnsFor(200, DEFAULT_WIDTH)).toBe(198)
+ expect(columnsFor(200, 120)).toBe(120)
+ expect(columnsFor(100, 120)).toBe(98)
+ expect(columnsFor(200, 40)).toBe(40)
+ // An Image is 255 columns at most, also for a larger cap.
+ expect(columnsFor(400, 'full')).toBe(IMAGE_MAX_COLUMNS)
+ expect(columnsFor(400, 400)).toBe(IMAGE_MAX_COLUMNS)
+ // A narrow terminal still gets 20 columns.
+ expect(columnsFor(10, 'full')).toBe(20)
+ expect(columnsFor(10, 40)).toBe(20)
+ // Over ssh a page is 4096 px wide at most: 256 columns of 16 px, 204 of 20 px.
+ expect(columnsFor(400, 'full', { width: 16, height: 32 })).toBe(IMAGE_MAX_COLUMNS)
+ expect(columnsFor(400, 'full', { width: 20, height: 40 })).toBe(204)
+ expect(columnsFor(150, 'full', { width: 20, height: 40 })).toBe(148)
+ expect(columnsFor(400, 'full', null)).toBe(IMAGE_MAX_COLUMNS)
+})
+
+test('the width command: a value of 40 to 400, full, or nothing to show it', () => {
+ expect(parseCommand('width')).toEqual({ kind: 'width' })
+ expect(parseCommand('width full')).toEqual({ kind: 'width', width: 'full' })
+ expect(parseCommand('WIDTH Full')).toEqual({ kind: 'width', width: 'full' })
+ expect(parseCommand('width 40')).toEqual({ kind: 'width', width: 40 })
+ expect(parseCommand('width 160')).toEqual({ kind: 'width', width: 160 })
+ expect(parseCommand('width 400')).toEqual({ kind: 'width', width: 400 })
+ expect(parseCommand('width 39')).toEqual({ kind: 'bad' })
+ expect(parseCommand('width 401')).toEqual({ kind: 'bad' })
+ expect(parseCommand('width 12.5')).toEqual({ kind: 'bad' })
+ expect(parseCommand('width wide')).toEqual({ kind: 'bad' })
+ expect(parseCommand('width 120 full')).toEqual({ kind: 'bad' })
+})
+
test('the size command takes 80 to 200 percent', () => {
expect(parseCommand('')).toEqual({ kind: 'show' })
expect(parseCommand(' on ')).toEqual({ kind: 'on' })