Skip to content

Latest commit

 

History

History
435 lines (379 loc) · 30.1 KB

markdown-rendering.md

File metadata and controls

435 lines (379 loc) · 30.1 KB

CLI assistant markdown rendering

This is the exact display contract for MVP-2a. Implementation is accepted on development at b636be5f after clean cumulative reviews and a separate parser security sitting; see the step acceptance record. All four MVP-2 steps are implemented and step-reviewed. The checkpoint record owns combined validation and maintainer review; publication remains a later release decision.

Amended 2026-11-23. Two parts of this contract came after the MVP-2a acceptance above and carry their own decisions: the wrapped grid and records for a table that does not fit (ADR-0143, Accepted 2026-11-23), and syntax highlighting (ADR-0144, Accepted 2026-11-23). The acceptance record above covers the rest.

Scope and source

Render only assistant entries, including restored assistant answers. User echoes, notices, reasoning and tool rows remain plain: no markdown interpretation, with the same terminal sanitization floor. Plain/non-TTY, --json, run output and chat export keep their existing representations.

With color disabled, render sanitized markdown source with its markers intact. The geometry layer still expands tabs and wraps to fit. Do not interpret markup and silently remove emphasis markers when it cannot be styled.

Sanitize source once at the existing transcript boundary before parsing. Keep a source projection for /copy, /edit and /scrollback, and a separate styled projection for drawing; neither projection bypasses that boundary. Source hatches retain sanitized markdown and tabs rather than grid borders or display expansion. Copy-on-select returns the rendered rows actually highlighted. Restored user entries in all hatches use their safe restored display form, never expanded attachments.

Supported blocks

Source Display with color enabled
ATX heading, one to six # followed by space Heading text, bold; omit the opening marker and optional space-separated closing markers
Backtick or tilde fence of at least three characters Code text verbatim with a dim │ gutter; nonempty info string shown as a dim label; a block whose info string names a supported language is coloured by token class
-, +, * followed by space Bullet • , with a hanging continuation indent
Decimal digits followed by . or ) and space Preserve the written ordinal with a hanging continuation indent
Nested list indentation Preserve relative indentation, up to the nesting limit
> followed by optional space Dim quote bar │ ; nested bars up to the nesting limit
Thematic break, at least three matching -, * or _, with optional spaces A dim rule fitting the available columns
Paragraph Inline text; a soft source newline becomes a display space within the paragraph
GFM pipe table Bordered grid when the complete table fits; otherwise a grid with each cell wrapped inside its column; labelled records only when even the column floors do not fit (see below)

A fence closes only on the same character, at least the opening length, with no following non-space text. An unfinished fence remains code through end-of-turn. Code bodies get no inline processing. Syntax highlighting classes the text of a block whose info string names a supported language and changes nothing else. An info string is sanitized as an inline value and never changes the parser or executes anything.

Setext headings, indented code, HTML, reference definitions/links, footnotes and lazy continuation render literally. Unsupported structures must not cause otherwise literal text to disappear. More deeply nested constructs also fall back to their source; this is a subset, not CommonMark compliance.

Block precedence and indentation

After identifying the current quote/list container, use this precedence: an existing open fence, a new fence, a pipe-table header/delimiter pair, an ATX heading, an unsupported Setext pair kept literally, a thematic break, a list item, a quote, then a paragraph. A thematic break wins over a list marker, so - - - is a rule. Title followed by --- or === is a literal two-line Setext pair, not a table or a paragraph followed by a rule. A standalone --- is a rule. Hold a potential paragraph/header line pending for this one-line lookahead.

Fence openers/closers accept zero to three leading source ASCII spaces relative to their container. Four or more source ASCII spaces are unsupported indented code and stay literal. A root-leading source TAB remains paragraph content, expanded for display; it does not itself select the indented-code fallback. Tabs consumed as list indentation follow the structural column rules below. Remove up to the opener's indentation from each code-body line, preserving any remaining indentation. A closer may have its own zero-to-three-space indentation and may be followed only by ASCII spaces or TABs. A backtick fence's info string cannot contain a backtick; such an opener is literal. Tilde info strings have no corresponding backtick restriction.

