📖 3 min read (~ 600 words).

Color a document for a terminal

The task: print a document in color, in a CLI or a diff tool, with every byte of the source kept.

The file

const src = `# service
name: pet-store   # the name
port: 8080
debug: false
tags:
  - "web"
`

Full source: docs/examples/documents/colorize/example_test.go

Render through the theme

// render writes src through the theme. The hook runs only under Verbatim and VerbatimFile,
// so the renderer needs the source.
func render(w io.Writer, src []byte, theme colorize.Theme) error {
	f, err := parser.ParseBytes(src, parser.WithComments())
	if err != nil {
		return err
	}

	r := ast.NewRenderer(ast.WithSource(src), ast.WithTransform(colorize.New(theme)))

	return r.VerbatimFile(w, f)
}

Full source: docs/examples/documents/colorize/example_test.go

colorize.New returns an ast.TransformFunc, which ast.WithTransform installs in the renderer. The renderer hands the function each stretch of the document before it writes it, and the function wraps the stretch’s text in the escapes of its Style.

The hook runs only under Renderer.Verbatim and Renderer.VerbatimFile. Pass the source with ast.WithSource. Renderer.Render calls no hook.

The default theme

var out bytes.Buffer
if err := render(&out, []byte(src), colorize.Default()); err != nil {
	fmt.Println(err)

	return
}
fmt.Print(strings.ReplaceAll(out.String(), "\x1b", "ESC"))

Full source: docs/examples/documents/colorize/example_test.go

The output below writes ESC for the escape byte, 0x1b, so it can be read and checked:

ESC[90m# serviceESC[0m
ESC[96mnameESC[0mESC[37m:ESC[0m ESC[92mpet-storeESC[0m   ESC[90m# the nameESC[0m
ESC[96mportESC[0mESC[37m:ESC[0m ESC[95m8080ESC[0m
ESC[96mdebugESC[0mESC[37m:ESC[0m ESC[95mfalseESC[0m
ESC[96mtagsESC[0mESC[37m:ESC[0m
  ESC[37m-ESC[0m ESC[92m"web"ESC[0m

Full source: docs/examples/documents/colorize/example_test.go

colorize.Default() writes keys in bright cyan (96), strings in bright green (92), numbers and booleans in bright magenta (95), comments in grey (90), and the : and - indicators in white (37). Each stretch closes with 0.

The escapes go round the text alone. The three spaces before # the name and the indentation before - are written plain, so a color never runs to the end of a line.

Values take their style from the type the parse resolved, not from how they were written: 8080 is an integer and "web" a string.

A theme of your own

A field left at its zero value leaves that part uncolored. A Style is a prefix and a suffix, and nothing requires them to be ANSI escapes:

theme := colorize.Theme{
	Key:     colorize.Style{Prefix: `<b>`, Suffix: `</b>`},
	Comment: colorize.Style{Prefix: `<i>`, Suffix: `</i>`},
}

var out bytes.Buffer
if err := render(&out, []byte(src), theme); err != nil {
	fmt.Println(err)

	return
}
fmt.Print(out.String())

Full source: docs/examples/documents/colorize/example_test.go

<i># service</i>
<b>name</b>: pet-store   <i># the name</i>
<b>port</b>: 8080
<b>debug</b>: false
<b>tags</b>:
  - "web"

Full source: docs/examples/documents/colorize/example_test.go

The zero theme

var out bytes.Buffer
if err := render(&out, []byte(src), colorize.Theme{}); err != nil {
	fmt.Println(err)

	return
}
fmt.Println(out.String() == src)

Full source: docs/examples/documents/colorize/example_test.go

true

Full source: docs/examples/documents/colorize/example_test.go

With no field set, the renderer writes the source back byte for byte.

Limits

  • No terminal check. colorize writes escapes wherever it is told to. Check that the output is a terminal before you pass Default(), and pass the zero Theme otherwise.
  • No escaping. A Style wraps the source text as written. For HTML, a value holding < or & reaches the page unescaped.
  • An edit can leave a comma plain. After a caller removes a value from a flow sequence, the , in front of the removed value is written plain.

See Rewriting a document for the Theme fields, and The syntax tree for VerbatimFile.