All 22 apps

CandyMdview

Markdown CLI viewer + pager

inspired by charmbracelet/glow markdown viewer pager

CandyMdview code coverage

candy-mdview is a Markdown viewer for the terminal. It renders a file, a directory's README, an http(s):// URL or stdin to ANSI text, or opens the result in a fullscreen pager that reflows on resize and reloads when the file changes on disk. Rendering comes from SugarMarkdown, scrolling from the SugarForms Viewport. The tool is the native-PHP counterpart of charmbracelet/glow: rendering, paging, themes and live reload are ported, while glow's directory browser, search, config UI and presentation modes are left out.

Install

composer require sugarcraft/candy-mdview   # binary lands in vendor/bin/candy-mdview

Requires PHP 8.3 or newer. For a single file, the rolling latest phar is rebuilt on every push to master that changes the library. Verify it against the .sha256 sidecar before running it:

wget https://github.com/detain/sugarcraft/releases/download/candy-mdview/latest/candy-mdview.phar
wget https://github.com/detain/sugarcraft/releases/download/candy-mdview/latest/candy-mdview.phar.sha256
sha256sum -c candy-mdview.phar.sha256
php candy-mdview.phar README.md

The .phar.commit sidecar names the exact tested commit each dev build was cut from. Both sidecars are published only from CI-green pushes to master. A monorepo checkout needs no install step for a quick look: cd candy-mdview && php bin/candy-mdview README.md runs straight from the tree.

Quickstart

candy-mdview README.md                        # render to stdout (the default)
candy-mdview -p README.md                     # open in a fullscreen pager
git log -1 --pretty=%B | candy-mdview -p      # pipe stdin; the pager keys still work
candy-mdview --theme dracula README.md
candy-mdview --width 80 --no-hyperlinks README.md

Stdout mode is pipe-friendly and exits cleanly. Pager mode arms the alternate screen and mouse tracking, so it needs a real terminal. Stdin can feed the pager because the keyboard is read from /dev/tty.

Concepts

Every input is a document. A file path, a directory (resolved to one README), an http(s):// URL and stdin all pass the same gate: DocumentGate refuses non-text (binary) input and anything over 64 MiB, and a leading YAML front-matter block is removed before Markdown parsing, whichever door the bytes came through. A URL is fetched with a 10 second transfer deadline, at most 5 redirects, TLS verification on, and a 2xx final answer. Its remote origin earns no special trust.

The rendered text then goes one of two ways. Stdout mode writes it and exits. Pager mode hands it to MdViewModel, a Model whose body is a SugarForms Viewport, so the view is a window onto the text rather than a copy of it. Resizing re-wraps the document when no --width is pinned.

Output is always sanitized. SugarMarkdown strips escape, control and OSC bytes from the rendered output, and this tool never turns that default off. A hostile Markdown file therefore renders as data: it cannot move the cursor or restyle the stream.

Input doors and their limits

  • File: a regular file. A directory, FIFO or device is refused with exit 2.
  • Directory: resolves to README.md, then README.markdown, then index.md, then a single unambiguous *.md. Recursive trees are not walked, and several competing candidates refuse with exit 2.
  • URL: fetched as above. Auto-reload and the file · scroll% header are local-file features, so a pager opened on a URL watches nothing.
  • Stdin: the default when no file argument is given. The pager reads keys from /dev/tty and has no header row.

Tasks

Read a file in the pager and let it reload on save

candy-mdview -p docs/guide.md

A fixed 0.5 second tick (MdViewModel::RELOAD_POLL_SECONDS) compares the file's (mtime, size) pair against the last one seen. A change queues one re-read and re-render for the following tick, so a burst of saves coalesces into one render of the newest bytes. A rewrite that keeps both the second-granularity mtime and the byte size is invisible to that check. Press r to force a reload in that case.

Pin the column width

candy-mdview --width 72 CHANGELOG.md   # wrap at 72 columns, resizing moves only the clip window
candy-mdview --width 0 table-heavy.md  # no wrap: long lines are cut, and the pager scrolls them sideways