For lists, expand source tabs to eight-cell stops for structural column math. A marker is followed by one to four spaces; its content column is the first non-space column after that padding. A child marker at or beyond its parent's content column opens the next depth; a marker at the same column is a sibling, and dedenting pops containers until the column fits. A non-marker line reaching the active content column continues that item with a hanging indent equal to its displayed marker/padding width. Lazy or ambiguous continuation remains literal. Excess-depth list/quote lines and their over-depth continuations render literally until they return within the admitted depth; earlier admitted siblings stay styled. The limit does not turn an already completed list into raw source.

Each > consumes one quote depth and at most one following space. Once inline depth reaches its cap, additional delimiters themselves remain literal; earlier matched spans remain styled. These are interpretation limits, not truncation.

A whole-line simple opening HTML tag owns literal source through its whole-line matching closing tag, including same-name nested pairs. Matching is ASCII case-insensitive; names start with an ASCII letter, followed by ASCII letters, digits or hyphens. An unclosed region remains literal through EOF; leaving its quote/list container ends it. Self-closing tags, tags with trailing text and the HTML void elements remain one-line literal forms. Attributes and HTML content are never interpreted. Tag-led HTML comments remain literal through --> or EOF, and complete doctype declarations remain one-line literal forms. Comment terminator lines remain wholly literal, including trailing text.

Supported inline constructs

Source Display
Matching backtick runs Code text, preserving literal internal markup
**strong** or __strong__ Bold text
*emphasis* or _emphasis_ Italic text; _ within a word stays literal
~~strike~~ Struck text
[label](target) Label followed by (target); if label equals target, show it once
<https://example.test> or an email autolink Show the complete displayed target once
![alt](target) Dim [image: alt] (target); no fetch or image decoding
Backslash before ASCII punctuation Literal escaped punctuation
Two trailing spaces or a trailing unescaped backslash before newline Hard line break

An unmatched delimiter stays literal. Bound delimiter nesting; unsupported link forms, including optional titles, stay literal rather than dropping information. Complete bare bracket groups remain literal as unsupported shortcut-reference candidates; labels of valid inline links still receive inline styling. Labels, targets and info strings receive sanitizeInline treatment, so they cannot forge rows. Never emit OSC 8, launch a URL, resolve it or fetch its target. Do not truncate or conceal a link's real target. A long URL wraps as text.

Tables and fixed limits

A table begins with a header and a matching delimiter row. Delimiter cells have at least three hyphens and optional leading/trailing colons. Leading/trailing pipes are optional, but both the header and delimiter row must contain at least one unescaped pipe outside a code span. This distinguishes even a one-column table (| Title | / | --- |) from the pipe-free literal Setext pair. Split cells with a linear scanner that respects escaped pipes and code spans. Header and delimiter column counts must match; unsupported or ambiguous forms remain literal. A body row may contain one cell without a pipe; short body rows receive empty trailing cells. A table ends at a blank line, an unambiguous new block or EOF. An over-wide body row makes the table literal rather than discarding a cell.

Use ┌┬┐, ├┼┤, └┴┘, ─ and │ for the grid, one space of cell padding, and header emphasis. Colon alignment controls cell alignment. Measure the displayed inline cell text, including visible link targets. No cell is cropped.

