Spectrum - Color and Formatting for Terminal Output

Overview

Spectrum provides ANSI color and style formatting integrated with OCaml's Format module using semantic tags. It supports named colours from the xterm 256-color palette, CSS-style hex codes, and RGB or HSL values.

Terminal capabilities are detected automatically and colours are quantized to the nearest match using LAB color space distance.

opam install spectrum
Spectrum.Simple.printf "@{<green>Hello@} @{<bold>world@}!@."

Documentation

Tutorial

getting_started — Install Spectrum, write your first colored output, learn the tag syntax step by step.

Tag Syntax Reference

The pattern is @{<TAG-NAME>CONTENT@}. Tags are case-insensitive and can be nested arbitrarily.

Colors

Styles

bold, dim, italic, underline, blink, rapid-blink, inverse, hidden, strikethru, overline

Qualifiers and Compound Tags

How-to Guides

Explanation

API Reference

Spectrum provides two module variants:

Both expose the same interface:

val prepare_ppf : Format.formatter -> unit -> unit

module Simple : sig
  val printf : ('a, Format.formatter, unit, unit) format4 -> 'a
  val eprintf : ('a, Format.formatter, unit, unit) format4 -> 'a
  val sprintf : ('a, Format.formatter, unit, string) format4 -> 'a
end

Spectrum.Simple.printf handles formatter setup/teardown automatically. For repeated printing, use Spectrum.prepare_ppf with the standard Format functions.

For programmatic (non-string) tag construction, see Spectrum.Stag.

Note: Format.sprintf uses its own buffer, so you must use Spectrum.Simple.sprintf for styled sprintf, or create your own buffer with Format.fprintf as described in the Format docs.

Terminal Capabilities

Spectrum detects terminal color support and quantizes accordingly:

let info = Spectrum.Capabilities.supported_color_levels () in
match info.stdout with
| True_color -> Printf.printf "24-bit color\n"
| Eight_bit -> Printf.printf "256 colors\n"
| Basic -> Printf.printf "16 colors\n"
| Unsupported -> Printf.printf "No color support\n"

Override with FORCE_COLOR=0|1|2|3. See Spectrum_capabilities.Capabilities for details, or color_quantization for how quantization works.

Libraries

See Also

Project