theme

package
v0.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 7 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package theme holds the colors the packages of this module paint with.

A Style is a set of SGR parameters ("1;38;5;141"); a Theme assigns one to each role text plays on screen — a title, a muted note, the selected row, an error. Packages read their colors from the active theme, so a tool that wants its own palette calls Use once at start-up, usually with a copy of Default that changes a few roles. Whether anything is painted at all is decided by term.Colored, not by the theme; Style.For and Theme.For ask it for a given writer.

Theme.PaintDiff paints a unified diff with the theme's diff roles, and DiffScanner tells its lines apart for code that shows only some of them. Both take the diff as it is and take nothing out of it: a diff that does not come from the program itself goes through term.Plain first. Theme.PaintJSON paints encoded JSON with the theme's JSON roles in the same way.

ParseStyle reads a style a user wrote, such as "fg=white:bg=#aa0000:bold" in an environment variable, and Style.PaintMatches paints what a regular expression matches in text that may be painted already.

Hashed gives a name a style of its own that stays the same across rows and runs, such as a color per author, picked from NamePalette or a palette of the caller's. Theme.Hashed does the same for output painted with a theme, and stays plain where the theme is Plain.

Index

Examples

Constants

View Source
const Reset = "\x1b[0m"

Reset ends every SGR attribute.

Variables

View Source
var Default = Theme{
	Title:             Bold,
	Subject:           Bold,
	Header:            Join(Bold, Fg256(252)),
	Border:            Fg256(240),
	Muted:             Fg256(244),
	Status:            Fg256(244),
	Qualifier:         Fg256(250),
	Value:             Fg256(141),
	Detail:            Fg256(117),
	Selected:          Join(Bold, Fg256(141)),
	SelectedQualifier: Fg256(146),
	Action:            Fg256(73),
	SelectedAction:    Join(Bold, Fg256(79)),
	Accent:            Fg256(214),
	Flag:              Fg256(203),
	Info:              Fg256(117),
	Success:           Fg256(114),
	Warning:           Fg256(221),
	Error:             Fg256(203),
	Added:             Fg256(114),
	Removed:           Fg256(203),
	DiffHeader:        Bold,
	DiffHunk:          Fg256(117),
	JSONKey:           Fg256(116),
	JSONString:        Fg256(120),
	JSONNumber:        Fg256(118),
	JSONBool:          Fg256(156),
	JSONNull:          Fg256(242),
}

Default is the theme the packages use unless Use installs another. It sticks to the 256-color palette, which every common terminal supports, and to mid-luminance tones that read on dark and light backgrounds. A diff reads the way git paints one: file headers bold, hunk headers in light blue, removed lines red and added lines green, in the tones of Error and Success. JSON reads in cool tones: keys turquoise, strings and numbers in two greens, true and false in a pale green, and null receding in grey.

View Source
var NamePalette = []Style{
	Fg256(218),
	Fg256(116),
	Fg256(216),
	Fg256(105),
	Fg256(120),
	Fg256(177),
	Fg256(110),
}

NamePalette is the palette Hashed picks from when it is given none: seven distinct mid-luminance hues of the 256-color palette — pink, turquoise, apricot, periwinkle, green, orchid and steel blue — that read on dark and light backgrounds and stay apart from the red and yellow of warnings and errors.

View Source
var Plain = Theme{}

Plain paints nothing. Installing it keeps escape sequences out of output even where term.Colored would allow them.

Functions

func Use

func Use(t Theme)

Use installs t as the active theme for the whole process. Call it once at start-up, before any output is drawn.

Types

type DiffKind added in v0.5.0

type DiffKind int

DiffKind is what a line of a unified diff is, as a DiffScanner tells it.

const (
	// DiffText is a line outside the files a diff changes, such as the
	// commit message above them. It is not painted.
	DiffText DiffKind = iota
	// DiffFileHeader is a line that introduces a file: diff --git, index,
	// mode and rename lines, and the --- and +++ lines naming the old and
	// the new file.
	DiffFileHeader
	// DiffHunkHeader is the line that starts a hunk: @@ -12,7 +12,8 @@.
	DiffHunkHeader
	// DiffContext is an unchanged line inside a hunk, or a "\ No newline at
	// end of file" note. It is not painted.
	DiffContext
	// DiffRemoved is a line the change takes away.
	DiffRemoved
	// DiffAdded is a line the change adds.
	DiffAdded
)