Wrapped grid. When the single-line grid is wider than the available columns, or the aligned cells need tab stops that cannot agree, the table keeps its grid with each cell wrapped inside its column (ADR-0143):

  • a column's floor is the largest of 8, its longest word (capped at 24) and its widest grapheme cluster, and never more than its natural width; no column drops below its floor;
  • the excess above the floors is shared in proportion to how far each column sits above its floor, so the widest columns give up the most and the grid fills the width exactly;
  • a row is as tall as its tallest cell; cell text keeps its inline styling;
  • alignment applies to every wrapped line; the header row is bold and ruled off;
  • body rows are ruled apart only when a cell wraps;
  • a word wider than its column breaks inside the word.
  • a wrap drops only an ASCII space or tab where it broke a line (a continuation line starts at its text, and a line has no trailing space); a no-break space (U+00A0), an ideographic space (U+3000) and the other Unicode spaces are content and stay, though a line may still break at one.

Records. Only when even the column floors do not fit the width does the table render as records:

  • a dim notice, table shown as records: its grid does not fit this width;
  • then, for each body row, a blank line and, for each column, the header as a bold label line with its cell text on the lines below, indented two columns;
  • cell text keeps its inline styling and wraps to the width, so no cell is cropped;
  • an empty cell shows a dim —; a blank header shows a dim column N;
  • alignment is not drawn, and no gutter is added, so a record inside a quote shows only the quote bar;
  • every record repeats every label, so when the repeated labels alone would exceed four times the length of the table's source, the table stays literal instead; a label whose widest grapheme does not fit the width, or a value whose widest grapheme does not fit the width less the two-column indent, keeps it literal too.

Literal fallback. Sanitized source is shown with its markers intact. With color enabled it is word-wrapped to the width like prose, so it is not a verbatim, column-preserving copy. It applies to a table over a fixed limit, a table with a hard break inside a cell, a header-only table that does not fit its grid, and a width at which not even one record value fits (two columns or fewer, or a label or value whose widest grapheme cannot fit its line). A header-only table that fits is drawn as a grid. A table kept literal starts each wrapped line at its text, not at the ASCII space or tab that broke the line, because a table's spacing is not prose. A grid or a record never replaces a grapheme with ?; a literal table is drawn by the general geometry rule, which does, at a width below that grapheme's own. Inside a quote, a table kept literal for a fixed limit is drawn with the quote bar and its inner source, and one that falls back for width is drawn as its quoted source. With color disabled, every table keeps the color-off path of Scope and source: records would drop the pipes that carry the structure without color.

Limit Value Overflow behavior
List depth 8 Deeper structure renders literally
Quote depth 8 Deeper structure renders literally
Inline delimiter nesting 32 Excess delimiters remain literal
Table body rows 128, excluding header/delimiter Entire table renders literally
Table columns 32 Entire table renders literally
Pending table source 65,536 UTF-16 code units Entire table renders literally

Limits bound interpretation work, not source retention. Do not omit overflow rows or truncate source to satisfy a parser cap. Once a streaming table crosses a cap, keep that table literal through its end. No later token can reactivate a grid and force repeated full-table layout. While such a table is still arriving, it is laid out as the finished literal table is, so the transcript does not reflow when the stream ends. That holds for a table outside a container; inside a quote the pending lines are wrapped to the full width with their raw > marks, and are re-wrapped inside the quote bar when the table finishes. A table that ends as a grid is first literal and then a grid: its column widths depend on every row. Layout work is linear in the admitted bounded table; there is no search over alternative column-width combinations. Alignment padding participates in tab-stop geometry for a single-line grid. If aligned cells require incompatible tab-stop phases, or the compatible grid does not fit, the table becomes a wrapped grid (see Tables above). The wrapped grid expands each tab from the start of its own cell, so tab stops do not align across its rows. The fixed limits above still render the entire table literally.

Syntax highlighting

ADR-0144 owns the reasoning. This section is the contract.

A fenced block whose info string names a supported language is split into runs, and each run has one token class. The scan is lexical: it reads characters, not a grammar, and it never edits, drops, repeats or reorders one. The runs, joined, are exactly the block's text, so rows, wrapping, tab stops, the gutter, copy, edit and scrollback are the same with and without it. Highlighting changes only the style of a run. It runs on text that is already sanitized and adds no terminal sink.