Without --width, stdout wraps at min(terminal width − 2, 80) and the pager wraps at the live column count. --width accepts 1 to 9999; 0 disables wrapping, and anything non-numeric is a usage error.

Load a custom theme file

candy-mdview --theme-config ./my-theme.json README.md

A theme file is read as a regular file of at most 1 MB. Two shapes are detected automatically: a Glamour-style document with a top-level "document" block, which GlamourDecorationGate admits and sugar-markdown's StyleGuide maps onto a SugarMarkdown theme, and the flat shape, one style object per element slot, which Theme::fromJsonString() reads. themes/solarized.json in the repository is a worked flat starting point. A payload that matches neither shape refuses with exit 2 instead of quietly rendering the stock theme.

Persist preferences and remap pager keys

{
  "theme": "dracula",
  "width": 80,
  "pager": false,
  "keymap": { "reload": "ctrl-r", "help": "h" }
}

Save that as $XDG_CONFIG_HOME/mdview/mdview.json (or ~/.config/mdview/mdview.json), or point MDVIEW_CONFIG at it. Flags beat environment variables, and environment variables beat the file. The keymap block maps the actions quit, reload and help to a chord written x, ctrl-x or alt-x. The Escape and Ctrl+C quit paths are fixed and stay available whatever the map says.

Render a URL

candy-mdview https://example.com/README.md
candy-mdview -p https://example.com/README.md   # pager on a fetched URL: no auto-reload

API reference

The public classes live in SugarCraft\MdView\. The pager is a SugarCraft Model, so MdViewModel follows the usual init(), update(Msg) and view() contract, and the tests drive it that way. The other classes are static helpers or value objects.

MdViewModel and the pager

MethodDescription
MdViewModel::fromContent(string $content, int $width = 80, int $height = 24)Build the pager Model from already-rendered text. Sole genesis site for the Model.
withDocument(string $name)Enter document mode: a one-row status header shows the file name, scroll percent and reload marker.
withWatch(string $path, \Closure $reRender)Arm auto-reload for a local file. The closure turns the new Markdown into rendered text.
isWatching()Whether a file watch is armed on this model.
withReflow(\Closure $reflowAt)Re-wrap the document when the terminal width changes.
withKeymap(array $overrides)Merge action-to-chord overrides onto the default quit, reload and help map.
init(), update(Msg $msg), view(), subscriptions()The Model contract. update() returns [Model, ?Cmd], and isExited() reports whether a quit key ended the run.

Input, watching and configuration

ClassMethodDescription
DocumentGatereadFile(string $path), readStream($stream, string $label)Read a document under the 64 MiB cap, refusing directories and binary input.
DocumentGaterefuseBinary(string $raw, string $label)Throw for input that is not text.
FrontMattersplit(string $raw), has(string $raw), strip(string $raw)Separate, detect or remove a leading YAML front-matter block.
HttpFetchisRemote(string $arg), fetch(string $url)Recognize an http(s):// argument and fetch it under the timeout, redirect and TLS rules.
FileWatcher__construct(string $path), hasChangedSince(int $mtime)Instance check against a remembered mtime for one path.
FileWatchersnapshot(string $path), pollTuple(string $path, int $lastMtime, int $lastSize)Static (mtime, size) fingerprint, and the one non-blocking sweep that returns a new fingerprint only when it differs from the baseline.
Configload(?string $path = null), defaultPath(), empty()Read the preferences file (at most 64 KiB, known keys only), find its default location, or get the empty config.
GlamourDecorationGateadmit(array $decoded)The one refusal in front of the Glamour loader. A document or paragraph block_prefix / block_suffix that is not inert whitespace throws glamour.decoration_unsafe, and a non-string affix reads as empty. The admitted document then goes to sugar-markdown's StyleGuide::fromDecoded(), and theme() returns the SugarMarkdown Theme.
RenderCommandpickTheme(string $name)Resolve a built-in theme name (dracula, tokyo-night, …) to a SugarMarkdown Theme.
ReloadTickMsg__construct(string $id = self::ID)The tick message the pager's reload timer delivers. ID is mdview.reload.
ApplicationversionString(), hostArchive()The version string shown by --version, and the path of the running phar (an empty string outside a phar).

