coloring

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2021 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package coloring provides functions and types to add style attributes in the form of ANSI escape sequences to strings.

The APIs provided by this package can be categorized as follows:

┌──────────────────────┬─────────────────────────────────────────────┐
│ Method               │ Use Case                                    │
├──────────────────────┼─────────────────────────────────────────────┤
│ coloring.* functions │ Simple, ad-hoc styling                      │
├──────────────────────┼─────────────────────────────────────────────┤
│ StyleBuilder         │ Combining multiple styles; reusing the same │
│                      │ style for various strings                   │
├──────────────────────┼─────────────────────────────────────────────┤
│ StyledText           │ Sealed, self-contained styled string useful │
│                      │ for passing around                          │
├──────────────────────┼─────────────────────────────────────────────┤
│ SentenceBuilder      │ Complex styling; full control of placing    │
│                      │ (start and end) of style attributes         │
├──────────────────────┼─────────────────────────────────────────────┤
│ coloring.Tagged      │ Custom markup syntax to embed color         │
│                      │ attributes directly in a string             │
└──────────────────────┴─────────────────────────────────────────────┘

In the examples below, whenever you see the string "ESC", it symbolically refers the the byte "0x1B" ("27" in decimal or "33" in octal) which is the control character used to start the ANSI escape sequences.

Utility functions

These are utility functions that lets you apply simple style attributes to a provided string, like:

fmt.Println(coloring.Green("All checks passed!"))

Composition is also possible:

fmt.Println(coloring.Bold(coloring.Red("Some checks did not pass")))

The string returned by these functions can also be used as format arguments:

fmt.Printf("Build result: %s\n", coloring.Green("SUCCESSFUL"))

The full set of utility functions is:

// Text colors
Black(s string)
Red(s string)
Green(s string)
Yellow(s string)
Blue(s string)
Magenta(s string)
Cyan(s string)
White(s string)

// Background colors
BgBlack(s string)
BgRed(s string)
BgGreen(s string)
BgYellow(s string)
BgBlue(s string)
BgMagenta(s string)
BgCyan(s string)
BgWhite(s string)

// Text style
Bold(s string)
Faint(s string)
Italic(s string)
Underline(s string)
Blink(s string)
Invert(s string)
Conceal(s string)
Strikethrough(s string)

Functions to apply bright text and background colors are found under the coloring.Extras variable:

fmt.Println(coloring.Extras.BrightGreen("All checks passed!"))

The full list of extra functions is:

// Bright text colors
BrightBlack(s string)
BrightRed(s string)
BrightGreen(s string)
BrightYellow(s string)
BrightBlue(s string)
BrightMagenta(s string)
BrightCyan(s string)
BrightWhite(s string)

// Bright background colors
BgBrightBlack(s string)
BgBrightRed(s string)
BgBrightGreen(s string)
BgBrightYellow(s string)
BgBrightBlue(s string)
BgBrightMagenta(s string)
BgBrightCyan(s string)
BgBrightWhite(s string)

StyleBuilder

When you need to apply multiple styles to the same word/phrase you can use a StyleBuilder:

boldRedFiretruck := coloring.For("fire truck").Bold().Red()

fmt.Printf("Here comes the %s\n", boldRedFiretruck)

StyleBuilder implements the Stringer interface, and by doing so, can be used in any place expecting one

If you need the styled string for use in other contexts not expecting a Stringer, just call the String() func on the StyleBuilder:

styledFiretruck := boldRedFiretruck.String()

// pass or use the styledFiretruck string as needed

Styles generated by StyleBuilder combine multiple attributes in a single escape sequence and resets all the styles at the end.

For example, the following code:

styledWolf := coloring.For("Wolf").Red().Bold().Underline().Blink().String()

creates the escaped string:

ESC[31;1;4;5mWolfESC[0m

If you pretend to reuse the same style for different strings, you can do so by using the New() shorthand, and then calling Func() at the end, which will give you a ColorizerFunc that can be invoked with different strings:

boldRed := coloring.New().Bold().Red().Func()

fmt.Printf("Here comes the %s to extinguish the %s\n", boldRed("fire truck"), boldRed("fire"))

Whether to use For(string) or New() + Func() will be a matter of reusability needs.

Finally, if you only need to print the styled text and nothing else, StyleBuilder offers a convenience function: Print().

It returns a ColorizerPrint which can be invoked with the text to print, much like the ColorizerFunc, but instead of returning styled strings, it outputs them on the terminal:

printAlert := coloring.New().White().Bold().Background().Red().Print()

printAlert("ALERT: The house is on fire!!!\n")

StyledText

This can be considered a spin-off from StyleBuilder that lets you get a "sealed" styled string which can't be further modified.

The StyledText struct also implements Stringer, so it can be used as a parameter for any function expecting one.

The motivation behind this type is to allow for the separation between styled text definition and usage. You can create a StyleBuilder at program start, and then get multiple StyledText instances that you can pass around to the rest of the program handling console output.

The main (and only) difference to a plain string is that StyledText also contains an Unformatted() function which returns the original, unstyled string. This could come in handy if for some reason you need to alternate the display of the styled text and the plain text (i.e.: the one without styles).

The following example tries to illustrate this idea.

func main() {
  boldGreenTextBuilder := coloring.New().Bold().Green()

  successfulTitle := boldGreenTextBuilder.StyleText("successful")
  successTitle := boldGreenTextBuilder.StyleText("succeeded")

  pipeline(successfulTitle, successTitle)
}

func pipeline(successTitle, successfulTitle *coloring.StyledText) {
  fmt.Println("BUILDING...")

  // "building"
  fmt.Println("...")
  fmt.Println("...")
  fmt.Println("...")
  fmt.Println()
  fmt.Printf("Build %s.\n", successfulTitle)
  fmt.Println()

  fmt.Println("RUNNING TESTS...")

  // "testing"
  fmt.Println("...")
  fmt.Println("...")
  fmt.Println()
  fmt.Printf("Running tests: all tests %s.", successTitle)
  fmt.Println()
}

SentenceBuilder

This is perhaps the most cumbersome way to add style attributes, but in return it provides more granular control to mark the start and end of each style attribute.

The biggest advantage is that you can apply styles that spans different sections of the text in a non-uniform way, like crossed text covering bold red text and regular text.

Of course this is also doable with the other APIs, but it will be more repetitive to accomplish.

coloring.Sentence().      // gets an instance of SentenceBuilder
  StrikethroughStart().   // marks the start of crossed text
  ColorSet(coloring.RED). // marks the start of red text
  Bold("All this text").  // outputs the given text with bold style
  ColorReset().           // sets text color back to the default one
  Text(" is crossed").    // adds normal (non-styled) text
  Println()               // resets all styles and then prints the whole sentence to stdout

All the functions of the SentenceBuilder API comes in two flavours, one that outputs a single chunk of text with a single style (like the bold text in the example above), and another as a pair of functions in the form XXXStart/XXXEnd that lets you start some style and leave it "open" until you call the corresponding "end" function, much like closing an HTML tag. ColorSet/ColorReset are the exception to this naming convention, but serves the same purpose.

You might notice that we didn't call StrikethroughEnd on the previous example. But that's fine, since we are ending the sentence with Println(), which adds the attribute to reset al styles before writing the output. The rationale behind this is to not "leak" any styles in subsequent output.

Dissecting the generated string will complete the picture:

Strikethrough starts  Bold starts         Bold ends         All attributes cleared
          |                |                  |                        |
          v                v                  v                        v
       ------           ------             -------                  ------
       ESC[9mESC[38;5;1mESC[1mAll this textESC[22mESC[39m is crossedESC[0m
             -----------                          -------
                  ^                                  ^
                  |                                  |
            Red color set                       Color reset

Given that the SentenceBuilder API is quite large, there are no color-named functions for setting colored text/background, as it will expand the API surface further. There's only one method to write colored text/background which expects to receive the color number as a parameter (and equivalent ones for RGB colors).

As with StyleBuilder, SentenceBuilder also lets you grab a StyledText containing the buffered styled text so far, as well the unformatted text.

Tagged function

The SentenceBuilder API, while powerful, is very verbose and can produce hard-to-read code.

The coloring.Tagged function aims to provide pretty much the same fine grained control, while keeping your strings more readable and less fragmented across different function calls.

It allows you to use an HTML-like syntax in your strings to set the starting and ending points of style attributes.

HTML-like tags were chosen because probably most developers have worked with HTML, so the resulting strings will result familiar to them.

For example, to create a styled string you can write:

coloring.Tagged("The <b>wolf</b> <i>howls</i> at the <b><yellow>moon</yellow></b>")

This will result in the word "wolf" styled as bold text, the word "howls" in italics, and the word "moon" in bold and yellow color.

The full list of tags that can be used are:

┌──────────────────────┬──────────────────┬───────────┐
| Attribute            | Tag              | Shorthand |
├──────────────────────┼──────────────────┼───────────┤
| Bold                 | <bold>           | <b>       |
├──────────────────────┼──────────────────┼───────────┤
| Faint                | <faint>          | <f>       |
├──────────────────────┼──────────────────┼───────────┤
| Italic               | <italic>         | <i>       |
├──────────────────────┼──────────────────┼───────────┤
| Underline            | <underline>      | <u>       |
├──────────────────────┼──────────────────┼───────────┤
| Blink                | <blink>          | <bl>      |
├──────────────────────┼──────────────────┼───────────┤
| Invert               | <invert>         | <in>      |
├──────────────────────┼──────────────────┼───────────┤
| Conceal              | <conceal>        | <c>       |
├──────────────────────┼──────────────────┼───────────┤
| Strikethrough        | <strikethrough>  | <s>       |
├──────────────────────┼──────────────────┼───────────┤
| Black text           | <black>          | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| Red text             | <red>            | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| Green text           | <green>          | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| Yellow text          | <yellow>         | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| Blue text            | <blue>           | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| Magenta text         | <magenta>        | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| Cyan text            | <cyan>           | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| White text           | <white>          | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| Black background     | <bg-black>       | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| Red background       | <bg-red>         | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| Green background     | <bg-green>       | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| Yellow background    | <bg-yellow>      | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| Blue background      | <bg-blue>        | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| Magenta background   | <bg-magenta>     | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| Cyan background      | <bg-cyan>        | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| White background     | <bg-white>       | N/A       |
├──────────────────────┼──────────────────┼───────────┤
| Reset all attributes | <reset>          | <r>       |
└──────────────────────┴──────────────────┴───────────┘

Note that, unlike real HTML, these tags are only used to mark the starting and ending points of the style attribute they represent, but they don't requiere to be correctly nested.

The following code will produce a valid escaped string:

coloring.Tagged("<b>Lorem ipsum <red>dolor sit </b>amet</red>")

Because it's translated to:

 <b>                 <red>              </b>      </red>
  |                    |                  |          |
  v                    v                  v          v
------            -----------          -------    -------
ESC[1mLorem ipsum ESC[38;5;1mdolor sit ESC[22mametESC[39mESC[0m
                                                         ------
                                                            ^
                                                            |
                                              Reset attribute automatically
                                              added at the end of the string

Also, because a reset attribute (ESC[0m) is automatically added at the end of the generated string (so it doesn't leak styles to the next console output), it would be possible to leave open tags that set styles that doesn't change anymore in the current string:

coloring.Tagged("<b>Starting bold and <green>turning green")

As you may guess, this produces the escaped string:

ESC[1mStarting bold and ESC[38;5;2mturning greenESC[0m

If you feel more comfortable with the "simmetry" of regular HTML, you can also write:

coloring.Tagged("<b>Starting bold and <green>turning green</green></b>")

Which produces the same visual output, although with a bit more redundant escape sequence:

ESC[1mStarting bold and ESC[38;5;2mturning greenESC[39mESC[22mESC[0m

One could say that the latter form is more maintainable because in case you need to move things around, it's more easy to spot the boundaries of each attribute. Performance impact should be negligible.

But in the end, it's up to you to decide which style might be the "best" for your specific scenario, taste, etc.

You can also set bright color mode for any text or background color adding the attribute "bright" inside the tag (similar to how the disabled attribute can be specified in the HTML <select> element):

coloring.Tagged("<red bright>Bright color</red> and <bg-green bright>bright background</bg-green> enabled!")

"bright" should be interpreted as an "attribute without value", and thus go after the tag name.

A special tag named <reset> (shorthand <r>) allows to insert the "reset" attribute (ESC[0m) that turns off all other attributes at once.

This can come in handy if you have multiple style attributes applied and don't want to bother with closing each one individually:

coloring.Tagged("<bg-cyan bright><red bright><b><u><i>This starts very convoluted,<reset> but ends quietly.")

If your string actually contains the "<" character as part of the text, you will need to escape it by prepending a "\" character before it. The "\" must itself be escaped in a string, so the final string will become:

coloring.Tagged("The \\<bold> or \\<b> tags are used to output <b>bold</b> text.")

In case that you need to output a "\" character, you escape the "\" by adding a "\" before it.

Example (Formatting)
package main

import (
	"fmt"

	"github.com/go-color-term/go-color-term/coloring"
)

func main() {
	fmt.Printf("Build result: %s\n", coloring.Green("SUCCESSFUL"))

}
Output:

Build result: �[32mSUCCESSFUL�[39m
Example (StyleBuilderMultipleStyles)
package main

import (
	"fmt"

	"github.com/go-color-term/go-color-term/coloring"
)

func main() {
	fmt.Println(coloring.For("Wolf").Red().Bold().Underline().Blink())

}
Output:

�[31;1;4;5mWolf�[0m
Example (StyleComposition)
package main

import (
	"fmt"

	"github.com/go-color-term/go-color-term/coloring"
)

func main() {
	fmt.Println(coloring.Bold(coloring.Red("Some checks did not pass")))

}
Output:

�[1m�[31mSome checks did not pass�[39m�[22m

Index

Examples

Constants

View Source
const (
	BLACK = iota
	RED
	GREEN
	YELLOW
	BLUE
	MAGENTA
	CYAN
	WHITE
	BRIGHTBLACK
	BRIGHTRED
	BRIGHTGREEN
	BRIGHTYELLOW
	BRIGHTBLUE
	BRIGHTMAGENTA
	BRIGHTCYAN
	BRIGHTWHITE
)

Predefined color values that can be used to specify a color in functions expecting a single int.

Variables

This section is empty.

Functions

func BgBlack

func BgBlack(s string) string

BgBlack wraps s with the attribute to render it with black background.

Equivalent to the sequence ESC[40;m follwed by s and ended with ESC[49;m.

func BgBlue

func BgBlue(s string) string

BgBlue wraps s with the attribute to render it with blue background.

Equivalent to the sequence ESC[44;m follwed by s and ended with ESC[49;m.

func BgCyan

func BgCyan(s string) string

BgCyan wraps s with the attribute to render it with cyan background.

Equivalent to the sequence ESC[46;m follwed by s and ended with ESC[49;m.

func BgGreen

func BgGreen(s string) string

BgGreen wraps s with the attribute to render it with green background.

Equivalent to the sequence ESC[42;m follwed by s and ended with ESC[49;m.

func BgMagenta

func BgMagenta(s string) string

BgMagenta wraps s with the attribute to render it with magenta background.

Equivalent to the sequence ESC[45;m follwed by s and ended with ESC[49;m.

func BgRed

func BgRed(s string) string

BgRed wraps s with the attribute to render it with red background.

Equivalent to the sequence ESC[41;m follwed by s and ended with ESC[49;m.

func BgWhite

func BgWhite(s string) string

BgWhite wraps s with the attribute to render it with white background.

Equivalent to the sequence ESC[47;m follwed by s and ended with ESC[49;m.

func BgYellow

func BgYellow(s string) string

BgYellow wraps s with the attribute to render it with yellow background.

Equivalent to the sequence ESC[43;m follwed by s and ended with ESC[49;m.

func Black

func Black(s string) string

Black wraps s with the attribute to render it as black text.

Equivalent to the sequence ESC[30;m follwed by s and ended with ESC[39;m.

func Blink(s string) string

Blink wraps s with the attribute to make it blink.

Equivalent to the sequence ESC[5;m follwed by s and ended with ESC[25;m.

func Blue

func Blue(s string) string

Blue wraps s with the attribute to render it as blue text.

Equivalent to the sequence ESC[34;m follwed by s and ended with ESC[39;m.

func Bold

func Bold(s string) string

Bold wraps s with the attribute to render it in bold intensity.

Equivalent to the sequence ESC[1;m follwed by s and ended with ESC[22;m.

func Conceal

func Conceal(s string) string

Conceal wraps s with the attribute to render it concealed.

Equivalent to the sequence ESC[8;m follwed by s and ended with ESC[28;m.

func Cyan

func Cyan(s string) string

Cyan wraps s with the attribute to render it as cyan text.

Equivalent to the sequence ESC[36;m follwed by s and ended with ESC[39;m.

func Faint

func Faint(s string) string

Faint wraps s with the attribute to render it with dimmed intensity.

Equivalent to the sequence ESC[2;m follwed by s and ended with ESC[22;m.

func Green

func Green(s string) string

Green wraps s with the attribute to render it as green text.

Equivalent to the sequence ESC[32;m follwed by s and ended with ESC[39;m.

func Invert

func Invert(s string) string

Invert wraps s with the attribute to render it with inverted text/background colors.

Equivalent to the sequence ESC[7;m follwed by s and ended with ESC[27;m.

func Italic

func Italic(s string) string

Italic wraps s with the attribute to render it in italics.

Equivalent to the sequence ESC[3;m follwed by s and ended with ESC[23;m.

func Magenta

func Magenta(s string) string

Magenta wraps s with the attribute to render it as magenta text.

Equivalent to the sequence ESC[35;m follwed by s and ended with ESC[39;m.

func Red

func Red(s string) string

Red wraps s with the attribute to render it as red text.

Equivalent to the sequence ESC[31;m follwed by s and ended with ESC[39;m.

Example
package main

import (
	"fmt"

	"github.com/go-color-term/go-color-term/coloring"
)

func main() {
	fmt.Println(coloring.Red("wolf"))

}
Output:

�[31mwolf�[39m

func Strikethrough

func Strikethrough(s string) string

Strikethrough wraps s with the attribute to render it crossed.

Equivalent to the sequence ESC[9;m follwed by s and ended with ESC[29;m.

func Tagged added in v0.3.0

func Tagged(s string) string

Tagged allows to apply style attributes to a string using an HTML-like tag syntax to mark the start and end of each attribute (bold, italics, text and background colors and more).

For example, the following will be a valid string to pass to Tagged:

"The <b>wolf</b> <i>howls</i> at the <b><yellow>moon</yellow></b>"

That will result in the word "wolf" styled as bold text, the word "howls" in italics, and the word "moon" in bold and yellow color.

Note that Tagged will not generate any console output by itself, but the returned string is ready to be used with console output functions like fmt.Println and others.

Example
package main

import (
	"fmt"

	"github.com/go-color-term/go-color-term/coloring"
)

func main() {
	fmt.Println(coloring.Tagged("The <b>wolf</b> <i>howls</i> at the <b><yellow>moon</yellow></b>"))

}
Output:

The �[1mwolf�[22m �[3mhowls�[23m at the �[1m�[38;5;3mmoon�[39m�[22m�[0m
Example (AsymetricTags)
package main

import (
	"fmt"

	"github.com/go-color-term/go-color-term/coloring"
)

func main() {
	fmt.Println(coloring.Tagged("<b>Lorem ipsum <red>dolor sit </b>amet</red>"))

}
Output:

�[1mLorem ipsum �[38;5;1mdolor sit �[22mamet�[39m�[0m
Example (BrightColors)
package main

import (
	"fmt"

	"github.com/go-color-term/go-color-term/coloring"
)

func main() {
	fmt.Println(
		coloring.Tagged("<red bright>Bright color</red> and <bg-green bright>bright background</bg-green> enabled!"))

}
Output:

�[38;5;9mBright color�[39m and �[48;5;10mbright background�[49m enabled!�[0m
Example (Escape)
package main

import (
	"fmt"

	"github.com/go-color-term/go-color-term/coloring"
)

func main() {
	fmt.Println(coloring.Tagged("Escape is <b>bold</b>."))
	fmt.Println(coloring.Tagged("Escape is \\<b>bold\\</b>."))
	fmt.Println(coloring.Tagged("Escape is \\ <b>bold</b>."))
	fmt.Println(coloring.Tagged("Escape is <b>\\bold</b>."))
	fmt.Println(coloring.Tagged("Escape is <b>\\\\bold</b>."))
	fmt.Println(coloring.Tagged("Escape is \\\\<b>bold</b>."))
	fmt.Println(coloring.Tagged("Escape is \\\\\\<b>bold\\</b>."))
	fmt.Println(coloring.Tagged("Escape is <b>bold</b>.\\"))
	fmt.Println(coloring.Tagged("Escape is <b>bold</b>.\\\\<b>"))

}
Output:

Escape is �[1mbold�[22m.�[0m
Escape is <b>bold</b>.�[0m
Escape is  �[1mbold�[22m.�[0m
Escape is �[1mbold�[22m.�[0m
Escape is �[1m\bold�[22m.�[0m
Escape is \�[1mbold�[22m.�[0m
Escape is \<b>bold</b>.�[0m
Escape is �[1mbold�[22m.�[0m
Escape is �[1mbold�[22m.\�[1m�[0m
Example (Reset)
package main

import (
	"fmt"

	"github.com/go-color-term/go-color-term/coloring"
)

func main() {
	fmt.Println(
		coloring.Tagged("<bg-cyan bright><red bright><b><u><i>This starts very convoluted,<reset> but ends quietly."))

}
Output:

�[48;5;14m�[38;5;9m�[1m�[4m�[3mThis starts very convoluted,�[0m but ends quietly.�[0m
Example (UnclosedTags)
package main

import (
	"fmt"

	"github.com/go-color-term/go-color-term/coloring"
)

func main() {
	fmt.Println(coloring.Tagged("<b>Starting bold and <green>turning green"))

}
Output:

�[1mStarting bold and �[38;5;2mturning green�[0m

func Underline

func Underline(s string) string

Underline wraps s with the attribute to render it with an underline.

Equivalent to the sequence ESC[4;m follwed by s and ended with ESC[24;m.

func White

func White(s string) string

White wraps s with the attribute to render it as white text.

Equivalent to the sequence ESC[37;m follwed by s and ended with ESC[39;m.

func Yellow

func Yellow(s string) string

Yellow wraps s with the attribute to render it as yellow text.

Equivalent to the sequence ESC[33;m follwed by s and ended with ESC[39;m.

Types

type BackgroundColorBuilder

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

BackgroundColorBuilder allows to add attributes that sets the background color.

func (*BackgroundColorBuilder) Black

func (bg *BackgroundColorBuilder) Black() *StyleBuilder

Black adds an attribute to the current sequence to display black background. The original StyleBuilder is returned as there's no more attributes that can be specified to alter the background style.

func (*BackgroundColorBuilder) Blue

Blue adds an attribute to the current sequence to display blue background. The original StyleBuilder is returned as there's no more attributes that can be specified to alter the background style.

func (*BackgroundColorBuilder) Color

func (bg *BackgroundColorBuilder) Color(code int) *StyleBuilder

Color adds an attribute to set the background color in the 0-255 8-bit range. See constants declared in the coloring package to access the most common ones (0-15). The original StyleBuilder is returned as there's no more attributes that can be specified to alter the background style.

func (*BackgroundColorBuilder) Cyan

Cyan adds an attribute to the current sequence to display cyan background. The original StyleBuilder is returned as there's no more attributes that can be specified to alter the background style.

func (*BackgroundColorBuilder) Green

func (bg *BackgroundColorBuilder) Green() *StyleBuilder

Green adds an attribute to the current sequence to display green background. The original StyleBuilder is returned as there's no more attributes that can be specified to alter the background style.

func (*BackgroundColorBuilder) Magenta

func (bg *BackgroundColorBuilder) Magenta() *StyleBuilder

Magenta adds an attribute to the current sequence to display magenta background. The original StyleBuilder is returned as there's no more attributes that can be specified to alter the background style.

func (*BackgroundColorBuilder) Red

Red adds an attribute to the current sequence to display red background. The original StyleBuilder is returned as there's no more attributes that can be specified to alter the background style.

func (*BackgroundColorBuilder) Rgb

func (bg *BackgroundColorBuilder) Rgb(r, g, b int) *StyleBuilder

Rgb adds an attribute to set the background color to an RGB color. The terminal should support 24-bit colors. The original StyleBuilder is returned as there's no more attributes that can be specified to alter the background style.

func (*BackgroundColorBuilder) White

func (bg *BackgroundColorBuilder) White() *StyleBuilder

White adds an attribute to the current sequence to display white background. The original StyleBuilder is returned as there's no more attributes that can be specified to alter the background style.

func (*BackgroundColorBuilder) Yellow

func (bg *BackgroundColorBuilder) Yellow() *StyleBuilder

Yellow adds an attribute to the current sequence to display yellow background. The original StyleBuilder is returned as there's no more attributes that can be specified to alter the background style.

type ColorizerFunc

type ColorizerFunc = func(string) string

ColorizerFunc returns the supplied string with coloring attributes applied.

type ColorizerPrint

type ColorizerPrint = func(string)

ColorizerPrint can print colored strings.

type ExtraUtility added in v0.4.0

type ExtraUtility struct{}

ExtraUtility contains methods to apply additional style attributes. The zero value exposed through the coloring.Extras variable is ready to use.

Example (BrightRed)
package main

import (
	"fmt"

	"github.com/go-color-term/go-color-term/coloring"
)

func main() {
	fmt.Println(coloring.Extras.BrightRed("wolf"))

}
Output:

�[91mwolf�[39m
var Extras ExtraUtility

Extras allow to access to additional utility functions.

The functions exposed by the field might not work on all terminals.

func (*ExtraUtility) BgBrightBlack added in v0.4.0

func (ex *ExtraUtility) BgBrightBlack(s string) string

BgBrightBlack wraps s with the attribute to render it with bright black background.

Equivalent to the sequence ESC[100;m followed by s and ended with ESC[39;m.

func (*ExtraUtility) BgBrightBlue added in v0.4.0

func (ex *ExtraUtility) BgBrightBlue(s string) string

BgBrightBlue wraps s with the attribute to render it with bright blue background.

Equivalent to the sequence ESC[104;m followed by s and ended with ESC[39;m.

func (*ExtraUtility) BgBrightCyan added in v0.4.0

func (ex *ExtraUtility) BgBrightCyan(s string) string

BgBrightCyan wraps s with the attribute to render it with bright cyan background.

Equivalent to the sequence ESC[106;m followed by s and ended with ESC[39;m.

func (*ExtraUtility) BgBrightGreen added in v0.4.0

func (ex *ExtraUtility) BgBrightGreen(s string) string

BgBrightGreen wraps s with the attribute to render it with bright green background.

Equivalent to the sequence ESC[102;m followed by s and ended with ESC[39;m.

func (*ExtraUtility) BgBrightMagenta added in v0.4.0

func (ex *ExtraUtility) BgBrightMagenta(s string) string

BgBrightMagenta wraps s with the attribute to render it with bright magenta background.

Equivalent to the sequence ESC[105;m followed by s and ended with ESC[39;m.

func (*ExtraUtility) BgBrightRed added in v0.4.0

func (ex *ExtraUtility) BgBrightRed(s string) string

BgBrightRed wraps s with the attribute to render it with bright red background.

Equivalent to the sequence ESC[101;m followed by s and ended with ESC[39;m.

func (*ExtraUtility) BgBrightWhite added in v0.4.0

func (ex *ExtraUtility) BgBrightWhite(s string) string

BgBrightWhite wraps s with the attribute to render it with bright white background.

Equivalent to the sequence ESC[107;m followed by s and ended with ESC[39;m.

func (*ExtraUtility) BgBrightYellow added in v0.4.0

func (ex *ExtraUtility) BgBrightYellow(s string) string

BgBrightYellow wraps s with the attribute to render it with bright yellow background.

Equivalent to the sequence ESC[103;m followed by s and ended with ESC[39;m.

func (*ExtraUtility) BrightBlack added in v0.4.0

func (ex *ExtraUtility) BrightBlack(s string) string

BrightBlack wraps s with the attribute to render it as bright black text.

Equivalent to the sequence ESC[90;m followed by s and ended with ESC[39;m.

func (*ExtraUtility) BrightBlue added in v0.4.0

func (ex *ExtraUtility) BrightBlue(s string) string

BrightBlue wraps s with the attribute to render it as bright blue text.

Equivalent to the sequence ESC[94;m followed by s and ended with ESC[39;m.

func (*ExtraUtility) BrightCyan added in v0.4.0

func (ex *ExtraUtility) BrightCyan(s string) string

BrightCyan wraps s with the attribute to render it as bright cyan text.

Equivalent to the sequence ESC[96;m followed by s and ended with ESC[39;m.

func (*ExtraUtility) BrightGreen added in v0.4.0

func (ex *ExtraUtility) BrightGreen(s string) string

BrightGreen wraps s with the attribute to render it as bright green text.

Equivalent to the sequence ESC[92;m followed by s and ended with ESC[39;m.

func (*ExtraUtility) BrightMagenta added in v0.4.0

func (ex *ExtraUtility) BrightMagenta(s string) string

BrightMagenta wraps s with the attribute to render it as bright magenta text.

Equivalent to the sequence ESC[95;m followed by s and ended with ESC[39;m.

func (*ExtraUtility) BrightRed added in v0.4.0

func (ex *ExtraUtility) BrightRed(s string) string

BrightRed wraps s with the attribute to render it as bright red text.

Equivalent to the sequence ESC[91;m followed by s and ended with ESC[39;m.

func (*ExtraUtility) BrightWhite added in v0.4.0

func (ex *ExtraUtility) BrightWhite(s string) string

BrightWhite wraps s with the attribute to render it as bright white text.

Equivalent to the sequence ESC[97;m followed by s and ended with ESC[39;m.

func (*ExtraUtility) BrightYellow added in v0.4.0

func (ex *ExtraUtility) BrightYellow(s string) string

BrightYellow wraps s with the attribute to render it as bright yellow text.

Equivalent to the sequence ESC[93;m followed by s and ended with ESC[39;m.

type SentenceBuilder

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

A SentenceBuilder allows to create a long string of text applying different style attributes to different parts of the sentence.

It gives fine grained control of where the style attributes starts and ends independently of each other, allowing for styles spanning sections with different colors and attributes.

func Sentence

func Sentence() *SentenceBuilder

Sentence creates a new SentenceBuilder.

func (*SentenceBuilder) Background

func (builder *SentenceBuilder) Background(text string, color int) *SentenceBuilder

Background adds a string of text with a specific background color. The color must be in the range 0-255. See constants declared in the coloring package to access the most common ones (0-15).

func (*SentenceBuilder) BackgroundDefault added in v0.3.0

func (builder *SentenceBuilder) BackgroundDefault() *SentenceBuilder

BackgroundDefault sets the background color to the default one, irrespective of the current background color stack, which is also cleared.

func (*SentenceBuilder) BackgroundReset

func (builder *SentenceBuilder) BackgroundReset() *SentenceBuilder

BackgroundReset reverts the background color to the one that was in use before the last call to BackgroundSet or BackgroundRgbSet.

func (*SentenceBuilder) BackgroundRgb

func (builder *SentenceBuilder) BackgroundRgb(text string, r, g, b int) *SentenceBuilder

BackgroundRgb adds a string of text with a specific background color using RGB values. Each color component must be in the range 0-255. You can use hexadecimal numeric literals like BackgroundRgb("sample", 0xFF, 0xC0, 0x33).

func (*SentenceBuilder) BackgroundRgbSet

func (builder *SentenceBuilder) BackgroundRgbSet(r, g, b int) *SentenceBuilder

BackgroundRgbSet sets the current background color of the sentence using RGB values. Further added text will have this background color until another background color is set or the background color is reseted with BackgroundReset. You can use hexadecimal numeric literals like ColorRgb("sample", 0xFF, 0xC0, 0x33).

func (*SentenceBuilder) BackgroundSet

func (builder *SentenceBuilder) BackgroundSet(color int) *SentenceBuilder

BackgroundSet sets the current background color of the sentence. Further added text will have this background color until another background color is set or the background color is reseted with BackgroundReset.

func (builder *SentenceBuilder) Blink(text string) *SentenceBuilder

Blink adds a string of blinking text to the sentence.

func (*SentenceBuilder) BlinkEnd

func (builder *SentenceBuilder) BlinkEnd() *SentenceBuilder

BlinkEnd clears the blink attribute previously set with BlinkStart.

func (*SentenceBuilder) BlinkStart

func (builder *SentenceBuilder) BlinkStart() *SentenceBuilder

BlinkStart marks the start of blinking text. Use BlinkEnd to end the blinking section.

func (*SentenceBuilder) Bold

func (builder *SentenceBuilder) Bold(text string) *SentenceBuilder

Bold adds a string of bold text to the sentence.

func (*SentenceBuilder) BoldEnd

func (builder *SentenceBuilder) BoldEnd() *SentenceBuilder

BoldEnd clears the bold attribute previously set with BoldStart.

func (*SentenceBuilder) BoldStart

func (builder *SentenceBuilder) BoldStart() *SentenceBuilder

BoldStart marks the start of bold text. Use BoldEnd to end the bold section.

func (*SentenceBuilder) Color

func (builder *SentenceBuilder) Color(text string, color int) *SentenceBuilder

Color adds a string of text with a specific color. The color must be in the range 0-255. See constants declared in the coloring package to access the most common ones (0-15).

func (*SentenceBuilder) ColorDefault added in v0.3.0

func (builder *SentenceBuilder) ColorDefault() *SentenceBuilder

ColorDefault sets the color to the default one, irrespective of the current color stack, which is also cleared.

func (*SentenceBuilder) ColorReset

func (builder *SentenceBuilder) ColorReset() *SentenceBuilder

ColorReset reverts the color to the one that was in use before the last call to ColorSet or ColorRgbSet.

func (*SentenceBuilder) ColorRgb

func (builder *SentenceBuilder) ColorRgb(text string, r, g, b int) *SentenceBuilder

ColorRgb adds a string of text with a specific color using RGB values. Each color component must be in the range 0-255. You can use hexadecimal numeric literals like ColorRgb("sample", 0xFF, 0xC0, 0x33).

func (*SentenceBuilder) ColorRgbSet

func (builder *SentenceBuilder) ColorRgbSet(r, g, b int) *SentenceBuilder

ColorRgbSet sets the current text color of the sentence using RGB values. Further added text will have this color until another color is set or the color is reseted with ColorReset. You can use hexadecimal numeric literals like ColorRgb("sample", 0xFF, 0xC0, 0x33).

func (*SentenceBuilder) ColorSet

func (builder *SentenceBuilder) ColorSet(color int) *SentenceBuilder

ColorSet sets the current text color of the sentence. Further added text will have this color until another color is set or the color is reseted with ColorReset.

func (*SentenceBuilder) Conceal

func (builder *SentenceBuilder) Conceal(text string) *SentenceBuilder

Conceal adds a string of concealed text to the sentence.

func (*SentenceBuilder) ConcealEnd

func (builder *SentenceBuilder) ConcealEnd() *SentenceBuilder

ConcealEnd clears the conceal attribute previously set with ConcealStart.

func (*SentenceBuilder) ConcealStart

func (builder *SentenceBuilder) ConcealStart() *SentenceBuilder

ConcealStart marks the start of concealed text. Use ConcealEnd to end the concealed section.

func (*SentenceBuilder) Faint

func (builder *SentenceBuilder) Faint(text string) *SentenceBuilder

Faint adds a string of dimmed text to the sentence.

func (*SentenceBuilder) FaintEnd

func (builder *SentenceBuilder) FaintEnd() *SentenceBuilder

FaintEnd clears the faint attribute previously set with FaintStart.

func (*SentenceBuilder) FaintStart

func (builder *SentenceBuilder) FaintStart() *SentenceBuilder

FaintStart marks the start of dimmed text. Use FaintEnd to end the dimmed section.

func (*SentenceBuilder) Invert

func (builder *SentenceBuilder) Invert(text string) *SentenceBuilder

Invert adds a string of text with inverted colors to the sentence.

func (*SentenceBuilder) InvertEnd

func (builder *SentenceBuilder) InvertEnd() *SentenceBuilder

InvertEnd clears the invert attribute previously set with InvertStart.

func (*SentenceBuilder) InvertStart

func (builder *SentenceBuilder) InvertStart() *SentenceBuilder

InvertStart marks the start of text with inverted colors. Use InvertEnd to end the inverted colors section.

func (*SentenceBuilder) Italic

func (builder *SentenceBuilder) Italic(text string) *SentenceBuilder

Italic adds a string of italic text to the sentence.

func (*SentenceBuilder) ItalicEnd

func (builder *SentenceBuilder) ItalicEnd() *SentenceBuilder

ItalicEnd clears the italics attribute previously set with ItalicStart.

func (*SentenceBuilder) ItalicStart

func (builder *SentenceBuilder) ItalicStart() *SentenceBuilder

ItalicStart marks the start of italics text. Use ItalicEnd to end the italics section.

func (*SentenceBuilder) Print

func (builder *SentenceBuilder) Print()

Print reset all the styles and outputs the currently built sentence on os.Stdout.

func (*SentenceBuilder) PrintAndClear

func (builder *SentenceBuilder) PrintAndClear() *SentenceBuilder

PrintAndClear performs a SentenceBuilder.Print and then clears the current sentence buffer and returns this SentenceBuilder, allowing to start building a new sentence right away.

func (*SentenceBuilder) Println

func (builder *SentenceBuilder) Println()

Println reset all the styles and outputs the currently built sentence on os.Stdout adding a new line at the end.

func (*SentenceBuilder) PrintlnAndClear

func (builder *SentenceBuilder) PrintlnAndClear() *SentenceBuilder

PrintlnAndClear performs a SentenceBuilder.Println and then clears the current sentence buffer and returns this SentenceBuilder, allowing to start building a new sentence right away.

func (*SentenceBuilder) Reset

func (builder *SentenceBuilder) Reset() *SentenceBuilder

Reset clears al formatting attributes currently applied to the sentence.

func (*SentenceBuilder) Strikethrough

func (builder *SentenceBuilder) Strikethrough(text string) *SentenceBuilder

Strikethrough adds a string of crossed text to the sentence.

func (*SentenceBuilder) StrikethroughEnd

func (builder *SentenceBuilder) StrikethroughEnd() *SentenceBuilder

StrikethroughEnd clears the strikethrough attribute previously set with StrikethroughStart.

func (*SentenceBuilder) StrikethroughStart

func (builder *SentenceBuilder) StrikethroughStart() *SentenceBuilder

StrikethroughStart marks the start of crossed text. Use StrikethroughEnd to end the crossed section.

func (*SentenceBuilder) String

func (builder *SentenceBuilder) String() string

String returns a string with the currently built sentence. It also allows to use this instance of SenteceBuilder in any place that expects a Stringer type.

func (*SentenceBuilder) StyledText

func (builder *SentenceBuilder) StyledText() *StyledText

StyledText returns a StyledText instance that you can use in any place that expects a Stringer type. Further changes to this builder doesn't affect the returned StyledText.

Note that the returned StyledText will contain a reset attribute at the end. This is to safely concatenate it with other strings without leaving open any style attribute.

func (*SentenceBuilder) Text

func (builder *SentenceBuilder) Text(text string) *SentenceBuilder

Text adds a string of unformatted text to the sentence.

func (*SentenceBuilder) Underline

func (builder *SentenceBuilder) Underline(text string) *SentenceBuilder

Underline adds a string of underlined text to the sentence.

func (*SentenceBuilder) UnderlineEnd

func (builder *SentenceBuilder) UnderlineEnd() *SentenceBuilder

UnderlineEnd clears the underline attribute previously set with UnderlineStart.

func (*SentenceBuilder) UnderlineStart

func (builder *SentenceBuilder) UnderlineStart() *SentenceBuilder

UnderlineStart marks the start of underlined text. Use UnderlineEnd to end the underlined section.

type StyleBuilder

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

StyleBuilder allows to compose multiple color/formatting attributes in a single escape sequence. It can start with a predefined text to decorate (see For(string)) or empty (see New()).

Example (Func)
package main

import (
	"fmt"

	"github.com/go-color-term/go-color-term/coloring"
)

func main() {
	boldRed := coloring.New().Bold().Red().Func()

	fmt.Printf("Here comes the %s to extinguish the %s\n", boldRed("fire truck"), boldRed("fire"))

}
Output:

Here comes the �[1;31mfire truck�[0m to extinguish the �[1;31mfire�[0m
Example (Print)
package main

import (
	"github.com/go-color-term/go-color-term/coloring"
)

func main() {
	printAlert := coloring.New().White().Bold().Background().Red().Print()

	printAlert("ALERT: The house is on fire!!!")

}
Output:

�[37;1;41mALERT: The house is on fire!!!�[0m

func For

func For(s string) *StyleBuilder

For creates a new StyleBuilder with a predefined text.

func New

func New() *StyleBuilder

New creates an empty StyleBuilder. You mostly use this when you plan to call the Func() function to get a ColorizerFunc that lets you specify the text to colorize on a call-by-call basis.

func (*StyleBuilder) Background

func (builder *StyleBuilder) Background() *BackgroundColorBuilder

Background returns a BackgroundColorBuilder which exposes funtions to set the background color. After calling this function, it's required to invoke some of the BackgroundColorBuilder functions to return to the original builder.

func (*StyleBuilder) Black

func (builder *StyleBuilder) Black() *StyleBuilder

Black adds an attribute to the current sequence to render black text.

func (builder *StyleBuilder) Blink() *StyleBuilder

Blink adds an attribute to the current sequence to render blinking text.

func (*StyleBuilder) Blue

func (builder *StyleBuilder) Blue() *StyleBuilder

Blue adds an attribute to the current sequence to render blue text.

func (*StyleBuilder) Bold

func (builder *StyleBuilder) Bold() *StyleBuilder

Bold adds an attribute to the current sequence to render bold text.

func (*StyleBuilder) Color

func (builder *StyleBuilder) Color(code int) *StyleBuilder

Color adds an attribute to the current sequence to render text with a color in the 0-255 8-bit range. See constants declared in the coloring package to access the most common ones (0-15).

func (*StyleBuilder) Conceal added in v0.2.0

func (builder *StyleBuilder) Conceal() *StyleBuilder

Conceal adds an attribute to the current sequence to render the text concealed (hidden). Check compatibility for different OS/terminals as it's not widely supported.

func (*StyleBuilder) Cyan

func (builder *StyleBuilder) Cyan() *StyleBuilder

Cyan adds an attribute to the current sequence to render cyan text.

func (*StyleBuilder) Faint

func (builder *StyleBuilder) Faint() *StyleBuilder

Faint adds an attribute to the current sequence to render faint text.

func (*StyleBuilder) Func

func (builder *StyleBuilder) Func() ColorizerFunc

Func returns a ColorizerFunc function that can be invoked with different texts to apply the styles currently defined on this builder. Further changes to this builder doesn't affect the output of the returned ColorizerFunc.

func (*StyleBuilder) Green

func (builder *StyleBuilder) Green() *StyleBuilder

Green adds an attribute to the current sequence to render green text.

func (*StyleBuilder) Invert added in v0.4.0

func (builder *StyleBuilder) Invert() *StyleBuilder

Invert adds an attribute to the current sequence to invert the current color and background color.

func (*StyleBuilder) Italic

func (builder *StyleBuilder) Italic() *StyleBuilder

Italic adds an attribute to the current sequence to render italic text.

func (*StyleBuilder) Magenta

func (builder *StyleBuilder) Magenta() *StyleBuilder

Magenta adds an attribute to the current sequence to render magenta text.

func (*StyleBuilder) Print

func (builder *StyleBuilder) Print() ColorizerPrint

Print returns a ColorizerPrint function that can be invoked with different texts to print them on screen with the styles currently defined on this builder. Further changes to this builder doesn't affect the output of the returned ColorizerPrint.

func (*StyleBuilder) Red

func (builder *StyleBuilder) Red() *StyleBuilder

Red adds an attribute to the current sequence to render red text.

func (*StyleBuilder) Rgb

func (builder *StyleBuilder) Rgb(r, g, b int) *StyleBuilder

Rgb adds an attribute to the current sequence to render text with an RGB color. The terminal should support 24-bit colors.

func (*StyleBuilder) Strikethrough

func (builder *StyleBuilder) Strikethrough() *StyleBuilder

Strikethrough adds an attribute to the current sequence to render crossed text.

func (*StyleBuilder) String

func (builder *StyleBuilder) String() string

String returns the passed string to For(string) decorated with the attributes added so far. The decorated sequence resets all attributes at the end, so it's not suitable to cobine with an already decorated string, as it will reset the previous styles, if any.

func (*StyleBuilder) StyleText

func (builder *StyleBuilder) StyleText(s string) *StyledText

StyleText returns a StyledText instance that you can use in any place that expects a Stringer type. Further changes to this builder doesn't affect the returned StyledText.

func (*StyleBuilder) Styled

func (builder *StyleBuilder) Styled() *StyledText

Styled returns a StyledText instance that you can use in any place that expects a Stringer type. Further changes to this builder doesn't affect the returned StyledText.

It uses the string that was passed to this StyleBuilder instance if it was created with For(string) function.

If you created the StyleBuilder instance with the New function, just call StyleText(string) to style a particular string.

func (*StyleBuilder) Underline

func (builder *StyleBuilder) Underline() *StyleBuilder

Underline adds an attribute to the current sequence to render underline text.

func (*StyleBuilder) White

func (builder *StyleBuilder) White() *StyleBuilder

White adds an attribute to the current sequence to render white text.

func (*StyleBuilder) Yellow

func (builder *StyleBuilder) Yellow() *StyleBuilder

Yellow adds an attribute to the current sequence to render yellow text.

type StyledText

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

StyledText represents a string decorated with style attributes.

It can be obtained from a StyleBuilder or a SentenceBuilder.

func (*StyledText) String

func (st *StyledText) String() string

String returns the string represented by this StyledText with the corresponding style attributes applied during it's creation.

func (*StyledText) Unformatted

func (st *StyledText) Unformatted() string

Unformatted returns the original string without any style attributes.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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