Languages

The language is named by the first word of the info string, matched case-insensitively. A leading {, . or blanks and a leading language- are skipped, and the word ends at the first character that is not a letter, a digit, _, +, # or -, so ts title="a.ts", {.ts}, typescript{1,3}, language-ts and ts:src/a.ts all name TypeScript. There is no sniffing of the content. A block with no info string, or with one that is not listed, is not highlighted and keeps the single code colour (cyan) it has always had.

Family Info strings What it reads
typescript typescript, ts, tsx, mts, cts Keywords, types, numbers, strings, template literals with their ${…} holes, regular-expression literals, comments, decorators, call sites
javascript javascript, js, jsx, mjs, cjs, node, nodejs The same, without the TypeScript-only keywords
json json, jsonc, json5, jsonl Keys against values, numbers, true, false, null, comments
python python, py, python3, py3 Keywords, triple-quoted and prefixed strings, decorators, builtin types, comments
shell bash, sh, shell, zsh, ksh, dash Command names, options, strings, $ expansions, assignments (also after export), keywords, comments; in a session transcript (the first line starts with $ ) only the prompt lines
yaml yaml, yml Keys, scalars, comments, anchors, tags, flow collections and block scalars
toml toml Tables, keys (also in inline tables), strings (also multiline), numbers, dates, comments, multi-line arrays
ini ini, cfg, properties, env, dotenv Sections, keys, export, values, # and ; comments (a # right after the = is part of the value)
diff diff, patch, udiff Added and removed lines, hunk headers, file headers
sql sql, psql, mysql, postgres, postgresql, sqlite, pgsql, plpgsql, tsql Keywords in any case, types, strings, quoted identifiers, numbers, comments, calls
go go, golang Keywords, types, raw strings, runes, comments
rust rust, rs Keywords, types, lifetimes and char literals, raw strings, attributes, macros, comments
java java Keywords, types, annotations, text blocks, comments
c c, h Keywords, types, preprocessor directives and include paths, digit separators, comments
cpp cpp, c++, cc, cxx, hpp, hh, hxx, cplusplus The same, with the C++ keywords
csharp csharp, cs, c# Keywords, types, methods and constructors, verbatim and raw strings, preprocessor directives, comments
markup html, htm, xml, svg, xhtml, plist, xsd, rss Tags, attributes, values, comments, declarations
css css At-rules, property names, colours, numbers with units, !important, comments
dockerfile dockerfile, docker, containerfile Instructions (in capitals), strings, comments

Classes and colours

Colour is by class, in one place (syntax-palette.ts), and only five named ANSI colours, bold and dim are used. The terminal's own palette chooses the shade, so a light and a dark theme need no detection. Blue and the bright shades are not used, because blue has the weakest contrast on a dark theme and the bright shades on a light one. A comment is dim and not grey, because some themes draw grey as their background. Code in a highlighted block that has no class of its own (identifiers, punctuation, whitespace) is drawn in the default colour.

Class Colour Used for
text default Identifiers, punctuation, whitespace
keyword magenta Reserved words, shell and SQL keywords, tag names
string green String and character literals, include paths, block scalars
number yellow Numbers, dates, colours in CSS
constant yellow true, false, null and the like
comment dim Comments
type cyan Builtin and capitalised type names, lifetimes, table headers
function bold A name followed by (, a shell command name
property cyan Keys, options (--flag), attributes, CSS properties
variable cyan Shell variables and assignments
meta yellow Decorators, annotations, directives, anchors and tags, diff file headers
inserted green A line added in a diff
deleted red A line removed in a diff
hunk cyan The @@ … @@ part of a diff hunk header

Limits and fallbacks

  • A block over 65,536 UTF-16 units, or with a line over 4,096, is not highlighted, as a whole. So is a block whose scanner fails: every scanner counts its steps against a budget of eight per character plus 256, and exceeding it is a failure of the scanner, not of the input. A partly coloured block would read as broken; a plain one reads as it always did.
  • Every scanner is a single pass, and every lookahead (the search for a closing delimiter, or for the end of a line) goes through one remembered search for each delimiter, so asking again past a search that found nothing reads nothing. A lookahead that stops at a character class and not at a delimiter (the colon after a string, the characters after a CSS property name, a YAML line's key, the blanks before a TOML =) cannot use that search, so it charges what it reads itself (Segments.charge), and a block built to make each of them read far ahead is shown plain. The work counter counts every step and every character such a search reads. It stays at most four per character on every input tested, and the block is not highlighted past eight per character plus 256. Tests prove the bound by counting, not by time: four times the text must cost no more than about four times the work, which a repeated failing search (a quadratic scan) would break.
  • The scanners are approximate, and a misread changes a colour and nothing else. Known cases:
    • JavaScript and TypeScript: a regular-expression literal after a ) or ] (read as division); an apostrophe or // in JSX text between tags (read as a string or comment up to the end of its line); a word that is a keyword in one place and a name in another (type, of, from); a template literal nested more than 32 deep.
    • Shell: a heredoc body, a case pattern with |, and the first word of an output line in a block that has no $ prompt.
    • Go: capitalised user types are plain (only builtin types are classed). Python: match and case. Dockerfile: the digits of an image tag. A call to a generic function (f<T>(x)) is not bold.
    • YAML: a plain scalar that spans lines, whose continuation can be read as a key.
  • With colour disabled the source keeps its markers and no span is drawn.

Streaming

The scanner is a pure function of the block's text. A block that fits the live window is coloured while it streams as the finished block is. The live tail lays out at most 4,000 characters of an open fence, and the window keeps the fence's language even when it has to leave the label out, so a long block is coloured too. The part of a block before that window is not scanned: a construct that opened there (a block comment, a template literal) is read as code until the turn ends and the whole text is laid out. At that moment only colours change: no character and no row does. An unfinished multiline construct (a block comment, a template literal, a triple-quoted or raw string) colours the rest of the block until it closes; an unfinished single-line string ends at its line. The live tail and the finished layout have the same rows, with and without a language.

Geometry

Expand tabs to the next eight-cell stop on each logical display line before measuring, including prefixes. Full-screen prose wraps at word boundaries, with a grapheme-preserving fallback for a token wider than the available columns. Preserve code indentation and content; wrap code to fit with its gutter retained when the prefix leaves at least one content cell. Continuation rows inherit the block's hanging indent under that same condition. If gutters, quote/list prefixes or hanging indentation exhaust the available columns, render that block's sanitized source literally with no added prefix/indentation. Literal wrapping still advances at widths 1 and 2; do not subtract a prefix into a zero/negative content budget. Source hatches retain original content in either case.

A DisplayLine occupies one terminal row. Its text equals the concatenated drawn spans. Measure grapheme clusters across adjacent span boundaries, so a combining mark or ZWJ sequence split by markup cannot be counted twice. Resolve style changes inside one grapheme consistently for the whole cluster. Full-line width must agree with Ink's string-width measurement. Selection and clipboard partition the same displayed text by the existing column primitive.

Both renderers draw the same word-wrapped rows, with semantic spans as nested Ink text. They share parsed constructs, literal fallbacks and tab geometry. Borders, gutters and prefixes count toward the live row budget. Spinner, elision line, prompt and abort hint remain visible at 80×24. For a positive row width smaller than one wide grapheme, the geometry layer draws ? for that cluster as a terminating display fallback; source hatches retain the original cluster. At zero/invalid width, suspend transcript painting until resize while keeping cancellation available. Do not assume the Home's minimum-size guard also exists on standalone chat; MVP-3 still owns the full 80×24 chat guard. Test these narrow-width paths in both hosts, including code gutters, lists, quotes and deep indentation at widths 1 and 2.

Streaming and caching

An incremental parser consumes sanitized appended input before the live viewport tails it. Sanitization must handle terminal-control sequences split between chunks identically to the existing whole-source boundary. Rendering must not reveal a control sequence merely because its terminator has not arrived. An unfinished control sequence exceeding 65,536 UTF-16 units suspends that live segment with a fixed notice and keeps cancellation available. The retained final turn is sanitized independently; this live buffer bound never truncates its source.

Retain stable completed blocks and an open-block checkpoint. A potential table header is pending until its delimiter is known; a table stays verbatim until a blank line, an unambiguous next block or end-of-turn closes it. Only then build its grid once. An in-progress fence or inline delimiter retains its own state. Completed stable blocks do not change when new tokens arrive. The pending block may change, including source-to-grid conversion at table completion.

Parsing appended input is amortized O(n) over a turn, not O(n) for every token. Do not repeatedly rescan a long unfinished line, copy the entire accumulated source, or reparse a completed prefix per frame. Drawing may re-layout the bounded visible pending region; count that separately from parser work. Reuse parsed blocks across resize; invalidate layout by width and color policy. Bound live layout caches and keep immutable entry caches scoped to entries still retained. Reset stream state on turn, tool-round and host changes according to existing assistant-text ownership; do not leak a previous fence into the next answer.

Acceptance evidence

Direct tests cover every subset construct, unmatched syntax, exact/+1 limits, hostile controls/bidi, split chunks, escaped pipes, long unfinished lines, fences, tables and Unicode across spans. A structural-work counter or equivalent causal assertion proves incremental processing; elapsed time alone cannot prove linearity. Autolink admission uses a single-pass target check. A malformed email candidate with a long dotted domain and a second @ must remain literal without regex backtracking. Native child regressions exercise actual cold wrapping and the live closing-delimiter append with 200,000 dots, a finite deadline and a process heap cap; these resource checks supplement the grammar-equivalence and structural tests. Multiline literal bracket groups retain opaque ownership across LF. A provisional block close/reopen must reactivate cached delimiter queries as actual input grows, without rescanning the retained prefix. Cold/live semantic suffix and tab checks cover bare, link, image and reference forms, including a wrapper outside the live source window and a transient thematic-break candidate inside the group. Replacing an inner opaque owner with an enclosing literal group must notify cached owner/scope queries even when byte coverage stays unchanged. Restored dirty decisions must settle before drawing the same append, including work queued during gap filling; inner autolink angle bytes must not disappear. Escaped literal backtick runs must consume source and preserve adjacent ticks as literal text. Native whole/split regressions enforce finite completion, heap and indexed-work bounds; a synchronous no-progress loop cannot rely on an in-process test timer for cancellation. Test Title\n---, - - -, one-column pipe tables, fence indentation/info strings and nesting/fallback units both complete and split at every streaming boundary, through both renderers and both color policies.

Mounted Ink tests exercise both renderers, color on/off, resize and 80×24, source hatches, rendered selection, failure marks and local clipboard-write failure, including a delayed native callback fault without premature success or feedback after unmount/reseat. Cold-wrap evidence uses actual assistant entries with markdown, wide/combining characters, tables and long tokens, including a 500-entry restore. Keep the existing cold-wrap guard and report measured results without claiming an unmeasured maximum-size archive is fast.

Highlighting is covered by highlight/*.test.ts (each language's classes, the run collector, and the invariants on random, prefix and adversarial text), highlight-layout.test.ts (spans through wrapping, quotes and lists, the limits, and the live tail against the finished layout), syntax-palette.test.ts and markdown-text-highlight.test.tsx (the palette and the SGR sequences of a real ink frame, colour on and off), and highlight-reference.test.ts, which compares the two tables above with the code in both directions.

MVP-2a also needs the scoped security sitting on parser bounds, target display and sanitize order. Headless package/Windows smoke proves machine compatibility; it does not establish native terminal input or clipboard acceptance.