Visual width measuring is delegated to SugarCraft\Core\Util\Width in sugar-core. This package ships no local width helpers.

Only methods declared in candy-mdview/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\MdView

Application final class

candy-mdview entry point. Registers a single default command so users can invoke candy-mdview <file> without a subcommand name.

MethodSummary
__construct()
static versionString(): stringThe version Symfony's --version will print, phar-aware: inside an archive the build manifest wins — the hardcoded literal would otherwise freeze a number no release process produced, while the manifest names the exact tag the artifact was cut from. A bare dev-build stamp is working-tree noise, not a version, and falls through. Outside an archive nothing is consulted and the historical 0.1.0 answers byte-true (pinned by ApplicationTest and by the precedence test here).
static hostArchive(): stringThe real-filesystem path of the phar archive hosting this install, or '' when this code is not running from an archive. Three identities, first answer wins (measured on PHP 8.3.6 while porting the archive-version guard): Phar::running() names the archive for code executing inside it; in the stub region running() answers '' and __FILE__ names the self-naming archive; a phar:// prefix on this file's own __FILE__ covers shapes where a class was loaded from the archive but running() stayed empty.

Config final class

The persisted-preferences file: mdview.json under the XDG config home (glow keeps ~/.config/glow/glow.yml; this port uses JSON to avoid a YAML dependency). Every setting the CLI takes as a flag or environment fact can live here instead — theme, style, width, pager, keymap — and the resolution precedence is flag > environment > file > default.

MethodSummary
static empty(): selfThe empty config — every lookup answers "no position".
static defaultPath(): ?stringResolve the file location: MDVIEW_CONFIG names it directly (the test seam and the --config-equivalent door); an explicitly EMPTY value disables file lookup entirely — the hermetic escape the suite uses. Otherwise $XDG_CONFIG_HOME or ~/.config, under mdview/mdview.json. Returns null when even HOME is unknown — there is simply no file to consult.
static load(?string $path = null): selfLoad the file at $path (or the default location when null). Absent files and absent directories yield the empty config; a present file is held to the door law (regular file, capped, JSON object, known keys, typed values) or the run refuses with exit code 2.

DocumentGate final class

The ONE document door: is_file → regular-file re-check on the opened handle → size cap → capped read → binary refusal, in that order, used by every path bytes take to enter a render — the file argument, piped stdin, and the pager's reload sweep alike. Before this consolidation the sweep bypassed all of it (a 20 MB replacement grew past the "64 MiB contract" into an OOM of the live pager, and an ELF swapped onto the watched path rendered as a success frame), and stdin was an unbounded slurp while the file lane refused the same bytes cleanly.

MethodSummary
static readFile(string $path): stringRead a local document path under the full gate.
static readStream($stream, string $label): stringRead a piped document stream under the same size and binary contract. The read itself is bounded (MAX+1 bytes), so an endless producer is refused, not slurped.
static refuseBinary(string $raw, string $label): voidRefuse to render binary payloads. Mistyping onto a PNG/PDF/ELF must not spray escape sequences (possible cursor/color-state changes) at the terminal with a success code. Probe: a NUL byte ANYWHERE in the document is conclusive (the cap already holds it whole and str_contains is a memchr-class scan — the old head-only probe let 9000 printable bytes hide an ELF tail); beyond that, a control-character ratio above 5% of the 8 KiB head window is refusal-grade for anything a human would call a text file (UTF-8 text and its multi-byte sequences contain no C0 bytes).

FileWatcher final class

File watching utility for auto-reload on change.

MethodSummary
__construct(private readonly string $path)
hasChangedSince(int $mtime): boolCheck if the file's mtime differs from the given baseline.
static snapshot(string $path): ?arrayCurrent (mtime, size) fingerprint of a file, or null when the path is not a readable regular file. Baseline for pollTuple().
static pollTuple(string $path, int $lastMtime, int $lastSize): ?arrayOne non-blocking change check against a (mtime, size) baseline.

