Self-contained HTML export#

gtroff render --format html turns the common Linux man semantic model into a standalone page. The default output includes responsive CSS, Go Regular/Bold/ Italic/Mono fonts, a title, semantic content and stable section permalinks. It requires no installed groff, browser, fontconfig, fonts or external rendering utility to generate the page. Open the output in a browser to read it.

go build -o gtroff ./cmd/gtroff
./gtroff render --format html -o page.html examples/man-tool.1
./gtroff render --section OPTIONS --theme dark -o options.html examples/man-tool.1
./gtroff render --section OPTIONS --fragment examples/man-tool.1 > fragment.html
printf '.SH NAME\nhello\n' | ./gtroff render - > stdin.html

The committed example is generated by the CLI and verified byte-for-byte in tests against the API and source scenario. Download it with its embedded fonts, then open it locally; no font installation or server is needed. Source remains separate and unchanged.

API and selection#

tree, err := groff.ParseAST(input, groff.WithPackage("man"))
if err != nil {
    return err
}
document, err := man.Build(tree, man.Options{})
if err != nil {
    return err
}
result, err := renderhtml.Render(output, document, renderhtml.Options{
    Section: "OPTIONS",
    Theme: "dark",
})
// result.Diagnostics includes source and conversion findings.

Render(io.Writer, *man.Document, Options) exports the full document by default. API Options.Node uses a semantic node ID; Options.Section selects all exact repeated matching sections/subsections. These options are mutually exclusive. RenderSelection accepts roots from a man.Selection together with the owning semantic document. It uses the owner’s validated data and ancestry, rather than trusting altered selection copies. Overlapping roots render once in source order. A selected item receives a valid definition-list wrapper, and a selected body retains its enclosing item/relative indentation without replaying roff requests.

CLI --node uses an AST source ID, matching gtroff ast output. Inline IDs resolve to their physical line’s complete semantic block. Supported indent and preformatted AST block IDs select their semantic group. Header/body/terminator lines and nested block IDs inside a capture select its complete literal owner. IDs that have no semantic content are errors, not implicit whole-page exports. API callers can use document.SelectAST before RenderSelection for the same mapping. The library’s original syntax/source APIs remain separate from HTML formatting.

Full pages have a document shell, viewport settings and a restrictive CSP. --fragment / Fragment returns an article and its styles without the document shell. NoAnchors / --no-anchors removes generated heading IDs/permalinks; ordinary validated source links are independent. Stable numeric node IDs keep repeated headings distinct. Metadata, node kinds, source offsets and original layout annotations are escaped data attributes, not executable source.

Appearance and fonts#

Options include Title, Theme (light/dark), FontSize (8–72 pixels), LineHeight (1–3), MaxWidth (320–2400 pixels), and a typed six-digit hexadecimal Palette. Defaults are 18px, 1.5 and 960px. Arbitrary raw CSS is not accepted. CSS is scoped to the article/document classes and includes responsive and print rules; print CSS is not an image-layout engine.

The fontset package supplies independent byte slices for the four Go faces. Options.Fonts can explicitly replace any face with TTF/OTF bytes; omitted faces keep bundled defaults. Font data is validated with the patched SFNT parser and limited to 2 MiB per face. The renderer performs no font discovery, file access or network requests. CLI font paths are explicit capabilities:

--font-regular FILE  --font-bold FILE  --font-italic FILE  --font-mono FILE

Go fonts cover their supported Unicode repertoire; additional script coverage can require a suitable explicitly supplied font. Glyph coverage does not change source text preservation. The Go font license is retained in fontset/LICENSE-Go-Fonts.txt and embedded CSS. Assets: OmitFonts / --assets omit-fonts is an explicit option for fragments or hosts that already provide typography. It omits font payloads and permits generic browser fallback; the default always embeds all four faces.

Simple bounded numeric indentation/tag widths and vertical spacing are mapped to CSS. Roff expressions or unsupported units warn and use documented fallback spacing. Font family/style flags become semantic strong/em/code/small elements; preformatted spaces and newlines remain literal text.

Safety, diagnostics and file writes#

All source text, metadata, headings, notes and attributes are escaped. Raw roff HTML never becomes active markup. Link targets permit explicit HTTP, HTTPS, mailto recipients and same-document fragments; script, file, data, relative, credential-bearing and control-containing URLs are omitted with diagnostics. No images, scripts, includes or remote fonts are fetched. Normal external links remain links; activating them is a separate browser action.

Unsupported semantic blocks/escapes are visible literal fallback, with source positions in returned diagnostics and an accessible conversion-notes aside. Source diagnostics refer to the whole input, including for selected output. There is no perfect-groff-rendering claim. Strict mode rejects any diagnostics with ErrStrict before touching the writer. Output construction is buffered and bounded to 32 MiB by default (configurable downward); ErrLimit also leaves the writer untouched. A failure in the supplied writer may leave a partial stream.

The CLI sends diagnostics to stderr and keeps HTML stdout clean. Exit codes retain the earlier command contracts: 0 success/warnings, 1 malformed/strict failure, 2 usage/selection errors, 3 input/output/resource failures. Permissive malformed input can produce inspectable fallback HTML with exit 1. Strict, selection, font, input and render-budget failures do not replace output files.

-o - (default) writes stdout. -o FILE writes a bounded completed result to a same-directory temporary file, syncs/closes it, then renames it over the regular destination. It never deletes the old destination as a replacement fallback. Input-path/file-identity aliases, symlink destinations and nonregular outputs are rejected. New files use mode 0600; existing regular-file permissions are retained. Rename atomicity depends on the host filesystem. Unsupported platform replacements return an error; no non-atomic copy/delete fallback is attempted. Concurrent changes by other processes are outside this file API’s contract.

Compiler/dependency decision#

This phase raises the module minimum from Go 1.19 to Go 1.26, with the tested go1.26.10 toolchain directive. It introduces current x/image/x/net releases instead of older parsers affected by malicious-font allocation and HTML parsing failures. The CI setup follows go.mod. Parser and generated token APIs retain their previous signatures; older compilers are no longer a supported module build target. Headless builds remain pure Go and CGO-free. govulncheck was run on the resulting imports.

Fixtures and verification#

testdata/render/html/*.txtar contains source, optional renderer options, expected.html, diagnostics and expected-error text. Output is parsed with the current Go HTML parser and checked for semantic list structure, unique IDs, valid generated anchors and absence of executable/source-driven resource tags. The complete, section, node, empty, repeated-heading, Unicode/fragment, malformed/unknown, escaping/URL, strict and invalid-option cases are separate.

To keep archives readable, only font payloads in golden HTML are replaced with a face name, SHA256 and byte length. The harness independently decodes and compares every actual font with the bundled bytes before replacement. The real example HTML outside TXTAR retains its full embedded fonts. API/binary tests also cover custom fonts, writer failures, budgets, inherited selection context, atomic output, source aliases and preservation of existing files on failure. Normal tests never rewrite artifacts. Refresh explicitly, then review the diff:

go test . -run '^TestHTMLScenarios$' -update-html
go test . -run '^TestCLIScenarios$' -update-cli
go test ./...
go test ./renderhtml -run '^$' -fuzz '^FuzzHTMLSource$' -fuzztime=15s

This branch depends on #34 → #33 → #32 → #19. Existing parser/evaluator/include issues remain separate. Semantic conversion loops (#24) and paginated raster layout (#25) remain subsequent phases; no raster renderer is hidden in HTML.