type DiffScanner added in v0.5.0

type DiffScanner struct {
	// contains filtered or unexported fields
}

DiffScanner tells the lines of a unified diff apart, one at a time. It reads the diff the way patch does: a hunk header says how many old and new lines the hunk holds, and until they are through, a line starting with "-" is a removed line even when it reads "--- something" — only outside a hunk does such a line name a file. A hunk header without line counts, as some tools write them, makes the hunk run until the next header.

A file's header starts at its diff line (diff --git, diff --cc, diff -u) and holds the lines git and diff write there: index, mode, similarity, rename and copy lines, the --- and +++ lines and the note that binary files differ. Any other line ends it, so what follows a file without a hunk, a renamed or a binary one, is text again: the next commit of a git log -p, say.

The combined diff git shows for a merge is read as well. Its hunk headers have one more @ per further parent (@@@ -1,3 -1,3 +1,4 @@@), and its lines start with one marker column per parent: a line with a "-" in any column is removed, one with a "+" and no "-" is added.

A DiffScanner reads its lines as they are and takes them for plain text: a line that starts with an escape sequence is not told apart. Diff text from elsewhere goes through term.Plain before it is classified, see Theme.PaintDiff.

The zero DiffScanner is ready to read a diff from its first line.

Example

A review shows only what a change removes and adds, painted where the output takes color: here Plain stands in for theme.Active().For(os.Stdout) on a pipe.

package main

import (
	"fmt"
	"strings"

	"github.com/mittwald/cli-kit/theme"
)

var diff = "--- a/version.yaml\n" +
	"+++ b/version.yaml\n" +
	"@@ -1,2 +1,2 @@\n" +
	"-version: 8.4.24\n" +
	"+version: 8.4.25\n" +
	" stable: true\n"

func main() {
	th := theme.Plain
	var scanner theme.DiffScanner
	for line := range strings.SplitSeq(strings.TrimSuffix(diff, "\n"), "\n") {
		switch kind := scanner.Classify(line); kind {
		case theme.DiffRemoved, theme.DiffAdded:
			fmt.Println("    " + th.PaintDiffLine(kind, line))
		}
	}
}
Output:
    -version: 8.4.24
    +version: 8.4.25

func (*DiffScanner) Classify added in v0.5.0

func (s *DiffScanner) Classify(line string) DiffKind

Classify returns what line is, given the lines classified before it, and remembers it for the next. line is one line of the diff, without its newline.

type Style

type Style string

Style is a set of SGR parameters, such as "1" (bold) or "38;5;141" (a 256-color foreground). The zero Style paints nothing.

const (
	Bold      Style = "1"
	Dim       Style = "2"
	Italic    Style = "3"
	Underline Style = "4"
	Reverse   Style = "7"
)

Common attributes.

func Bg256

func Bg256(n uint8) Style

Bg256 is a background color from the 256-color palette.

func BgRGB

func BgRGB(r, g, b uint8) Style

BgRGB is a 24-bit background color.

func Fg256

func Fg256(n uint8) Style

Fg256 is a foreground color from the 256-color palette.

func Hashed added in v0.8.0

func Hashed(name string, palette []Style) Style

Hashed returns a style for name that stays the same: the same name gets the same style on every row, in every list and on every run, so a list can be scanned by who or what a row belongs to, such as the author of a commit. It picks from palette by the FNV-1a hash of the name, or from NamePalette when palette is empty.

The name is compared without case and without the white space around it, so "Alice" and " alice" get one style. A blank name gets the zero Style, which paints nothing. Different names may share a style: a palette of seven tells seven names apart at best.

Example

Every row by the same author is painted alike, whatever case the name is written in.

package main

import (
	"fmt"

	"github.com/mittwald/cli-kit/theme"
)