FrontMatter final class

Leading YAML front matter detector (glow parity, finding 007).

MethodSummary
static split(string $raw): arraySplit a document into its renderable body and (optional) raw front-matter block.
static has(string $raw): boolWhether a document opens with a front-matter block.
static strip(string $raw): stringThe document with any leading front-matter block removed.

GlamourDecorationGate final class

The one refusal candy-mdview keeps in front of sugar-markdown's \SugarCraft\Markdown\StyleGuide loader (P1-12c-mdview, owner option b).

MethodSummary
static admit(array $decoded): arrayRefuse or normalize the affix slots of a decoded glamour document.

HttpFetch final class

The URL input door (finding 008): glow's second documented invocation is glow https://example.com/README.md; the port used to answer "no such file" because nothing in src/ knew what a scheme was.

MethodSummary
static isRemote(string $arg): boolWhether a file argument names a remote document (glow's parity door).
static fetch(string $url): stringFetch $url under the transport caps and hand the bytes to the shared document gate. Refusals leave through the usage channel: every one of them is an InvalidArgumentException naming the URL (credentials from its userinfo part never echoed) and the reason.

Lang final class

Per-library translation facade for candy-mdview.

MdViewModel final class

Pager Model used by RenderCommand when -p / --pager is set. Wraps a Viewport containing the already-rendered (styled) text. Standard reader keys are forwarded to the Viewport; plain q / Esc / Ctrl+C exit the loop (modified runes like Alt+q belong to the reader, never to the exit gate).

MethodSummary
static fromContent(string $content, int $width = 80, int $height = 24): self
withDocument(string $name): selfEnter document mode: paint a status header and reserve its row. The viewport height shrinks by one so header + body never exceed the terminal, and every later resize recomputes with the same accounting.
withWatch(string $path, \Closure $reRender): selfArm the auto-reload watch on $path. Every returned instance carries the closure forward (immutability), so later key handling cannot silently drop the watch state.
isWatching(): bool
withReflow(\Closure $reflowAt): selfArm the resize-reflow path (finding 014). The closure receives the live column count on every geometry-changing WindowSizeMsg and returns the fully re-rendered document text; the viewport re-clips scroll offsets against it. Armed ONLY for an unpinned width — an explicit --width is a user decision the resize leg must never override.
withKeymap(array $overrides): selfReplace the default chords for this model's own keys (the config file's keymap door, finding 036). Overrides merge onto the current map, so a partial keymap keeps every untouched binding; the Escape and Ctrl+C quit legs are structural and stay whatever the map says.
init(): ?\Closure
update(Msg $msg): array
view(): string
isExited(): bool
subscriptions(): ?\SugarCraft\Core\Subscriptions

ReloadTickMsg final class

Timer tick that drives the pager's file-watch pump.

MethodSummary
__construct(public readonly string $id = self::ID)

RenderCommand final class

Default candy-mdview command. Reads Markdown from a file argument or stdin, renders it via Renderer, and either prints it to the terminal (default) or opens a fullscreen pager via MdViewModel when -p / --pager is set.

MethodSummary
static setColorProbeCallback(?callable $callback): void
static setTerminalCheckCallback(?callable $callback): void
static setStdinTtyCallback(?callable $callback): void
static setPagerDevTtyCallback(?callable $callback): void
static pickTheme(string $name): ThemeResolve a theme name. The lookup lives in sugar-markdown's Theme (P1-12c-mdview): stock names through Theme::byName(), the bundled JSON slugs through Theme::catalogByName(). The roster and the two aliases remain this CLI's contract.

Configuration

Environment variables

