sugarcraft / candy-mdview
Markdown CLI viewer / pager composing SugarMarkdown + Viewport, modeled on charmbracelet/glow. 12 stock themes including an ascii accessibility tier, word-wrap, OSC 8 hyperlinks.
Requires
- php: ^8.3
- sugarcraft/sugar-async: dev-master
- sugarcraft/sugar-colorprofile: dev-master
- sugarcraft/sugar-core: dev-master
- sugarcraft/sugar-forms: dev-master
- sugarcraft/sugar-markdown: dev-master
- sugarcraft/sugar-style: dev-master
- symfony/console: ^6.4 || ^7.0
Requires (Dev)
- phpunit/phpunit: ^10.5
- sugarcraft/sugar-testing: dev-master
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-20 01:03:59 UTC
README
CandyMdview
Formerly published as
sugarcraft/sugar-glow(renamed 2026-10).Library: CandyMdview · package
sugarcraft/candy-mdview· binarycandy-mdview. Namespace changed:SugarCraft\Glow\→SugarCraft\MdView\. The old package name no longer receives updates — requiresugarcraft/candy-mdview, and renameSugarCraft\Glow\*imports toSugarCraft\MdView\*.
candy-mdview — a Markdown CLI viewer for PHP 8.3+ that composes SugarMarkdown (rendering) and SugarForms Viewport (the scrolling window over the rendered text). It is the native-PHP counterpart of the Go viewer glow: rendering, paging, themes, and live reload are ported; glow's directory browser, search, config UI, presentation modes, and glow 3.0's -a/--all, -l/--line-numbers, -n/--preserve-new-lines, -t/--tui, and --config knobs are not part of this tool.
Install
composer require sugarcraft/candy-mdview # binary lands in vendor/bin/candy-mdview
Prefer a single file? The rolling latest phar is rebuilt on every push to master that changes this library:
wget https://github.com/detain/sugarcraft/releases/download/candy-mdview/latest/candy-mdview.phar php candy-mdview.phar README.md
Verify the download against its published checksum — the .sha256 sidecar
ships next to the phar, and the .phar.commit sidecar names the exact tested
commit every dev build was cut from (both are published only from CI-green
pushes to master):
wget https://github.com/detain/sugarcraft/releases/download/candy-mdview/latest/candy-mdview.phar.sha256 sha256sum -c candy-mdview.phar.sha256
Just cloned the monorepo? No install step is needed for a quick look —
cd candy-mdview && php bin/candy-mdview README.md runs straight from the
tree; a root composer install additionally lands the binary at
vendor/bin/candy-mdview.
CLI
candy-mdview README.md # render to stdout (default) candy-mdview -p README.md # open in a fullscreen pager git log -1 --pretty=%B | candy-mdview -p # pipe stdin (pager keys still work — see Pager) candy-mdview --theme dracula README.md candy-mdview --width 80 --no-hyperlinks README.md candy-mdview --theme-config ./my-theme.json README.md candy-mdview https://example.com/README.md # fetch a URL, then render it candy-mdview docs/ # render docs/README.md (glow's directory form)
One document per invocation; to batch a tree, drive it from the shell:
find docs/ -name '*.md' -print0 | xargs -0 -n1 candy-mdview --no-ansi > combined.txt.
A directory argument resolves to one document: README.md, then
README.markdown, then index.md, then a single unambiguous *.md in that
directory — and STDERR names the chosen file. A directory with no match (or
several competing *.md files) refuses exit 2 naming what it searched;
recursive trees are not walked. The resolved path then rides the ordinary
file door: auto-reload and the status header stay available.
The file argument is a path, a directory (resolved as above) or an
http(s):// URL. A URL is fetched
with a 10 s transfer deadline, a 5-redirect cap and TLS verification ON; the
final answer must be 2xx; the body then passes the exact same size cap and
binary refusal as a local file, and its remote origin earns no special
trust — every hostile-byte lane the file doors close, HttpFetch closes too.
Auto-reload and the file · scroll% status header are local-file features:
a pager opened on a URL watches and names nothing.
Flags:
--theme {ansi|ascii|plain|notty|dark|light|dracula|tokyo-night|pink|solarized|monokai|github}— picks a SugarMarkdown preset; aliasesno,auto-no,tokyonightare accepted —noresolves toplain,auto-notonotty,tokyonighttotokyo-night— and names match case-insensitively with_accepted in place of-(DRACULAandTokyo_Nightwork). Passautoto run the implicit ladder explicitly. Each built-in name maps one-to-one onto the same-named SugarMarkdown preset (Theme::ansi(),Theme::notty(),Theme::dracula(), …). Stock names resolve through SugarMarkdown'sTheme::byName(), so they never read a JSON file;solarized,monokai, andgithubare the three bundled JSON themes, read throughTheme::catalogByName()fromvendor/sugarcraft/sugar-markdown/themes/. The phar build refuses a vendor tree that lacks those files. candy-mdview keeps byte-identical copies inthemes/becauseThemeLoadTestandPharBuildScriptTestpin them; no runtime path reads that directory. The three tiers: ansi is the terminal-native palette, ascii keeps structure — bold/italic survive, color does not — and plain is undecorated bytes. With--themeomitted, the numbered color walk below picks the tier: ansi when the stream is decorated and color-capable, ascii when it is decorated but colorless, and plain when it is undecorated (--no-ansi, or stdout is not a terminal and nothing forces decoration). Conversely, forcing decoration (--ansi/CLICOLOR_FORCE/FORCE_COLOR) still emits color on a pipe, exactly like a terminal. To compare the palettes side by side, run./examples/render-readme.sh [file]over this README.--style/-s— glamour-compat alias for--theme: it takes theme names, not style files (JSON goes through--theme-config). When both flags are given and name different themes,--stylewins and anote: --style … overrides --theme …line lands on stderr.--version— handled by the Symfony Console application (no row in the command's own flags). A release-tagged phar reports its release stamp, and a rolling dev phar reportsdev-<short commit>, so two dev builds differ by commit. A bare checkout orvendor/bin/candy-mdviewreports the fallback0.1.0, and so does a phar stamped only with thedev-buildsentinel.--theme-config <path>— load a custom JSON theme (up to 1 MB). Two shapes are detected automatically: a glamour config (top-level"document"block with nested element/chroma maps — chroma is the Go syntax-token library glamour styles through, so its map is keyed by token family — the shape of charmbracelet/glamour's style files) is loaded by sugar-markdown'sStyleGuideonto a SugarMarkdownTheme, behind one refusal candy-mdview keeps in front of it:GlamourDecorationGaterejects any document or paragraphblock_prefix/block_suffixthat is not inert whitespace (glamour.decoration_unsafe), and reads a non-string affix as empty. Every other field followsStyleGuide. Output changes for edge glamour files (owner decision, P1-12c-mdview, option b):uppercaseorlowercaseon a heading block now sets the heading case,inline_imageandblock_imagenow style the image alt text, and a flag set to"false","no"or"off"(any letter case), to a non-zero float, or to a non-empty array now reads as off. The full list is under "Accepted edge changes" below. A file that uses none of these renders as before, and the three bundled themes and every built-in name render byte-identically. The legacy flat color map goes throughTheme::fromJsonString. (Theme::fromJsontakes a path and is used for the three bundled JSON themes.) In the flat shape the accepted top-level keys are exactly theThemeelement slots —heading1…heading6,paragraph,bold,italic,code,codeBlock,link,blockquote,listMarker,rule,keyword,string,number,comment,strike,linkText,image,htmlBlock,htmlSpan,definitionTerm,definitionDescription,text,autolink— each one a style object;themes/solarized.jsonis a worked flat starting point. Given with--themeas well, it replaces the named preset. The path must be a regular file — a directory, FIFO or device refuses under the same heading instead of warning, reading unbounded, or hanging — and the payload must satisfy one of the two shapes: scalars, JSON lists and objects that match neither schema (a typo'd top-level container) refuse with exit 2 rather than silently rendering the stock theme.--width/-w <N>— word-wrap paragraphs, blockquotes, and list bodies at N columns (1–9999).0disables wrapping; unwrapped lines are truncated by the pager, so scroll horizontally withh/l. Omitted, the wrap follows the terminal: stdout output wraps atmin(terminal width − 2, 80)and the pager wraps at the live column count — and re-wraps the document when you resize. Naming--widthpins the column count instead: resizing then only moves the clip window. Anything non-numeric is a usage error.--no-hyperlinks— suppresses the OSC 8 hyperlink envelopes (the escape wrappers that make links clickable). They are emitted for terminal output by default, and also into redirected output when decoration is forced (--ansi/CLICOLOR_FORCE/FORCE_COLOR) — forcing decoration means full decoration. Labelled links always show their visibletext (url)tail; plain autolinks andmailto:targets render the URL itself as the text, so the address stays visible either way.--show-front-matter— print a leading YAML front-matter block verbatim before the rendered document. The block is never rendered either way: a document that opens with a---(or...) fenced metadata block loses the fence before Markdown parsing, because the closing rule would otherwise turn the last metadata line into a setext heading (title: My Docfirst-block garbage on the Jekyll/Hugo/GitHub slice of the corpus). The rule applies to every door — file, directory-resolved README, stdin, fetched URL — and to every pager reload, so the metadata stays metadata for the whole life of the frame.--pager/-p— open in a fullscreen pager. Requires a real terminal: when neither stdout is a terminal nor/dev/ttycan be opened, the run refuses with exit code 2 naming stdout rendering as the replacement (drop-p) — the pager arms the alt screen and mouse tracking the moment it starts, so a non-terminal run would paint escape sequences into your redirect target instead of a screen.--ansi/--no-ansi— force / forbid decorated output.
Color runs through three decisions, in order:
- Explicit theme.
--theme,--style,--theme-config— and theMDVIEW_THEME/ config-file layers under the flags — name a theme, and a named theme renders its colors everywhere: an explicit--theme darkpiped into a file still emits SGR. The nameautosteps out of this decision and reruns the implicit walk. - Implicit tier. With no explicit name, the decorated verdict of
decision 3 and the capability facts pick the tier: on a decorated stream,
ansi when the terminal answers color-capable and ascii when it
answers colorless (
TERM=dumb,NO_COLOR,CLICOLOR=0all count as colorless); on an undecorated stream, plain — undecorated bytes. - Decoration gate. One boolean says whether the stream receives terminal
decoration:
--no-ansicloses it,--ansiopens it, and otherwise only affirmative environment verdicts act —CLICOLOR_FORCEorFORCE_COLORat any value other than0opens it even on a pipe. A non-emptyNO_COLOR— includingNO_COLOR=0per the spec — orCLICOLOR=0forces nothing closed here: it answers decision 2's color-capability question only, so on a terminal the gate still opens. An emptyNO_COLOR=takes no position anywhere. The terminfo probe is not consulted at the gate.
The gate's verdict also decides the OSC 8 hyperlink envelopes: no envelopes
on an undecorated stream or under --no-hyperlinks, and forced decoration
emits them even into a pipe or file — forcing decoration is forcing all of
it. An explicit theme changes the palette, never the envelopes.
Two consequences worth knowing: NO_COLOR on a terminal selects the ascii
theme but does not silence the link envelopes — the gate never reads
NO_COLOR; and --no-ansi on a color-capable terminal yields the plain
tier, not ascii. A value CLICOLOR or NO_COLOR cannot act on never
throws: it takes no position and the walk decides. FORCE_COLOR=banana is
the different shape — any non-0 value opens the gate.
Pager
The pager reads the keyboard from /dev/tty, so some-command | candy-mdview -p
stays scrollable; the document itself can still come from stdin. It reflows
when you resize the terminal, and a document taller than the screen grows a
█ scrollbar along the right edge — a short document renders without it. When
opened on a file, the header row
shows file · scroll% (plus ↻N after N auto-reloads); a stdin pager has no
header row. Read aloud, the segments are file name, scroll percent, reload
count — the · only separates, and ↻! means the last change was refused
and the frame is stale. On locales that do not declare UTF-8 (C/POSIX or an
explicit ISO-8859-style charset) the same row is written in pure ASCII:
file 42% (r3), (r!) when refused.
| Key | Action |
|---|---|
↑ / k |
line up |
↓ / j |
line down (Alt+j too) |
| mouse wheel | 3 lines per notch in either direction |
PgUp / b |
page up (Ctrl+B too) |
PgDn / space / f |
page down |
Ctrl+U / Ctrl+D |
half page |
Home / g |
top |
End / G |
bottom |
← / h, → / l |
scroll horizontally (no-wrap mode) |
r |
force a reload of the watched file (unmodified only) |
q / Esc / Ctrl+C |
exit (Shift+q, Alt+q and Ctrl+q do not) |
? |
show or hide a one-row strip condensing the keys above (unmodified only) |
Only an unmodified q quits. The scroll letter keys are the exception: they
are matched on their rune alone, so they fire even with modifiers held —
which is why Ctrl+B and Alt+j share the table rows above with plain b
and j, while Ctrl+U / Ctrl+D are distinct bindings, the deliberate
half-page chords. Unmodified ? toggles a one-row help strip that carries
these chords in condensed form — while shown it replaces the first body row,
so the frame never grows; it degrades through shorter tiers on narrow boxes
so ? toggle always survives, and on locales that do not declare UTF-8 it
is written in pure ASCII.
When the pager is opened on a file (not stdin) it auto-reloads: a fixed
0.5 s tick runs one non-blocking (mtime, size) probe through
FileWatcher::pollTuple(); a tick that finds a differing tuple consumes the
baseline and queues the read and re-render for the FOLLOWING tick — save
bursts coalesce into one render of the newest bytes and the pager never sits
on a parse while your keystrokes queue. A delete-and-recreate keeps the last
good frame until the recreated (mtime, size) differs from the baseline. A
rewrite preserving both second-granularity mtime and byte size stays
invisible to the tuple; press r to force a reload in that case. Refused
replacements (oversize, device swap, binary) and throwing re-renders never
blank the screen: the last good frame stays and the header marks ↻! until
the next accepted reload.
The pager is fully keyboard-driven: the alt screen and mouse tracking are
armed unconditionally, but every mouse action has a key twin in the table, so
a basic terminal that cannot answer either loses nothing usable — with
TERM=dumb (or no mouse support) prefer the plain stdout mode and drop -p
if you would rather keep your own scrollback.
Configuration
Persistent preferences live in mdview.json under $XDG_CONFIG_HOME/mdview/
(without that variable, ~/.config/mdview/mdview.json). MDVIEW_CONFIG
overrides the path outright — and an explicitly empty MDVIEW_CONFIG=
skips file lookup entirely. Every setting resolves flag > environment >
file > built-in default, independently: MDVIEW_THEME, MDVIEW_WIDTH
(0–9999, where 0 is the explicit no-wrap opt-out), and MDVIEW_PAGER
(1/0, true/false, yes/no). A worked file:
{
"theme": "dracula",
"width": 100,
"pager": true,
"keymap": { "quit": "x", "reload": "ctrl-r" }
}
style is accepted as the file's twin of --style (inside the file, as
between the flags, style wins over theme — and says so on stderr). The
keymap block may remap the two chords the pager itself owns — quit and
reload — as a bare rune ("x", unmodified key) or an explicit ctrl- /
alt- chord; navigation keys belong to the Viewport and always answer to
the table above, and Esc / Ctrl+C quit regardless of any map. A file
that exists must be honest: a non-file, an over-cap payload (64 KiB),
malformed JSON, an unknown key, or a mistyped value refuses with exit
code 2 naming the path — nothing you wrote is ever silently ignored.
Accessibility
Color is an environment fact before it is anything else, so reduced-color
setups need no special build: a non-empty NO_COLOR, CLICOLOR=0, or
TERM=dumb drops the implicit theme to ascii on a terminal — structure
survives, hue does not — and a stdout that is not a terminal lands on
plain bytes with no decoration at all. The ascii, plain, dark, and
light themes are the high-contrast picks.
Screen-reader, braille, and copy-paste recipe — one plain stream, no escape sequences anywhere in it:
candy-mdview --no-ansi --no-hyperlinks notes.md
--no-ansi closes the decoration gate (no SGR anywhere on the stream), and
--no-hyperlinks suppresses the OSC 8 link envelopes even where decoration
stays open. Reduced motion is the default posture: nothing animates — the
pager jumps to its target in a single frame, and auto-reloads land on the
fixed 0.5 s tick rather than a transition.
Exit codes & errors
| Code | Meaning |
|---|---|
| 0 | rendered successfully (an empty file renders blank) |
| 1 | input faults caught at the console layer — unknown option, more than one file argument, or the space-separated --width -5 (the = form reaches the command and exits 2) — printed with the usage dump; runtime failures |
| 2 | usage error — bad theme, unreadable/oversized theme config, missing or unreadable file, a directory argument with no resolvable document, non-text (binary) input, a document over 64 MiB, a refused or failed URL fetch (transport, non-2xx answer, oversize body), invalid --width, or no input (no file argument while stdin is a terminal, or an empty stdin) |
Usage errors print a specific message to stderr (open notes.md: no such file,
no Markdown document in docs/: looked for …, …); file paths and option values coming from
argv are sanitized before display, so a crafted name cannot inject escape
sequences or restyle the message. The rendered document is written raw:
Symfony's output formatter never interprets <tags> inside your Markdown.
Run candy-mdview --help for the flag list; a console-layer fault prints the
same help beneath its error.
Trust boundary
Documents are untrusted input. Escape sequences, control bytes, and OSC
payloads are stripped on output, per rendered element — a hostile .md
cannot move the cursor or change terminal colors. OSC 8 hyperlink URLs pass
a refused-scheme gate in SugarMarkdown: javascript:, data: and
vbscript: never open a link target (their text and (url) suffix still
render, visible and inert). Every other scheme — file: and mailto:
included — reaches the terminal's opener unfiltered, so treat a hostile
document's non-http(s)/mailto links the way you would treat raw terminal
input. See the fleet
trust boundary.
--theme-config files are untrusted input too, and the glamour adapter treats
them that way at its parse door: the document/paragraph decoration slots
(block_prefix / block_suffix) accept only inert whitespace, so a style
file cannot inject title-setting escapes, arbitrary SGR, or forged hyperlink
envelopes into every frame; document.indent and document.margin refuse
values beyond Theme::MAX_DOCUMENT_DECORATION (256) instead of multiplying
into a memory blowup. Both refusals name themselves and exit 2. Colour and
spacing values that pass are painted verbatim, so style files should still
come from sources you trust.
Output languages
The CLI answers in 15 languages plus English (16 locale files). Selection
follows the standard chain — LC_ALL beats LC_MESSAGES beats LANG; an
unset, empty, C or POSIX value takes no position, and the default is
English. --help and the document itself stay as-is, as do the two
pre-autoload bootstrap refusals in bin/ (missing phar vendor, and no
autoloader found), which fire before the catalogue is even reachable.
Library API
Beyond the CLI, candy-mdview exposes three public pieces for integrating its
behavior into other PHP projects: the pager's TEA model (a The-Elm-
Architecture update loop, MdViewModel) and
two utility helpers (FileWatcher, GlamourDecorationGate). The deprecated
RenderCommand::set*Callback() test seams are deliberately not part of the
supported API; they remain for the package's own tests, and any integrator
using them does so at their own risk. The document input door is the
private readDocument(), which every real input path shares with the
DocumentGate size and binary guards. Visual width measuring
(CJK/emoji) is delegated to SugarCraft\Core\Util\Width in sugar-core —
use that directly; this package ships no local width helpers.
MdViewModel
The pager's Model (init/update/view over sugar-core's Program): fromContent()
builds it from already-rendered text at a given size, withDocument() prepends
the status header row (name · scroll% · reload marker), withWatch() arms
auto-reload from disk via the FileWatcher tuple API, and isWatching()
reports whether a watch is armed. Driving it is a few lines — render, wrap
the model in a Program, run:
use SugarCraft\Core\MouseMode; use SugarCraft\Core\Program; use SugarCraft\Core\ProgramOptions; use SugarCraft\MdView\MdViewModel; use SugarCraft\Markdown\Renderer; $rendered = (new Renderer())->withWordWrap(80)->render((string) file_get_contents('notes.md')); $model = MdViewModel::fromContent($rendered, 80, 24)->withDocument('notes.md'); (new Program($model, new ProgramOptions( useAltScreen: true, hideCursor: true, catchInterrupts: true, mouseMode: MouseMode::CellMotion, openTty: true, )))->run();
FileWatcher
File watching via (mtime, size) tuple polling — works cross-platform with no extensions.
use SugarCraft\MdView\FileWatcher; // Stateless tuple API (drives the pager's auto-reload): $base = FileWatcher::snapshot($path) ?? [0, 0]; // [mtime, size] $changed = FileWatcher::pollTuple($path, ...$base); // new tuple or null // Instance API: $watcher = new FileWatcher('/path/to/file.md'); $lastMtime = (int) @filemtime('/path/to/file.md'); // or the last value you recorded if ($watcher->hasChangedSince($lastMtime)) { // re-render }
The pager's reload path uses the tuple API directly on the model's fixed
tick: FileWatcher loops, sleeps and backs off nothing — the old generator
watch() and its unwired idle-backoff ladder were deleted with it, leaving
one watcher per session (the ReloadTickMsg chain in MdViewModel).
Glamour style files
Glamour style JSON (a "document" block, per-element StylePrimitive maps,
and a chroma token map) is loaded by sugar-markdown's StyleGuide, which
projects it onto SugarMarkdown's Theme. The --theme-config path sniffs the
shape with StyleGuide::isGlamourSchema(), runs GlamourDecorationGate::admit()
over the decoded document, and then calls StyleGuide::fromDecoded() and
theme(). The gate's one refusal is the whitespace-only affix law. The loader
refuses document indent or margin values over
Theme::MAX_DOCUMENT_DECORATION by name, and the file is read under the 1 MB
cap StyleGuide::MAX_CONFIG_BYTES.
Element blocks the Theme has no slot for stay unmapped, and that is deliberate:
the image, table_header, table_row, table_cell and table_separator
styles, line-control block_prefix / block_suffix on non-document and
non-paragraph elements, per-heading-level prefixes, and chroma families beyond
the four slots. Mapping the table and image blocks would change what existing
style files render.
Accepted edge changes (P1-12c-mdview, owner option b). The byte-identical rule is waived for these edge files only, and each change is listed here:
uppercase/lowercaseon a heading block now setsheadingCase. The former door ignored both flags.inline_image/block_imagenow style the image alt text (imageText). The former door dropped them.- A boolean flag (
bold,italic,underline,strikethrough,faint) now reads as off for the string"false","no"or"off"in any letter case, for a non-zero float such as1.0, and for a non-empty array. The former door tested!empty(), so each of these read as on. Booleans, integers,"","0"and the other strings read as they did before. The headinguppercase/lowercaseflags use the same reading, which the former door ignored altogether.
Together with the three JSON presets in themes/, this is the only way to
extend the fixed built-in theme set. GlamourDecorationGateTest pins the gate
and the path through StyleGuide.
Shared foundations
candy-mdview declares its direct dependencies: sugar-markdown (renderer +
themes), sugar-forms (Viewport), sugar-core (TEA runtime, width,
sanitize), sugar-colorprofile (terminal capability probing),
sugar-style, sugar-async (the bounded await on the color probe), and
symfony/console (^6.4 || ^7.0) — the app is a
Symfony Console program (Application extends
Symfony\Component\Console\Application; the whole flag and exit-code surface
depends on it). The command's private static terminalSupportsColor() consults
the environment verdict first, then awaits
\SugarCraft\ColorProfile\AsyncProbe::report() on the shared loop, and falls
back to true (assume color) if the probe throws or the await times out — ensuring graceful degradation
on Windows, over SSH, and in old terminals.
Snapshot tests
Render output is covered by golden-file snapshot tests. Golden files live
in tests/fixtures/ with a .golden extension and are compared against
actual ANSI byte output via SugarCraft\Testing\Snapshot\Assertions::assertGoldenAnsi().
The recorder is create-only: an existing golden that differs never gets
rewritten. To re-record after intentional output changes, delete the golden
file first:
rm tests/fixtures/<name>.golden UPDATE_GOLDENS=1 vendor/bin/phpunit
Testing
cd candy-mdview && composer install && vendor/bin/phpunit
Credits & inspiration
Originally inspired by the Go Charm ecosystem (notably glow); SugarCraft is developed as a native PHP project.

