All 48 libraries

SugarMarkdown

Markdown → ANSI renderer

inspired by charmbracelet/glamour markdown ansi renderer themes

SugarMarkdown code coverage

sugar-markdown renders CommonMark into ANSI for the terminal: word-wrapped text, OSC 8 hyperlinks, syntax-highlighted code, and nine built-in themes plus JSON themes in both this library's flat schema and glamour's styles.json schema. It mirrors charmbracelet/glamour (Go) and is built on league/commonmark and sugar-style.

Install

composer require sugarcraft/sugar-markdown

Requires PHP 8.3 or newer. The sibling sugarcraft/* packages track dev-master, so mirror the monorepo's minimum-stability: dev with prefer-stable: true in your own root manifest. The HTML converter needs ext-dom, which is a suggestion rather than a requirement. Without it, HtmlToMarkdown::convert() returns null.

Quickstart

render($markdown), "\n";

// A flat JSON theme takes one or more style slots, and the rest keep their defaults.
$theme = Theme::fromJsonString('{"heading1":{"bold":true}}');
echo (new Renderer($theme))->render("# Styled\n"), "\n";

A renderer with no theme uses Theme::ansi(). That is a deliberate divergence from glamour, which defaults to its dark style. Use new Renderer(Theme::dark()) for the one-line parity path.

Concepts

A Renderer holds the options and the theme. It parses a document with the CommonMark parser, walks the blocks, and writes ANSI bytes. The option setters are immutable: each with*() returns a new renderer. A renderer is not reentrant, so use one per thread of work and reuse it across renders. Renderer::cached() hands back a shared instance for a theme and width, which suits a render loop.

A Theme is a set of styles for each block and inline element, plus a few scalar decorations such as heading prefixes and the image text. Every decoded string is swept for control bytes, so a theme file cannot inject a raw escape sequence. A theme file is code that the terminal runs, so load only files the operator pinned.

Streaming is the second mode. stream() yields rendered sections as the Markdown arrives, and for any split of the same input the joined output equals render() byte for byte. Writer is the push-side version for a sink you control.

Tasks

Render a file to the terminal

$renderer = (new Renderer(Theme::tokyoNight()))->withWordWrap(100);
echo $renderer->render(file_get_contents('README.md')), "\n";

Word wrap is off unless you call withWordWrap(), so rendered lines follow the source. Wrapping counts terminal cells, not bytes, and it honors SGR and grapheme clusters.

Pipe Markdown through a stock theme from stdin

cat README.md | php examples/stdin-stdout.php --theme=dracula

The example reads at most 1 MiB, and an unknown theme name prints a warning to stderr and falls back to ansi. A longer input is refused with exit code 2.

Take the theme from the environment

$renderer = new Renderer(Theme::fromEnvironment(Theme::dark()));

Theme::fromEnvironment() reads GLAMOUR_STYLE, and NO_COLOR wins over every other input. GLAMOUR_STYLE=auto trusts isatty only, so pin notty or ascii for a pipeline behind a PTY that should carry no color.

Stream a document as it arrives

use SugarCraft\Markdown\Renderer;

$renderer = new Renderer(Theme::dark());
foreach ($renderer->stream($chunks) as $section) {
    echo $section;
}

Each yielded section is a complete block-level unit. Link reference definitions carry across sections, and a section that refers to a definition not yet seen is held back until that definition arrives. A document that uses post-processing themes, or withPreservedNewLines(true), buffers and emits once. defersStreaming() reports which regime applies.

Fold sections under chosen headings

$renderer = (new Renderer(Theme::dark()))->withFolds([Renderer::headingId('Usage')]);

A folded heading keeps its line and a fold marker, and hides the blocks after it up to the next heading of any level. Heading IDs come from the rendered text, so Renderer::headingId() must see the same text the renderer does.

Convert fetched HTML to Markdown

use SugarCraft\Markdown\Html\HtmlToMarkdown;

$markdown = HtmlToMarkdown::convert($html, 'https://example.com/docs/', 'UTF-8');
if ($markdown === null) {
    // Fall back to the raw body. See the troubleshooting entry below.
}

Scripts, styles, navigation and other non-content subtrees are dropped whole. The result is then rendered by Renderer like any other Markdown.

API reference

Renderer

MethodDescription
__construct(?Theme $theme = null, ?int $wrapWidth = null, bool $emitHyperlinks = true, ?string $baseUrl = null, bool $tableWrap = false, bool $inlineTableLinks = true, bool $tableColumnBudget = false, bool $preservedNewLines = false, bool $expandEmoji = false, bool $sanitize = true, bool $fenceColumnBudget = false, ?StyleSheet $styleSheetOverride = null, bool $lineNumbers = false, array $folds = [])Full configuration at construction. The defaults are the ansi theme, no wrap, hyperlinks on, and sanitizing on. A zero or negative wrap width throws; use null to turn wrapping off
render(string $markdown): stringRender to an ANSI string. A reused renderer starts each render from a clean block stack
Renderer::renderMarkdown(string $markdown, ?Theme $theme = null)One-shot render. For repeated renders, build a renderer and reuse it
Renderer::cached(?Theme $theme = null, ?int $width = null)Shared renderer keyed by theme identity and width. Holds at most 32 entries, evicting the least recently used
Renderer::ansi() / plain() / notty() / ascii() / dark() / light() / dracula() / tokyoNight() / pink()Renderer on a stock theme
Renderer::fromEnvironment(?Theme $default = null)Renderer on the theme that Theme::fromEnvironment() picks
stream(iterable $chunks): Generator / renderSection() / defersStreaming(): boolSection-by-section output for a chunked input / render one section / whether the streaming regime buffers
write(string $markdown, mixed $output = STDOUT): int / writer(StreamSink $sink): WriterWrite a document to a stream resource / the push-side writer for a sink
withTheme() / withWordWrap(?int) / withHyperlinks(bool) / withBaseURL() / withTableWrap() / withInlineTableLinks() / withTableColumnBudget() / withFenceColumnBudget() / withLineNumbers() / withPreservedNewLines() / withEmoji() / withSanitize() / withRawControlChars() / withStandardStyle(string) / withStyleSheet()Immutable option setters. Each one also has a short alias without the with prefix, such as hyperlinks(false). withStandardStyle() throws, naming Theme::names(), on an unknown name
withFolds(array)Immutable option setter for the folded heading IDs. It has no short alias, so there is no folds() method; call withFolds()
Renderer::headingId(string $text): stringThe fold ID for a heading's rendered text

Theme

MethodDescription
Theme::ansi(), plain(), notty(), ascii(), dark(), light(), dracula(), tokyoNight(), pink()Built-in presets. notty() returns plain(), and ascii() keeps emphasis on bold, italic and underline alone
Theme::byName(string): ?Theme / requireName(string): ThemeLookup by slug, returning null for an unknown name. requireName() throws instead. auto is not a slug: it is the fromEnvironment() channel, so a name lookup never probes the terminal
Theme::catalog() / catalogByName(string): ?ThemeEvery stock theme plus the bundled solarized, monokai and github. The lookup ignores case, hyphens, underscores and spaces
Theme::names(): list / Theme::isStock(Theme $theme): boolThe stock roster / whether the instance is a memoised stock theme. The check is by identity (===), not by slug, so a theme built with with() or mapStyles() is not stock even when its values match. Use byName() to look up by slug
Theme::fromEnvironment(?Theme $default = null)Resolve GLAMOUR_STYLE, with NO_COLOR taking precedence
Theme::fromJsonString(string $json) / fromFile(string $path, ?int $maxBytes = null) / fromJson(string $path)Load a theme from JSON. A payload with a top-level document object routes through StyleGuide. The file variant throws RuntimeException when the file is unreadable or over the ceiling. fromJson() is a deprecated alias of fromFile()
mapStyles(callable $map): Theme / with(...)A copy with each style slot passed through a callable, or with selected slots replaced

StyleGuide

MethodDescription
StyleGuide::isGlamourSchema(array $decoded): boolTrue when the decoded JSON has a top-level document object. The flat schema has no such key, so the two never collide
StyleGuide::fromFile(string $path): selfRead a glamour style file. Throws RuntimeException for a missing file, a directory, an unreadable file, or one over MAX_CONFIG_BYTES (1,000,000 bytes), checked before the read
StyleGuide::fromJsonString(string $json): self / fromDecoded(array $decoded): selfParse a glamour document. InvalidArgumentException for malformed JSON or a top-level scalar. A top-level JSON array is accepted, because only Theme::fromJsonString() refuses lists; a StyleGuide built from an array carries no elements, so its theme keeps only glamour's default bold and italic and leaves every other slot plain. fromDecoded() lets a caller that already decoded the document avoid decoding it twice
element(string $name): ?array / chroma(string $token): ?arrayRaw primitive for an element block such as h1 or code_block, or for a chroma token such as Keyword. null when absent
indentToken(string $element = 'document'): stringThe indent_token literal for an element, passed through the same sweep as the affix slots
theme(): ThemeMaterialize a native Theme. Missing elements fall through to a plain style, except bold and italic, which keep glamour's attribute defaults

HtmlToMarkdown and UrlReference

ClassMethodDescription
HtmlToMarkdownconvert(string $html, string $baseUrl, ?string $charset = null): ?stringConvert HTML to Markdown. Returns null when the caller should fall back to the raw body. MAX_PARSE_BYTES is 512 KiB
UrlReferenceresolve(string $base, string $reference): stringRFC 3986 reference resolution. The converter uses it for every relative link, so fragments land on the document URL

Streaming, highlighting and helpers

ClassMethodDescription
SectionStreampush(string $chunk): array / finish(): array / preview(): arrayIncremental section splitter. Holds back a section until its link labels resolve
SectionScannerpush(string $chunk): array / openSection(): string / finish(): ?stringLine-level scanner that splits the input into candidate sections. Bounds the buffer one push keeps live at MAX_SECTION_BYTES (1 MiB)
WritertoPath(Renderer, string) / toStream(Renderer, resource) / feed(string) / close() / isOpen()Push-side streaming to a sink. Single use. Each section flushes once
StreamSinktoStream(resource) / toPath(string) / write(string): int / close()The output side of Writer
SyntaxHighlighterhighlight(string $code, string $language, Theme $theme, bool $lineNumbers = false): stringTokenize and color one fenced block. A body over MAX_HIGHLIGHT_BYTES (1,000,000) falls back to the plain code-block style
TokenWrapwrap(string $s, int $max): stringPack a whitespace-free run longer than four times the wrap width into hard-break rows. The output is byte-identical to the plain wrapper, and the run no longer costs a per-cluster walk
GithubEmojiMAP (constant)Shortcode to Unicode map, used when withEmoji() is on
Frontmattersplit(string $document): ?SplitSeparate the --- fenced metadata block from the body. Returns null when there is no complete block

Only methods declared in sugar-markdown/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.

SugarCraft\Markdown

Frontmatter final class

The --- fenced metadata block that can open a Markdown document (the convention Jekyll, Hugo and agent skill or rule files share), split off from the body.

MethodSummary
static split(string $document): ?SplitSplit $document at its frontmatter fence, or return null when it has no complete block.

GithubEmoji final class

GitHub emoji shortcode table, the corpus glamour's WithEmoji option consults upstream (charmbracelet/glamour pipes emoji expansion through the kyokomi/emoji GitHub shortcode map). Transcribed from the GitHub emoji cheat-sheet (1,837 codes, dataset as of 2026).

Lang final class

Per-library translation facade for sugar-markdown.

Renderer final class

Markdown → ANSI renderer. Parses input with league/commonmark and walks the resulting AST, producing styled strings via the Theme.

MethodSummary
__construct(?Theme $theme = null, ?int $wrapWidth = null, bool $emitHyperlinks = true, ?string $baseUrl = null, bool $tableWrap = false, bool $inlineTableLinks = true, bool $tableColumnBudget = false, bool $preservedNewLines = false, bool $expandEmoji = false, bool $sanitize = true, bool $fenceColumnBudget = false, ?StyleSheet $styleSheetOverride = null, bool $lineNumbers = false, array $folds = [])
static ansi(): self
static plain(): self
static ascii(): self
static notty(): self
static dark(): self
static light(): self
static dracula(): self
static tokyoNight(): self
static pink(): self
static renderMarkdown(string $markdown, ?Theme $theme = null): stringTop-level convenience: render Markdown with a one-shot Renderer instance and return the ANSI string. Mirrors glamour's package-level Render function.
static cached(?Theme $theme = null, ?int $width = null): selfThe shared renderer for $theme at $width columns, built on first use and returned as the same instance after that. A caller that renders on every frame (a TUI pane, a chat transcript) gets one parser, one Environment and one stylesheet for the whole session instead of paying for them per frame (rank 39). Null $theme means Theme::ansi(); null $width means no wrapping.
write(string $markdown, mixed $output = STDOUT): intRender Markdown and write the ANSI output straight to a stream (default STDOUT). Mirrors charmbracelet/glamour's package-level Write function.
stream(iterable $chunks): \GeneratorIncremental render channel: consumes Markdown input as a stream of string chunks and yields styled ANSI chunks as complete top-level block sections finish — the sugar-ecosystem port of glamour's render-then-print block-by-block intent, so a caller can forward bytes while the tail of the document is still arriving.
defersStreaming(): boolTrue when this renderer's document-scope post-processing (block prefix/suffix, indent, margin, preservedNewLines) is global by nature, forcing the streaming family (stream(), Writer) to buffer the whole document into its final chunk. Single source of the law so both channels can never diverge on the predicate.
writer(StreamSink $sink): WriterWrite-side counterpart of stream(): an object channel that accepts Markdown chunks through Writer::feed() and pushes every newly proven section into the sink immediately (write-through flush law). Shares the section stream and deferral predicate with this channel, so feed()/close() output equals stream() output for the same bytes.
renderSection(string $section): stringRender one section to its raw ANSI body WITHOUT the document-scope post-processing of render(): no rtrim, block prefix/suffix, indent, or margin — those wrap the assembled stream exactly once (and when they are configured at all, stream() falls back to buffering).
static fromEnvironment(?Theme $default = null): selfBuild a Renderer whose theme is selected by the GLAMOUR_STYLE environment variable. Unset or unrecognised falls back to $default — and to Theme::ansi() when no default was supplied (SM-S33: the caller's fallback was previously forced to be ansi, which could not be expressed through this door). Mirrors charmbracelet/glamour.RenderWithEnvironmentConfig.
withTheme(Theme $theme): self
withWordWrap(?int $cols): selfWrap paragraph + blockquote + list-item bodies at $cols cells. Headings, code blocks and tables are never wrapped (they carry their own width semantics; heading passthrough matches glamour). Pass null to disable wrapping; 0 or a negative count throws.
withHyperlinks(bool $on = true): selfEmit OSC 8 hyperlink escapes for [text](url) links so terminals that support it render the text as a real clickable link. When disabled (or the terminal doesn't support OSC 8), links degrade to styled text plus a trailing (url) suffix. Default: enabled.
withBaseURL(?string $url): selfBase URL prefixed onto relative [text](path) link / image targets. URLs that already have a scheme (http://, https://, mailto:, …) pass through unchanged. Mirrors charmbracelet/glamour.WithBaseURL.
withTableWrap(bool $on = true): selfWrap text inside table cells at the renderer's word-wrap width. Default off (cells render unwrapped, matching glamour's default). Mirrors charmbracelet/glamour.WithTableWrap.
withInlineTableLinks(bool $on = true): selfWhether links inside table cells render as inline [text](url) pairs (default — terse, scannable) or as full hyperlinks. When false, table cells suppress the trailing (url) and OSC-8 envelope since they bloat narrow columns — which discards the destination ENTIRELY: probe | [x](https://e.com) | with the flag off and every byte of the URL is gone from the output (no visible text, no envelope), not demoted to plain text. Glamour instead collects the destinations below the table as a footnote-style appendix; adopting that here is the owner-gated behaviour alternative (table bytes shift, a theme slot is needed), so the loss stands on the port's own terms — dated note 2026-11 (sugar-markdown-079). Mirrors charmbracelet/glamour.WithInlineTableLinks.
withTableColumnBudget(bool $on = true): selfBound a table's TOTAL rendered width by giving every column its share of the renderer's word-wrap width. Natural column contents are scaled down proportionally, floor one cell per column, until padding, border rules and all columns together fit withWordWrap($cols); each cell is then CLIPPED to its column budget. Default off — legacy withTableWrap per-cell full-width reflow is untouched.
withFenceColumnBudget(bool $on = true): selfClip fenced-code lines to the renderer's word-wrap width (the fence half of the bounded-geometry pair). withTableColumnBudget() bounds the one block kind whose geometry it can shrink by redistributing columns; a fence has no columns to shrink, so its long lines simply overflow the pane today. This is the block-clip the table budget leaves for fences: with the option on (default OFF — every existing byte snapshot holds), each rendered fence line is Width::truncateAnsi()-clipped at the current block stack's available width, on both the plain code-block and the syntax-highlighted paths. Content clipped here is the consumer's scroll/pager territory, exactly the bounded-geometry-now / full-content-later trade the column budget makes for tables. Indented code blocks are NOT touched — the entry scopes the FENCED half only.
withLineNumbers(bool $on = true): selfPrefix every line of a SYNTAX-HIGHLIGHTED fence with its 1-based number in a padded gutter (default OFF — every existing byte snapshot holds). Mirrors glamour's code-block line_number decoration; the gutter number rides the theme's muted comment slot and joins the code with SyntaxHighlighter::GUTTER_SEPARATOR — a measurable 1-cell box rule plus a space, never a bare tab (2026-11, SM-S34: candy-code's DiffGutter documents why a tab cannot survive a width-measured frame). The gutter interacts with withFenceColumnBudget(): numbers consume the budget — with both on, a clip can start eating the gutter itself once the number column exceeds the available width, so pair the flag with a wrap width that leaves room for it.
withStyleSheet(StyleSheet $sheet): selfUse a caller-supplied block cascade instead of StyleSheet::base() (M7). The sheet styles whole block kinds per nesting depth; the renderer seeds it fresh at each channel entry, so the default (null) keeps every existing byte. Mirrors charmbracelet/glamour's cascade option (element style maps).
withFolds(array $headingIds): selfFold the sections under the top-level headings named by $headingIds. A folded heading renders its own line, then a fold marker, and the blocks after it are hidden up to the next heading of any level. The hidden blocks are the body only: a heading nested under a folded one is a heading of its own and shows, so the fold never has to know about sections the stream family renders separately.
static headingId(string $text): stringThe fold ID for a heading whose visible text is $text: lowercase, each run of characters that are neither letters nor digits becomes a single hyphen, and the hyphens at both ends are trimmed. Two headings with the same text share an ID, so folding that ID folds both.
withPreservedNewLines(bool $on = true): selfPreserve consecutive blank lines in source markdown. By default CommonMark collapses runs of blank lines; with this on, every run of blank lines between two blocks survives into render()'s output at the position it held in the source (runs between the items of a list excepted: lists render tight — a dated port decision, see renderList()). Mirrors charmbracelet/glamour.WithPreservedNewLines. The stream family buffers while it is on (defersStreaming()).
withStandardStyle(string $name): selfPick a stock theme by name. Mirrors charmbracelet/glamour.WithStandardStyle. Accepts every name Theme::byName() recognises (the roster is Theme::names(), alias spellings included); unknown names throw InvalidArgumentException listing the valid ones.
withEmoji(bool $on = true): selfExpand :smile:-style emoji shortcodes in rendered text, AFTER parsing: code spans, fenced code and link destinations keep the source bytes (M1). Default off; on, every :shortcode: token in text rewrites through the built-in map. Unknown shortcodes pass through verbatim. Stream and render channels stay byte-identical because the substitution is byte-local to a text run.
withRawControlChars(bool $on = true): selfThe LOUD flag for the control-byte sweep: raw source controls pass through untouched, so every text byte of the document re-opens the ESC / CSI / OSC path to the terminal — a code span may inject an OSC-8 hyperlink or a window-title bait verbatim (FUZZ-03: hostile corpora probe exactly this). Only for trusted input where controls are the payload (e.g. re-emitting captured ANSI art).
withSanitize(bool $on = true): selfStrip C0 / ESC control bytes from source-derived text before emitting it — the safe default. Documented alias of withRawControlChars() read the other way: pass false and you are asking for raw ESC/CSI/OSC re-entry, so prefer the loud name at the call site when you genuinely mean it.
rawControlChars(bool $on = true): self
sanitize(bool $on = true): self
theme(Theme $theme): self
wordWrap(?int $cols): self
hyperlinks(bool $on = true): self
baseURL(?string $url): self
tableWrap(bool $on = true): self
inlineTableLinks(bool $on = true): self
tableColumnBudget(bool $on = true): self
fenceColumnBudget(bool $on = true): self
lineNumbers(bool $on = true): self
preservedNewLines(bool $on = true): self
emoji(bool $on = true): self
standardStyle(string $name): self
styleSheet(StyleSheet $sheet): self
render(string $markdown): string

StreamSink final class

Write-through byte sink for the streaming family (Writer, Renderer::writer()).

MethodSummary
static toStream(mixed $resource): selfAdopt a caller-owned writable stream resource. The resource is never closed by this sink.
static toPath(string $path): selfOpen (create/truncate) a file for writing. Every door fires before any content exists on disk: missing parent, unwritable parent or target, and the open-failure race net.
write(string $bytes): intWrite the bytes and flush them through before returning.
close(): voidClose the sink. Idempotent: a second call is a no-op. Owned handles (toPath) are closed; adopted resources (toStream) survive — only the sink itself becomes unusable, guarded by isOpen().
isOpen(): bool

StyleGuide final class

Parser + producer for Glamour STYLE JSON documents.

MethodSummary
__construct(public readonly string $blockPrefix = '', public readonly string $blockSuffix = '', public readonly int $documentIndent = 0, public readonly int $documentMargin = 0, public readonly array $elements = [], public readonly array $chroma = [])
static isGlamourSchema(array $decoded): boolTrue when a decoded JSON document carries the glamour signature — a top-level document OBJECT. The flat per-element colour map Theme::fromJsonString() consumes has no document key, so the two schemas never collide and callers may sniff with this predicate.
static fromFile(string $path): selfParse a glamour JSON file.
static fromJsonString(string $json): self
static fromDecoded(array $decoded): selfBuild from an already-decoded document — the path a caller that sniffed via isGlamourSchema() takes, so the file is decoded exactly once.
element(string $name): ?arrayRaw StylePrimitive for an element block, null when absent.
chroma(string $token): ?arrayRaw StylePrimitive for a chroma token, null when absent.
indentToken(string $element = 'document'): stringThe indent_token literal for an element (glamour's block_quote carries "│ ", stock code_block carries four spaces). The document block falls back to $documentIndent plain cells when it sets indent without a token; every other element answers '' when unset.
theme(): ThemeMaterialise the native Theme. Missing elements fall through to the plain Style — the same default Theme::fromJsonString() gives its flat schema — except bold / italic, which fall through to the actual SGR attribute glamour's stock styles give them.

SyntaxHighlighter final class

Lightweight regex-based syntax highlighter for fenced code blocks. Tokenises into four classes (comment / string / number / keyword) and styles each via the matching Theme slot. Falls back to the plain code-block style for unknown / empty languages.

MethodSummary
static highlight(string $code, string $language, Theme $theme, bool $lineNumbers = false): string

Theme final class

A Renderer stylesheet — one Style per Markdown element type. Themes are immutable; pick a built-in via ansi() / plain() or build a custom one with the constructor.

MethodSummary
static isStock(self $theme): boolWhether $theme is one of the memoised stock instances (identity, not value equality — a custom theme that happens to match a stock theme's bytes deliberately stays outside the render-bundle cache).
__construct(?Style $heading1 = null, ?Style $heading2 = null, ?Style $heading3 = null, ?Style $heading4 = null, ?Style $heading5 = null, ?Style $heading6 = null, ?Style $paragraph = null, ?Style $bold = null, ?Style $italic = null, ?Style $code = null, ?Style $codeBlock = null, ?Style $link = null, ?Style $blockquote = null, ?Style $listMarker = null, ?Style $rule = null, public readonly ?Style $keyword = null, public readonly ?Style $string = null, public readonly ?Style $number = null, public readonly ?Style $comment = null, public readonly ?Style $strike = null, public readonly ?Style $linkText = null, public readonly ?Style $image = null, public readonly ?Style $htmlBlock = null, public readonly ?Style $htmlSpan = null, public readonly ?Style $definitionTerm = null, public readonly ?Style $definitionDescription = null, public readonly ?Style $text = null, public readonly ?Style $autolink = null, int $documentMargin = 0, int $documentIndent = 0, public readonly int $listLevelIndent = 0, public readonly string $taskTickedGlyph = '☑', public readonly string $taskUntickedGlyph = '☐', public readonly string $horizontalRuleGlyph = '─', public readonly int $horizontalRuleLength = 40, public readonly ?Style $tableHeader = null, public readonly ?Style $tableCell = null, public readonly ?Style $tableSeparator = null, public readonly ?Style $imageText = null, public readonly ?string $headingPrefix = null, public readonly ?string $headingSuffix = null, public readonly string $paragraphPrefix = '', public readonly string $paragraphSuffix = '', public readonly string $headingCase = 'none', public readonly ?Style $orderedListMarker = null, public readonly ?Style $unorderedListMarker = null, public readonly string $orderedListMarkerFormat = '%d.', public readonly string $unorderedListMarkerGlyph = '•', public readonly string $tableCenterSeparator = '┼', public readonly string $tableColumnSeparator = '│', public readonly string $tableRowSeparator = '─', public readonly ?Style $definitionList = null, public readonly string $documentBlockPrefix = '', public readonly string $documentBlockSuffix = '')
static ansi(): selfDefault ANSI theme: bright accents on each heading, coloured code, etc.
static plain(): selfPlain-text theme: every Style is a no-op. Colour-free, not glyph-free — the decorative glyphs still draw (see README ## Accessibility). Useful for snapshot tests.
static notty(): selfThe theme fromEnvironment() picks when stdout is not a TTY. Mirrors charmbracelet/glamour.Notty style: indistinguishable from plain() but a separate factory so docs can refer to it by name. Use as the fallback in non-interactive scripts (CI logs, file dumps).
static ascii(): selfMonochrome ASCII theme — every Style emits at most bold / italic / underline / strikethrough (no colour; the strike element carries Style::strikethrough() for ~~text~~). Distinct from plain() (which is a total no-op) and notty() (an alias of plain). Use this when you want emphasis to survive a colourless terminal but not a totally bare one — e.g. printer-friendly logs, accessibility output, or test fixtures that should still differentiate headings from body text.
static names(): arrayThe canonical stock-theme roster — the single source every name list in this library derives from (byName(), requireName(), Renderer::withStandardStyle() errors). Alias spellings (tokyonight, dashed/underscored variants) are accepted by normalisation in byName() but not listed here.
static requireName(string $name): selfStrict sibling of byName(): the same normalised lookup, but an unknown name throws instead of returning null. The message carries the full valid-name list, derived from names().
static byName(string $name): ?selfLook up a built-in theme by glamour-compatible name. Returns null for unknown names so callers can fall back to their own default rather than receiving a surprising one. Names mirror the upstream glamour preset slugs (case-insensitive, hyphens normalised to none); the roster is names(). auto is deliberately NOT a byName slug — it resolves via fromEnvironment() only, so a pure lookup never probes the terminal.
static catalog(): arrayEvery named theme this package ships, keyed by slug: the stock roster (names()) followed by the bundled glamour-style files (solarized, monokai, github). Each entry is loaded once and the same instance is returned on every call.
static catalogByName(string $name): ?selfLook up a theme in catalog() by a loose name: case, hyphens, underscores and spaces are ignored, so Tokyo-Night, tokyo_night and tokyonight name the same theme. Null when nothing answers.
static fromEnvironment(?self $default = null): selfGlamour-compatible env-var auto-selection. NO_COLOR, when set to any non-empty value, wins first (M16): the no-color.org convention asks for plain output regardless of anything else configured, so plain() is returned even against a GLAMOUR_STYLE preset. Otherwise GLAMOUR_STYLE names a preset, and the literal string auto (matching glamour's convention) returns notty() when STDOUT is not a TTY and dark() otherwise. Falls back to $default (default ansi()) when no variable applies or the name is unrecognised. auto probes stream_isatty(STDOUT) only — it never reads TERM, so dumb terminals and screen-reader pipes behind a PTY must pin notty/ascii explicitly (README ## Accessibility). Note that new Renderer() keeps its own ansi() hard default — honouring the environment is exactly what this factory is for.
static dark(): selfDark-background optimised theme. Bright accents for headings, faint code backdrop, blue underlined links — matches glamour's Dark preset visually.
static light(): selfLight-background optimised theme. Darker accents and a no-bg code style.
static dracula(): selfDracula colour scheme — popular dark-purple palette.
static tokyoNight(): selfTokyo Night theme — dark blue/purple palette.
static pink(): selfPink — playful sweet palette.
mapStyles(callable $map): self
with(string $slot, Style $style): selfOne-slot modification idiom: return a copy of this theme with a single Style slot swapped, leaving every other slot (styles and scalars alike) untouched. This is the cheap path for "dark, but gold code" — the constructor's 15 required styles never need re-listing. $slot must name a Style-typed constructor slot; anything else throws with the valid roster.
static fromFile(string $path, ?int $maxBytes = null): selfLoad a theme from a JSON file, optionally bounded by $maxBytes. The JSON shape is one object per element, each carrying a subset of foreground / background (hex #rrggbb or ansi:N or ansi256:N) and the standard boolean attribute flags (bold, italic, underline, strike, faint, blink, reverse) — blink is accepted for glamour parity and discouraged for WCAG 2.2.2 reasons (README ## Accessibility). Missing elements default to the plain Style.
static fromJson(string $path): self
static fromJsonString(string $json): selfDecode a theme from JSON. Two schemas are accepted (M6):

Writer final class

Push-side object channel of the streaming family: feed Markdown chunks as they arrive, and every newly proven top-level section is rendered and written through the StreamSink immediately — write-through flush law, one flush per completed section, no buffering beyond the section stream's own hold.

MethodSummary
__construct(private readonly Renderer $renderer, private readonly StreamSink $sink)
static toPath(Renderer $renderer, string $path): selfWriter over a file sink. Construction fires every path door (missing parent, unwritable target, failed open) before anything renders.
static toStream(Renderer $renderer, mixed $resource): selfWriter over a caller-owned writable stream resource.
feed(string $chunk): voidAbsorb one Markdown chunk; newly completed sections are written through to the sink before this returns.
close(): voidDeclare end of document: flush the trailing partial section (terminal flush-partial), drop the final newline run exactly like render() rtrims it, and close the sink. Idempotent.
isOpen(): bool

SugarCraft\Markdown\Frontmatter

Split final class

One document split at its --- fence by \SugarCraft\Markdown\Frontmatter::split().

MethodSummary
__construct(public readonly string $meta, public readonly string $body, public readonly int $bodyOffset)

SugarCraft\Markdown\Html

HtmlToMarkdown final class

Converts an HTML string into Markdown, the default format of a fetched web page.

MethodSummary
static convert(string $html, string $baseUrl, ?string $charset = null): ?string

UrlReference final class

RFC 3986 reference resolution: a relative reference (a link's href, a redirect's Location) against the absolute URL it was found at.

MethodSummary
static resolve(string $base, string $reference): stringResolve $reference against the absolute $base.

SugarCraft\Markdown\Render

AutolinkMarker final class

Delegates to an autolink inline parser and tags the Link it appends with AutolinkMarker::DATA_KEY.

MethodSummary
__construct(private readonly InlineParserInterface $inner)
getMatchDefinition(): InlineParserMatch
parse(InlineParserContext $inlineContext): bool

BlockContext final readonly class

Immutable context record pushed onto the BlockStack when entering a block.

MethodSummary
__construct(public BlockKind $kind, public int $depth, public int $accumulatedIndent, public Style $cascadedStyle)

BlockKind enum

Kinds of blocks that can appear in a document tree.

Cases: Document · Heading · Paragraph · BlockQuote · List · ListItem · CodeBlock · Table

PHP also provides cases().

BlockStack final class

Stack of block contexts that tracks accumulated indent and margins for computing available width at any nesting depth.

MethodSummary
push(BlockContext $ctx): voidPush a context onto the stack.
pop(): BlockContextPop and return the topmost context.
peek(): ?BlockContextPeek at the topmost context without removing it.
peekKind(): ?BlockKindPeek at the topmost block's kind without removing it.
accumulatedIndent(): intThe sum of accumulated indents across all blocks in the stack. O(1) — maintained incrementally via $indentTotal.
marginCount(): intNumber of blocks in the stack that carry a margin (typically blockquotes and list items that add vertical spacing). O(1) — maintained incrementally via $marginCount.
availableWidth(int $wordWrap): intCompute available width for text inside the current block context.
isEmpty(): boolWhether the stack is empty.
depth(): intCurrent depth, counted from the Document root frame — a bare document under the root reads 1.

SectionScanner final class

Pull-agnostic section-splitting state machine for the streaming family (\SugarCraft\Markdown\Renderer::stream() and \SugarCraft\Markdown\Writer, both through SectionStream).

MethodSummary
push(string $chunk): arrayAbsorb one input chunk; answer every section the assembled bytes have newly proven complete (non-blank, in order).
openSection(): stringThe section still being read: everything after the last boundary push() reported, up to the last complete line. When push() has just closed a section, this starts with the heading line that closed it.
finish(): ?stringEnd of document: scan the unterminated trailing line (if any) and return everything not yet returned, or null when it holds no content.

SectionStream final class

Incremental section renderer shared by the streaming family (Renderer::stream(), \SugarCraft\Markdown\Writer) and by any caller that keeps a growing document's rendering between frames.

MethodSummary
__construct(private readonly Renderer $renderer)
__clone()
push(string $chunk): arrayAbsorb one chunk; answer the bodies of the sections it made final.
finish(): arrayEnd of document: answer every body not answered yet. Held sections are rendered with every definition the document has. Terminal: a stream is not fed after this.
preview(): arrayWhat finish() would answer right now, without disturbing this stream: the frames of a growing reply concatenate their released bodies with this preview and byte-match a full render of everything fed so far. Internally a clone finishes, so the held-section replay (M4) is the same code the real finish runs — no second implementation to drift. The open tail is re-parsed per call; past SectionScanner::MAX_SECTION_BYTES the tail is capped, so an unbounded preview ladder is bounded per frame by construction (SM-S15).

TokenWrap final class

Word-wrapping with a fast path for overlong tokens (SM-S22 mitigation).

MethodSummary
static wrap(string $s, int $max): stringWrap $s at $max cells, byte-identical to Width::wrapAnsi($s, $max).

SugarCraft\Markdown\Style

StyleCascade final class

CSS-like cascade helper for merging parent and child styles.

MethodSummary
static merge(Style $parent, Style $child): StyleMerge a child style into a parent style. Child wins on any explicitly-set attribute; rest inherits from parent.

StyleSheet final class

Cascading stylesheet that resolves effective styles per block kind and depth.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
static base(): selfFactory: build a base stylesheet with default per-kind styles.
for(BlockKind $kind, int $depth): StyleLook up the effective style for a block kind at a given depth.
withBlockKind(BlockKind $kind, Style $style): selfReturn a new StyleSheet with the given style set for a block kind at depth 0.
withBlockKindAtDepth(BlockKind $kind, Style $style, int $depth): selfReturn a new StyleSheet with the given style set for a block kind at a specific depth.
stylesFor(BlockKind $kind): arrayGet all styles set for a block kind (all depths).

Configuration

OptionTypeDefaultEffect
Wrap width?intnullWord-wrap column. null follows the source line breaks
HyperlinksbooltrueOSC 8 envelope around links. The visible text is text (url) in both modes
SanitizebooltrueStrips control characters from the output. Turning it off is withRawControlChars(true) or withSanitize(false)
Inline table linksbooltrueKeep the (url) suffix and the link envelope in table cells. Off is visual-only, and it drops both
Table wrapboolfalseWrap each table cell at the full wrap width. It does not bound the table as a whole
Table column budgetboolfalseClip table cells to one physical line each, so a wide table keeps bounded geometry
Fence column budgetboolfalseClip each fence line, highlighted or plain, to the available width
Line numbersboolfalseNumber the lines of a highlighted fence. The gutter uses the fence budget
Preserved newlinesboolfalseKeep the source's blank-line runs between blocks. Streaming buffers when this is on
EmojiboolfalseExpand :shortcode: to Unicode
Foldslist<string>[]Heading IDs to fold
Theme?ThemeTheme::ansi()The style set

Hard limits apply regardless of options. Block nesting is capped at Renderer::MAX_NESTED_BLOCK_DEPTH (32): past the ceiling content still renders, but decoration stops. A glamour document whose indent or margin exceeds Theme::MAX_DOCUMENT_DECORATION (256) is refused by StyleGuide with a named error, and Theme clamps such values at construction.

Keys and input

sugar-markdown handles no keys. It is a renderer, and a TUI host such as candy-mdview owns its own key bindings for scrolling and navigation.

Theme and styling

The nine presets are ansi, plain, notty, ascii, dark, light, dracula, tokyo-night and pink. notty is an alias of plain. The catalog adds solarized, monokai and github from the bundled themes/ directory.

Two schemas load through Theme::fromJsonString(). The flat schema is this library's own, and it lists style slots such as {"heading1":{"bold":true}}. A payload with a top-level document object follows glamour's styles.json schema and routes through StyleGuide, which reads the document block, the element blocks and the chroma tokens.

StyleGuide::theme() projects what the Theme can hold. It keeps the paragraph block_prefix and block_suffix, and drops the affixes on other non-document elements such as headings and block quotes. It also drops per-heading-level prefixes and chroma families beyond the four slots it has. Dropped keys stay readable through element() and chroma(), so a richer theme can use them later. Glamour's inline and block images style the alt text only, because the library does not embed images.

Custom theme example: start from a stock theme and swap individual style slots with Theme::with(), as examples/custom-theme.php does.

Examples

  • examples/render.php renders a sample document with a handful of stock themes. With GLAMOUR_STYLE or NO_COLOR set, it adds a section for Theme::fromEnvironment(). Run it with php examples/render.php.
  • examples/themes.php renders the same document under each colorful stock theme. Run it with php examples/themes.php.
  • examples/custom-theme.php starts from a stock theme and swaps individual slots with Theme::with(). Run it with php examples/custom-theme.php.
  • examples/stdin-stdout.php renders Markdown read from stdin, with an optional --theme= flag. Run it with cat README.md | php examples/stdin-stdout.php.

The examples read vendor/autoload.php, so run them from the library root after composer install.

Testing

cd sugar-markdown
composer install
vendor/bin/phpunit

The suite includes golden ANSI snapshots under tests/fixtures/, checked with sugar-testing's assertGoldenAnsi(). Golden files are create-only: UPDATE_GOLDENS=1 makes a missing fixture and never rewrites one that differs. To accept an intended change, delete the fixture and run the suite again. Locale parity is checked by LocaleParityTest, and the HTML converter has its own tests under tests/Html/.

Troubleshooting

Colors are missing in a pipeline

GLAMOUR_STYLE=auto trusts isatty and nothing else. A pipeline behind a PTY can still receive full SGR. Set GLAMOUR_STYLE=notty or ascii explicitly for those pipelines. NO_COLOR always wins over GLAMOUR_STYLE.

A long word overflows the wrap width

Wrapping counts terminal cells. A whitespace-free run longer than four times the wrap width is hard-broken before the wrapper sees it, so a long token is split rather than overflowing. Check that withWordWrap() was called, because word wrap is off by default.

The OSC 8 envelope is on by default and wraps the visible text, and the visible text is followed by (url) in both modes. A terminal without OSC 8 support shows the text and the URL and nothing is lost. withHyperlinks(false) removes only the envelope, so the (url) suffix stays. A refused scheme never opens an OSC 8 target.

A theme throws on load

Lenient keys and strict values. An unknown key is ignored, but a bad hex color such as #ff5f or an out-of-range ansi:99 throws InvalidArgumentException. A file that is unreadable or over the byte ceiling throws RuntimeException. Read the message, which names the field.

HtmlToMarkdown returns null

The converter returns null for empty input, when ext-dom is absent, for a body over 512 KiB, for a body the parser refuses, and for a body with no renderable text, such as a lone <script>. Fall back to the raw body in that case. The raw bytes include the text that the drop rule removed, so a caller that must never show raw content should not take the fallback.

Upstream mapping

charmbracelet/glamour (Go)sugar-markdown (PHP)
TermRendererRenderer, with the same wrap and hyperlink options under with*() names
styles.json style readerStyleGuide, with isGlamourSchema() routing from Theme::fromJsonString()
Stock style presets (dark, light, dracula, tokyo-night, pink, notty)Theme::dark(), light(), dracula(), tokyoNight(), pink(), notty()
GLAMOUR_STYLE resolutionTheme::fromEnvironment(), with NO_COLOR taking precedence
Chroma syntax highlightingSyntaxHighlighter, a curated subset of 16 languages
Not ported: image embedding (sixel, kitty)Images render as alt text and URL

The port mapping is in docs/MATCHUPS.md. The defaults that differ from glamour, namely ansi as the default theme and word wrap being off, are dated decisions recorded in the README.

Architecture

The pipeline is parse, scan, render. SectionScanner splits the input into candidate sections, and SectionStream holds back any section whose link references are not yet defined. The renderer walks the CommonMark blocks with a block stack, and TokenWrap and the ANSI-aware wrapper do the layout. Every decoded string from a theme passes through the sanitizer before it reaches the output.

Renderer-side limits are fixed in code: the block nesting depth, the section size, the highlight size and the theme decoration ceiling. The converter uses its own limit, a 512 KiB parse size checked before parsing. Input is not capped at the library, so a hostile stdin needs an intake guard in the host.

Changelog and versioning

sugar-markdown has no separate changelog file and is tracked from dev-master. Its history is the commit log of the sugar-markdown/ directory in the monorepo. Read the commit history for changes. Deprecated names such as Theme::fromJson() keep working as aliases.

  • sugar-style provides the Style values that themes are made of.
  • candy-mdview is the CLI markdown viewer built on this renderer.
  • sugar-core provides the color and sanitizing primitives.

Try the quickstart →

Demos.

VHS-recorded GIFs of the render and themes examples. The custom-theme and stdin-stdout examples have no recording yet. Regenerated automatically on every push to master that touches the source.

Render

Render

The same document through four stock themes (ansi, dracula, tokyo-night, pink).
Themes

Themes

Same document rendered through the six color themes (ansi, dark, light, dracula, tokyo-night, pink).