VariableEffect
MDVIEW_THEMETheme name, used when no flag is given. It sits above the config file.
MDVIEW_WIDTHColumn width, an integer from 0 to 9999. A flag wins over it; it wins over the config file.
MDVIEW_PAGERPager mode: 1, true or yes turns it on, 0, false or no turns it off. Any other value is a usage error.
MDVIEW_CONFIGPath to the preferences file. Set it to an empty value to skip file lookup entirely.
XDG_CONFIG_HOME, HOMELocate the default mdview/mdview.json when MDVIEW_CONFIG is unset.
NO_COLOR, CLICOLOR, CLICOLOR_FORCE, FORCE_COLOR, TERM, COLORTERMColor decisions. See Theming.

Preferences file keys

KeyTypeEffect
themestringA built-in theme name, as --theme.
stylestringA theme name, as the --style alias.
widthintegerColumn width, as --width.
pagerbooleanDefault pager mode; a flag can still turn it on for one run.
keymapobjectAction-to-chord overrides for quit, reload and help.

Any other top-level key is refused with exit 2, and the message lists the unknown keys. The file is held to the same door rules as a document: a regular file, at most 64 KiB, a JSON object.

Keys and keybindings

The pager reads the keyboard from /dev/tty, so piped input stays scrollable. The table lists the default bindings.

KeyAction
↑ / kLine up
↓ / jLine down (Alt+j too)
Mouse wheelThree lines per notch in either direction
PgUp / bPage up (Ctrl+B too)
PgDn / space / fPage down
Ctrl+U / Ctrl+DHalf page up or down
Home / g, End / GTop, bottom
← / h, → / lScroll horizontally in no-wrap mode
rForce a reload of the watched file (unmodified only)
?Show or hide a one-row strip that condenses these keys (unmodified only)
q / Esc / Ctrl+CExit. Shift+q, Alt+q and Ctrl+Q do not.

The scroll letters match on their rune alone, so Ctrl+B and Alt+j work as their plain counterparts. A document taller than the screen grows a scrollbar along the right edge, and the header row reads file · scroll% plus ↻N after N auto-reloads. A ↻! means the last change was refused and the frame is stale.

Theming

Twelve stock themes ship: ansi, ascii, plain, notty, dark, light, dracula, tokyo-night, pink, solarized, monokai and github. The aliases no, auto-no and tokyonight resolve to plain, notty and tokyo-night. Names match case-insensitively, and _ is accepted for -. solarized, monokai and github load JSON files from themes/. Each built-in name maps to the SugarMarkdown preset of the same name.

candy-mdview --theme solarized README.md
candy-mdview --style github README.md          # --style is the Glamour-style alias for --theme
candy-mdview --theme dark --width 80 README.md

Three tiers exist for color. ansi is the terminal-native palette. ascii keeps structure, so bold and italic survive while color does not. plain is undecorated bytes. With no theme named, the implicit walk picks ansi on a decorated, color-capable stream, ascii on a decorated stream without color, and plain on an undecorated one.

./examples/render-readme.sh README.md         # the same README in several themes, side by side

The gate that says whether a stream is decorated has three inputs. --ansi opens it and --no-ansi closes it. Otherwise CLICOLOR_FORCE or FORCE_COLOR open it at any value other than 0, even on a pipe. NO_COLOR and CLICOLOR=0 do not close the gate. They only answer the color-capability question. An explicit theme names its palette everywhere, so --theme dark piped into a file still writes SGR bytes.

Examples

The examples/ directory holds four runnable programs. The three PHP examples load the Composer autoloader, so run them from a checkout or a project that has run composer install.

  • examples/render-string.php renders a Markdown string with Renderer::dark() and withWordWrap(60), and prints the ANSI output. Run it with php examples/render-string.php.
  • examples/pager-model.php builds MdViewModel::fromContent() from rendered text, sends two j key messages and a q, and prints each frame. It runs with no terminal.
  • examples/theme-json.php builds a theme from the flat JSON shape with Theme::fromJsonString() and renders a sample through it.
  • examples/render-readme.sh renders a README through several themes with the bundled binary. It needs bash and bin/candy-mdview or a global install.
php examples/render-string.php
php examples/pager-model.php
php examples/theme-json.php

Testing

The suite lives in tests/ and runs under PHPUnit 10. Run it once from the package root, with stdin redirected so a stray read cannot hang the run:

cd candy-mdview && vendor/bin/phpunit < /dev/null

The tests cover the pieces named above. MdViewModelTest and MdViewModelReloadTest drive the pager Model through update(). FileWatcherTest covers the (mtime, size) tuple law. GoldenRenderTest pins rendered output, GlamourDecorationGateTest and ThemeLoadTest cover theme loading, HttpFetchTest covers the URL door, and LocaleParityTest checks that all sixteen lang/ catalogs carry the English key set.

Troubleshooting

"needs a terminal" error with -p

The pager needs a real terminal, either stdout or /dev/tty. When neither is available the run exits 2. Drop -p to render to a pipe or file, which is what a CI job or a redirect wants.

No color in a pipe or redirect

Without a flag, a piped stream is undecorated, so the output is plain. Force decoration with --ansi, or set CLICOLOR_FORCE=1 or FORCE_COLOR=1. Forced decoration also writes the OSC 8 hyperlink envelopes into the file. Add --no-hyperlinks to drop them.

Edits to the file do not appear in the pager

Auto-reload runs only when the pager was opened on a local file, not on stdin or a URL. A rewrite that keeps the same mtime and byte size does not trigger a reload, so press r. If the header shows ↻!, the last change was refused and the frame is stale. Fix the file, then press r.

Exit 2 when --theme-config is refused

The path must be a regular file no larger than 1 MB, and its JSON must be an object that matches one of the two accepted shapes. A directory, a FIFO, a scalar, a JSON list, or an object that matches neither schema refuses with exit 2. The refusal is deliberate: the stock theme is never rendered in its place.

A directory argument refuses

A directory resolves only when it holds one of README.md, README.markdown, index.md, or exactly one *.md file. Several competing candidates refuse with exit 2, and the message names what was searched. Pass the file itself instead.

Leading --- block is missing from the output

That is the front-matter rule. The YAML block is stripped before rendering so it does not become a heading. Pass --show-front-matter to print the block verbatim above the rendered document.

Upstream mapping

Upstream (Go)candy-mdview (PHP)
charmbracelet/glow, the Markdown viewer and pagerbin/candy-mdview, RenderCommand, MdViewModel
charmbracelet/glamour, style files for renderingGlamourDecorationGate, which admits the document and chroma shapes, and sugar-markdown's StyleGuide, which maps them onto a SugarMarkdown Theme

Deliberately absent from the port: 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.

Architecture

Render before the view

Rendering happens once per document load, and the pager scrolls the finished string. The view never re-parses Markdown on a keystroke. A resize is the one exception that repeats the work: when no width is pinned, the Model re-wraps through the reflow closure it was given.

Refuse before painting

A usage error, an oversized document or a binary input stops the run before the alternate screen is armed. A pager that has already painted cannot print a usage message cleanly, so every refusal happens while the terminal is still a plain stream.

Fixed-cadence reload

The reload tick is fixed at 0.5 seconds. Each tick does one non-blocking pollTuple() probe, so the pager never waits on the filesystem and keystrokes keep flowing during a save burst.

Changelog and versioning

The rolling candy-mdview.phar is the version that tracks master. Its .sha256 and .phar.commit sidecars name the exact build. A tagged phar reports its release stamp through --version, and a rolling phar reports dev- followed by its short commit, so --version tells two dev builds apart by commit. A bare checkout or a vendor install reports the fallback 0.1.0, and so does a phar stamped only with the dev-build sentinel.

  • SugarMarkdown: the renderer behind every document, the Theme and Renderer classes used here.
  • SugarForms: the Viewport the pager scrolls with.
  • sugar-core: the Model, Msg and Program runtime the pager runs on.

Try the quickstart →

Demos.

VHS-recorded demo GIFs, regenerated on pushes that touch the tapes or the source.

Render

Render

The monorepo root README rendered with --theme dark.
Pager

Fullscreen pager

-p flag opens a Viewport-powered scrollable pager. Arrows, wheel, or j/k to scroll; q or Ctrl+C quits.