func main() {
	palette := []theme.Style{"31", "32", "33"}
	fmt.Println(theme.Hashed("Alice", palette) == theme.Hashed("alice ", palette))
	fmt.Printf("%q\n", theme.Hashed("", palette))
}
Output:
true
""

func Join

func Join(styles ...Style) Style

Join combines styles into one, skipping empty ones: Join(Bold, Fg256(141)).

func ParseStyle added in v0.9.0

func ParseStyle(spec string) (Style, bool)

ParseStyle reads a style specification, such as a user puts into an environment variable or a configuration file to change a color: parts separated by colons, each a color or a text attribute, as in "245", "160:bold" or "fg=white:bg=#aa0000:underline".

A color is a name (black, red, green, yellow, blue, magenta or purple, cyan, white or gray, and darkgray, lightred, lightgreen or lime, lightyellow, lightblue, lightmagenta, lightcyan and lightwhite), a number from 0 to 255 of the 256-color palette, or a hex color of three or six digits with an optional "#" or "0x". It colors the text; prefixed with "bg=" or "background=" it colors the background, and "fg=" or "foreground=" says the default out loud. A number of one to three digits is a palette index while it is at most 255; a larger one, such as 300, is read as a hex color of three digits.

A hex color is painted as it is where term.TrueColor reports that the terminal takes 24-bit colors, and as the nearest of the 256 colors (term.Nearest256) everywhere else, since a terminal that does not know 24-bit colors reads their parameters as attributes of their own.

An attribute is one of bold (or b), fuzzy (or dim), italic (or i), underline (or u), blink, reverse (or invert) and strikethrough. Upper and lower case are the same, and white space around a part is ignored.

Parts that are neither are skipped. The result is false when nothing is left, so a mistyped specification paints nothing rather than something unexpected. The result holds only SGR parameters, never anything of the specification itself.

Example

A style from the environment, such as EXAMPLE_COLOR_HEADER=160:bold.

package main

import (
	"fmt"

	"github.com/mittwald/cli-kit/theme"
)

func main() {
	style, ok := theme.ParseStyle("160:bold")
	fmt.Printf("%q %v\n", style.Paint("header"), ok)

	_, ok = theme.ParseStyle("bright-ish")
	fmt.Println(ok)
}
Output:
"\x1b[38;5;160;1mheader\x1b[0m" true
false

func RGB

func RGB(r, g, b uint8) Style

RGB is a 24-bit foreground color.

func (Style) For added in v0.4.0

func (s Style) For(w io.Writer) Style

For returns s where w takes color, as term.Colored decides, and the zero Style anywhere else, so text painted with the result stays plain in a pipe, a file or a test's buffer:

fmt.Fprintln(os.Stderr, theme.Active().Muted.For(os.Stderr).PaintLines(note))

func (Style) Paint

func (s Style) Paint(text string) string

Paint wraps text in s and a reset. It returns text unchanged when s is empty or text is empty, so it is safe to call unconditionally.

func (Style) PaintIf

func (s Style) PaintIf(on bool, text string) string

PaintIf paints text only when on is true, usually the result of term.Colored for the writer the text goes to.

func (Style) PaintLines

func (s Style) PaintLines(text string) string

PaintLines paints every line of text on its own, so a terminal that redraws a single line keeps its color and a newline never carries a color into the next line.

func (Style) PaintMatches added in v0.9.0

func (s Style) PaintMatches(text string, re *regexp.Regexp) string

PaintMatches paints what re matches in text with s, where text may be painted already, such as a table cell in a color of its own with a word in it to stand out. After each match the attributes the text had set before it are switched on again, so the rest of the text keeps its colors.

Only text is searched: escape sequences are copied as they are, so a match never lands inside one, such as the target of a hyperlink, and a match never spans one. Empty matches paint nothing. A nil re paints the whole text with s instead, with the colors it had taken out first (term.StripANSI), so they do not show through.

It returns text unchanged when s is the zero Style or text is empty. Like Style.Paint it paints whatever it is given: ask term.Colored, or use Style.For, before painting output that may not go to a terminal. Text from elsewhere goes through term.Sanitize or term.Plain first.

