spectrum

spectrum

[ Docs ]

An OCaml library for colour and formatting in the terminal.

It's a little DSL which is exposed via the Format module's "semantic tags" feature. String tags are defined for ANSI styles such as bold, underline etc and for named colours from the xterm 256-color palette, as well as 24-bit colours via CSS-style hex codes and RGB or HSL values.

It's inspired by the examples given in "Format Unraveled", a paper by Richard Bonichon & Pierre Weis, which also explains the cleverness behind OCaml's highly type-safe format string system.

Many features are borrowed from those found in chalk.js

Goals

Non-goals

See also

These OCaml libs provide support for styling console text with ANSI colours, and some also offer other features useful for formatting and interactivity in the terminal. In contrast, Spectrum focuses only on coloured text styling but offers deeper colour support. Hopefully it's complementary to the stdlib and other libs you may be using.

Installation

opam install spectrum

The main spectrum package includes everything you need for terminal color formatting. The implementation is split into several packages:

All of these are installed automatically as dependencies when you install spectrum.

Quick start

Spectrum.Simple.printf "@{<green>%s@}\n" "Hello world 👋";;

The pattern is @{<TAG-NAME>CONTENT@}.

Tag names match the 256 xterm color names and are case-insensitive. You can also specify colours directly with hex codes, RGB, or HSL values:

Spectrum.Simple.printf "@{<#f0c090>%s@}\n" "Hex color";;
Spectrum.Simple.printf "@{<rgb(240 192 144)>%s@}\n" "RGB color";;
Spectrum.Simple.printf "@{<hsl(60 100 50)>%s@}\n" "HSL color";;

Styles like bold, italic, underline, dim, strikethru, and overline are also supported. Tags can be nested and combined with comma-separated compound tags:

Spectrum.Simple.printf "@{<bold,bg:red,yellow>%s@}\n" "Compound tag";;
Spectrum.Simple.printf "@{<green>%s @{<bold>%s@} %s@}\n" "Hello" "world" "there";;

For efficient repeated printing, prepare a formatter once:

let reset = Spectrum.prepare_ppf Format.std_formatter in
Format.printf "@{<green>%s@}\n" "Hello world 👋";
reset ();;

Automatic color quantization

Spectrum automatically detects terminal capabilities and quantizes colors accordingly. If you specify an RGB color like #FF5733 or rgb(255 87 51), Spectrum will:

Documentation

Documentation is generated with odoc:

opam install spectrum --with-doc

Or online at: anentropic.github.io/ocaml-spectrum

Changelog

See CHANGELOG.md.