SugarMarkdown
Markdown → ANSI renderer
Built on league/commonmark + SugarStyle. Word-wrap, OSC 8 hyperlinks, syntax highlighting, nine built-in themes plus custom JSON themes.
Install
composer require sugarcraft/sugar-markdown
Quickstart
use SugarCraft\Markdown\{Renderer, Theme};
// render()'s output deliberately carries no trailing newline — a
// one-chunk document renders through stream() to exactly those same
// bytes; the echo supplies its own "\n" as a second operand (echo
// itself appends nothing). write() and Writer follow the same law.
echo (new Renderer())->render(<<<MD
# Welcome
A few **bold** and _italic_ words, with `inline code` and a
[link](https://example.com).
- one
- two
- three
```php
echo "hello world";
```
MD), "\n";
// Custom theme from inline JSON; for the file variant
// (Theme::fromFile($path), optionally under a byte ceiling)
// see examples/custom-theme.php.
$theme = Theme::fromJsonString('{"heading1":{"bold":true}}');
echo (new Renderer($theme))->render("# Styled\n");
What's in the box
CommonMark parserHeadings, paragraphs, lists, blockquotes, code blocks, tables, rules, links, images, definition lists. List items always render tight — loose-list spacing is not honored, a dated port decision (2026-11). Images are text-fallback only (alt + URL, mirroring glamour pre-0.8); sixel/kitty embedding is candy-mosaic / candy-flip territory, not a markdown-layer capability. Raw HTML (inline + block) passes through as inert literal text with theme styling, control-stripped regardless of the sanitize flag; refused schemes never open an OSC-8 target — see the README Link safety policy.
Nine presets (notty aliases plain)ansi, plain, notty, ascii, dark, light, dracula, tokyo-night, pink.
new Renderer() with no theme lands on ansi() — a dated divergence (glamour defaults to its dark style); the one-line parity path is new Renderer(Theme::dark()). Theme::fromEnvironment() honors GLAMOUR_STYLE with NO_COLOR winning over every other input.Two theme schemas
Theme::fromJsonString('{"heading1":{"bold":true}}') takes this library's FLAT schema directly; a payload carrying a document block follows glamour's styles.json schema and routes through StyleGuide, whose whole surface is public (isGlamourSchema() / fromFile() / theme() / element() / chroma()) so you can drive the guide itself. Lenient keys, strict values: unknown keys are ignored, but bad hex ("#ff5f") or out-of-range ansi:99 throw InvalidArgumentException; Theme::fromFile($path, ?maxBytes) throws RuntimeException on an unreadable file or one past the byte ceiling; both decoders sweep every decoded string slot so a hostile theme prefix cannot smuggle a raw OSC/CSI.Word-wrapOff unless you call
withWordWrap($cols) — rendered lines follow the source (glamour defaults to 80; this port deliberately does not, dated 2026-11: width-managing consumers would get double-wrapped). Honors SGR + grapheme cluster widths. List items and blockquotes charge only their own indent or 2-cell bar, so nested lines fit the wrap width as in glamour. A whitespace-free run longer than four times the wrap width is packed into hard-break rows before the ANSI-aware wrapper sees it — byte-identical output, a 400 KB base64 blob costs its row count, not a per-cluster walk.OSC 8 hyperlinksOn by default; disable at the library with
withHyperlinks(false) (short alias hyperlinks(false)) for terminals that don't support them — the --no-hyperlinks spelling belongs to the candy-mdview CLI. The visible text is text (url) in both modes: the toggle adds or removes only the OSC-8 envelope. Email autolinks render the address hyperlinked to mailto: with no href suffix. withInlineTableLinks(false) is visual-only for OSC-8-capable terminals — a table-cell link loses BOTH the (url) suffix and the envelope, so avoid it for accessible output.Streaming
stream(iterable $chunks) yields rendered sections as markdown arrives; for every split of the same input bytes into string chunks, the stream equals render() byte for byte. Link reference definitions carry across sections; a section with an unresolved [..] is held back until a later definition names one of its left labels (an unrelated definition just moves a watermark — O(1) for every held section it cannot resolve), and each section is seeded only with the definitions its own bracket spans could look up. Writer::toPath()/toStream() is the push-side twin — feed()/close(), one flush per section, single-use; themes with document-scope post-processing or withPreservedNewLines(true) buffer and emit once — defersStreaming() reports which regime applies.Syntax highlightingCode blocks tokenized + colored — a curated subset: 16 languages (PHP/JS/TS/JSON/Python/Go/Bash/SQL/Rust/Java/C/C++/Ruby/YAML/HTML/CSS) and four token kinds against chroma's full lexer catalog; a fence naming anything else degrades to the plain code-block style, and a fenced body over
MAX_HIGHLIGHT_BYTES (1,000,000) refuses to try rather than stall.Bounded on hostile inputBlock nesting capped at
MAX_NESTED_BLOCK_DEPTH (32) — past the ceiling content still renders, decoration stops; sanitization is ON by default, the opt-out carries a loud name (withRawControlChars(true), alias withSanitize(false)); thematic rules clamp to the block's available width once a wrap width is set; and there is deliberately no source-size cap — output stays proportional, but put the intake guard on hostile stdin yourself. Theme files are code: pin style paths from operator config, never auto-load workspace-adjacent JSON.Every user-facing string goes through Lang::t() (src/Lang.php) with 16 locales shipped in lang/ — consumers such as candy-mdview surface localized messages like theme.read_failed.
Accessibility
- Color is the first thing to go —
Theme::fromEnvironment()letsNO_COLORwin over every other input, and the stockplain()/ascii()themes drop SGR color by construction (emphasis inascii()survives on bold/italic/underline alone). autotrustsisattyand nothing else — it never readsTERM, so aTERM=dumbterminal or a screen-reader pipe behind a PTY still receives full SGR fromGLAMOUR_STYLE=auto; pinGLAMOUR_STYLE=notty(orascii) explicitly for those pipelines.- Link text stays visible — the OSC-8 envelope wraps visible
text (url), so a non-clicking terminal loses nothing; the one exception iswithInlineTableLinks(false), which discards table-cell destinations entirely. - Alt text always renders —
keepsaltunconditionally, the same fallback posture refused-scheme links get via their visible(url)suffix. - Color-free is not glyph-free —
plain()andnotty()still draw the decorative glyphs (▎ ─ ☐ • …); every glyph is a constructor-settable string if you need pure-ASCII output. blinkis accepted, discouraged — it lives in the theme-JSON flag vocabulary for glamour parity; WCAG 2.2.2 asks you not to ship it.
Source & demos
- Source on GitHub
- Full README
- Runnable examples
- Originally inspired by glamour (Go); SugarCraft is developed as a native PHP project.
See also
- SugarStyle — styling primitives used by SugarMarkdown
- CandyMdview — CLI markdown viewer that uses SugarMarkdown for rendering
API
| Class | Method | Description |
|---|---|---|
| Renderer | new Renderer(?Theme, ?int $wrapWidth, bool $emitHyperlinks, ?string $baseUrl, bool $tableWrap, bool $inlineTableLinks, bool $tableColumnBudget, bool $preservedNewLines, bool $expandEmoji, bool $sanitize, bool $fenceColumnBudget, ?StyleSheet $styleSheetOverride, bool $lineNumbers) — 13 slots | Full configuration at construction (defaults: no wrap, hyperlinks on, sanitize on); also Renderer::ansi() / plain() / ascii() / fromEnvironment() |
| Renderer | static renderMarkdown(markdown, ?Theme) | One-shot convenience for ad-hoc rendering; for repeated renders build a Renderer and reuse it (parser cached per instance — sequential renders only, a Renderer is not reentrant) |
| Renderer | render(markdown) | Render markdown to ANSI string; a reused Renderer starts every render from a clean block stack |
| Renderer | stream(iterable $chunks): Generator / write(resource) / writer($sink) / renderSection() / defersStreaming() | Incremental section-by-section rendering, stream resources, the push-side Writer::toPath()/toStream() family, and the buffered-vs-streaming regime readback (parseSection()/renderParsedSection() are @internal) |
| Renderer | withTheme() / withSanitize() / withWordWrap() / withHyperlinks() / withBaseURL() / withTableWrap() / withInlineTableLinks() / withTableColumnBudget() / withFenceColumnBudget() / withLineNumbers() / withPreservedNewLines() / withEmoji() / withStandardStyle() / withStyleSheet() | Immutable option setters — every option also has a short alias without the with prefix (e.g. hyperlinks(false), styleSheet($sheet)); full descriptions in the README. withPreservedNewLines() keeps the source's blank-line runs between blocks; withLineNumbers() numbers highlighted fence lines (the gutter consumes the fence budget); withStandardStyle() re-picks a stock theme and throws naming Theme::names() on an unknown one |
| Theme | fromFile(path, ?maxBytes) / fromJsonString(json) / fromJson(path) | Load theme from a JSON file (RuntimeException on unreadable or over-ceiling — fromJson() remains as a deprecated alias) or from a string (InvalidArgumentException on malformed JSON or a non-object payload); lenient keys, strict values, every decoded string slot swept |
| Theme | ansi(), plain(), notty(), ascii(), dark(), light(), dracula(), tokyoNight(), pink() | Built-in theme presets; byName() returns ?Theme (null on unknown, which lands silently on ansi()) — and auto is deliberately not a byName slug, it is a fromEnvironment() channel, so a name lookup never probes the terminal; requireName() is the same refusal standalone |
| Theme | fromEnvironment(?default) / names() / mapStyles(callable $map): Theme | GLAMOUR_STYLE resolution with NO_COLOR precedence; the roster static; mapStyles() returns a new theme with every style slot mapped through the callable (used to project palettes, e.g. candy-code's Theme::pair) |
Demos.
VHS-recorded GIFs of every example shipped with the library. Regenerated automatically on every push to master that touches the source.
Render
The same document through four stock themes (ansi, dracula, tokyo-night, pink).