Example

A word stands out in a muted line, and the line stays muted after it.

package main

import (
	"fmt"
	"regexp"

	"github.com/mittwald/cli-kit/theme"
)

func main() {
	line := theme.Dim.Paint("3 checks failed, 2 passed")
	fmt.Printf("%q\n", theme.Style("31").PaintMatches(line, regexp.MustCompile(`failed`)))
}
Output:
"\x1b[2m3 checks \x1b[0m\x1b[31mfailed\x1b[0m\x1b[2m, 2 passed\x1b[0m"

func (Style) Sequence

func (s Style) Sequence() string

Sequence returns the escape sequence that switches s on, or "" for the zero Style.

type Theme

type Theme struct {
	// Title is a heading, or the question a prompt asks.
	Title Style
	// Subject is the thing a title is about, drawn inside it.
	Subject Style
	// Header is a table's header row.
	Header Style
	// Border is a table's rules and frame.
	Border Style
	// Muted recedes text: notes, key hints, disabled rows.
	Muted Style
	// Status is text that only says what a command is doing while it does
	// it: the lines of pick.Status and the detail lines of live.Blocks.
	Status Style
	// Qualifier is secondary text beside a value, quieter than the value but
	// louder than Muted.
	Qualifier Style
	// Value is an answer or a typed value.
	Value Style
	// Detail is the full value of a shortened item, shown beside a title.
	Detail Style
	// Selected is the row or item under the cursor.
	Selected Style
	// SelectedQualifier is Qualifier on the selected row.
	SelectedQualifier Style
	// Action is what choosing a row does.
	Action Style
	// SelectedAction is Action on the selected row.
	SelectedAction Style
	// Accent marks something worth noticing, such as a marker column.
	Accent Style
	// Flag marks something worth stopping at.
	Flag Style
	// Info, Success, Warning and Error color messages by severity.
	Info    Style
	Success Style
	Warning Style
	Error   Style
	// Added and Removed are what a change adds and takes away, such as the
	// added and removed lines of a diff.
	Added   Style
	Removed Style
	// DiffHeader is the header of a file in a diff: the diff --git, index,
	// --- and +++ lines.
	DiffHeader Style
	// DiffHunk is the @@ -1,4 +1,5 @@ that starts a hunk of a diff.
	DiffHunk Style
	// JSONKey is the name of a member of a JSON object, quotes included.
	JSONKey Style
	// JSONString is a JSON string value, quotes included.
	JSONString Style
	// JSONNumber is a JSON number.
	JSONNumber Style
	// JSONBool is a JSON true or false.
	JSONBool Style
	// JSONNull is a JSON null.
	JSONNull Style
}

Theme assigns a style to each role text plays on screen.

func Active

func Active() Theme

Active returns the theme Use installed, or Default.

func (Theme) For added in v0.5.0

func (t Theme) For(w io.Writer) Theme

For returns t where w takes color, as term.Colored decides, and Plain anywhere else, so whatever is painted with the result stays plain in a pipe, a file or a test's buffer:

th := theme.Active().For(os.Stdout)
fmt.Println(th.Success.Paint("passed"), th.Muted.Paint("in 2s"))

func (Theme) Hashed added in v0.10.0

func (t Theme) Hashed(name string, palette ...Style) Style

Hashed is Hashed for output painted with t: the zero Style where t is Plain, such as what Theme.For returns for a pipe or a file, so a name colored this way stays plain wherever the rest of t does:

th := theme.Active().For(os.Stdout)
fmt.Println(th.Hashed(author).Paint(author), th.Muted.Paint(date))

An empty palette means NamePalette. The package-level Hashed paints wherever its result is used; call Style.For on it, or use this method.

func (Theme) PaintDiff added in v0.5.0

func (t Theme) PaintDiff(text string) string

PaintDiff paints every line of text, a unified diff, the way Theme.PaintDiffLine does, telling the lines apart with a DiffScanner. Each line is painted on its own, and line endings are kept. Paint with t.For(w) what is written to w, so it is painted only where w takes color:

fmt.Fprint(os.Stdout, theme.Active().For(os.Stdout).PaintDiff(diff))

The text is painted as it is: nothing is taken out of it. A diff shows what files hold, and a file can hold escape sequences: one that sets the clipboard, or colors that make an added line look removed or hide it. Painting leaves them in place, and term.Sanitize would keep the colors. Diff text that does not come from the program itself goes through term.Plain first, which leaves the text and the line breaks of the diff and nothing else:

fmt.Fprint(os.Stdout, theme.Active().For(os.Stdout).PaintDiff(term.Plain(diff)))

term.Plain reads a carriage return inside a line as a terminal does: the text after it draws over the text before it, the "+" or "-" of the line included. Where no changed line may pass for another, take the carriage returns out before, with strings.ReplaceAll(diff, "\r", "").

Example
package main

import (
	"fmt"
	"strings"

	"github.com/mittwald/cli-kit/theme"
)

var diff = "--- a/version.yaml\n" +
	"+++ b/version.yaml\n" +
	"@@ -1,2 +1,2 @@\n" +
	"-version: 8.4.24\n" +
	"+version: 8.4.25\n" +
	" stable: true\n"

func main() {
	th := theme.Theme{Added: "32", Removed: "31", DiffHeader: theme.Bold, DiffHunk: "36"}
	for line := range strings.Lines(th.PaintDiff(diff)) {
		fmt.Printf("%q\n", line)
	}
}
Output:
"\x1b[1m--- a/version.yaml\x1b[0m\n"
"\x1b[1m+++ b/version.yaml\x1b[0m\n"
"\x1b[36m@@ -1,2 +1,2 @@\x1b[0m\n"
"\x1b[31m-version: 8.4.24\x1b[0m\n"
"\x1b[32m+version: 8.4.25\x1b[0m\n"
" stable: true\n"

func (Theme) PaintDiffLine added in v0.5.0

func (t Theme) PaintDiffLine(kind DiffKind, line string) string

PaintDiffLine paints line, a line of a unified diff that a DiffScanner classified as kind: a file header in DiffHeader, the "@@ … @@" of a hunk header in DiffHunk — the function name git writes after it stays plain —, a removed line in Removed and an added one in Added. Text and context lines are returned unchanged.

The line is painted as it is. An escape sequence in it is written out with it, and a reset in it ends the line's color early; see Theme.PaintDiff for diff text from elsewhere.

func (Theme) PaintJSON added in v0.8.0

func (t Theme) PaintJSON(text string) string

PaintJSON paints text, JSON as an encoder wrote it, compact or indented: the names of object members in JSONKey, string values in JSONString, numbers in JSONNumber, true and false in JSONBool and null in JSONNull. Quotes are painted with what they enclose; brackets, braces, commas, colons and white space stay plain. Paint with t.For(w) what is written to w, so it is painted only where w takes color:

data, _ := json.MarshalIndent(v, "", "  ")
fmt.Println(theme.Active().For(os.Stdout).PaintJSON(string(data)))

PaintJSON does not parse: it reads tokens, and text that is not JSON comes out with its strings, numbers and literals painted as it finds them, and everything else as it is. A string is never painted past the end of its line, so a quote that is never closed does not color the lines after it.

Like Theme.PaintDiff, PaintJSON takes nothing out of the text. JSON written by encoding/json holds no escape sequence, since it escapes every control character in a string. JSON from elsewhere that was not decoded and encoded again goes through term.Plain first.

Example
package main

import (
	"fmt"

	"github.com/mittwald/cli-kit/theme"
)

func main() {
	th := theme.Theme{JSONKey: "36", JSONString: "32", JSONNumber: "33", JSONBool: "35", JSONNull: "2"}
	fmt.Printf("%q\n", th.PaintJSON(`{"id":7,"ok":true,"tag":null}`))
}
Output:
"{\x1b[36m\"id\"\x1b[0m:\x1b[33m7\x1b[0m,\x1b[36m\"ok\"\x1b[0m:\x1b[35mtrue\x1b[0m,\x1b[36m\"tag\"\x1b[0m:\x1b[2mnull\x1b[0m}"

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL