text

package
v6.5.8 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2024 License: MIT Imports: 11 Imported by: 399

README

text

Go Reference

Package with utility functions to manipulate strings/text.

Used heavily in the other packages in this repo (list, progress, and table).

Documentation

Index

Examples

Constants

View Source
const (
	CSIStartRune    = rune(91) // [
	CSIStopRune     = 'm'
	EscapeReset     = EscapeStart + "0" + EscapeStop
	EscapeStart     = "\x1b["
	EscapeStartRune = rune(27) // \x1b
	EscapeStop      = "m"
	EscapeStopRune  = 'm'
	OSIStartRune    = rune(93) // ]
	OSIStopRune     = '\\'
)

Constants

Variables

View Source
var ANSICodesSupported = areANSICodesSupported()

ANSICodesSupported will be true on consoles where ANSI Escape Codes/Sequences are supported.

Functions

func DisableColors

func DisableColors()

DisableColors (forcefully) disables color coding globally.

func EnableColors

func EnableColors()

EnableColors (forcefully) enables color coding globally.

func Escape

func Escape(str string, escapeSeq string) string

Escape encodes the string with the ANSI Escape Sequence. For ex.:

Escape("Ghost", "") == "Ghost"
Escape("Ghost", "\x1b[91m") == "\x1b[91mGhost\x1b[0m"
Escape("\x1b[94mGhost\x1b[0mLady", "\x1b[91m") == "\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m"
Escape("Nymeria\x1b[94mGhost\x1b[0mLady", "\x1b[91m") == "\x1b[91mNymeria\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m"
Escape("Nymeria \x1b[94mGhost\x1b[0m Lady", "\x1b[91m") == "\x1b[91mNymeria \x1b[94mGhost\x1b[0m\x1b[91m Lady\x1b[0m"
Example
fmt.Printf("Escape(%#v, %#v) == %#v\n", "Ghost", "", Escape("Ghost", ""))
fmt.Printf("Escape(%#v, %#v) == %#v\n", "Ghost", FgHiRed.EscapeSeq(), Escape("Ghost", FgHiRed.EscapeSeq()))
fmt.Printf("Escape(%#v, %#v) == %#v\n", FgHiBlue.Sprint("Ghost")+"Lady", FgHiRed.EscapeSeq(), Escape(FgHiBlue.Sprint("Ghost")+"Lady", FgHiRed.EscapeSeq()))
fmt.Printf("Escape(%#v, %#v) == %#v\n", "Nymeria"+FgHiBlue.Sprint("Ghost")+"Lady", FgHiRed.EscapeSeq(), Escape("Nymeria"+FgHiBlue.Sprint("Ghost")+"Lady", FgHiRed.EscapeSeq()))
fmt.Printf("Escape(%#v, %#v) == %#v\n", "Nymeria "+FgHiBlue.Sprint("Ghost")+" Lady", FgHiRed.EscapeSeq(), Escape("Nymeria "+FgHiBlue.Sprint("Ghost")+" Lady", FgHiRed.EscapeSeq()))
Output:

Escape("Ghost", "") == "Ghost"
Escape("Ghost", "\x1b[91m") == "\x1b[91mGhost\x1b[0m"
Escape("\x1b[94mGhost\x1b[0mLady", "\x1b[91m") == "\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m"
Escape("Nymeria\x1b[94mGhost\x1b[0mLady", "\x1b[91m") == "\x1b[91mNymeria\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m"
Escape("Nymeria \x1b[94mGhost\x1b[0m Lady", "\x1b[91m") == "\x1b[91mNymeria \x1b[94mGhost\x1b[0m\x1b[91m Lady\x1b[0m"

func Filter

func Filter(s []string, f func(string) bool) []string

Filter filters the slice 's' to items which return truth when passed to 'f'.

Example
slice := []string{"Arya Stark", "Bran Stark", "Jon Snow", "Sansa Stark"}
filter := func(item string) bool {
	return strings.HasSuffix(item, "Stark")
}
fmt.Printf("%#v\n", Filter(slice, filter))
Output:

[]string{"Arya Stark", "Bran Stark", "Sansa Stark"}
func Hyperlink(url, text string) string

func InsertEveryN

func InsertEveryN(str string, runeToInsert rune, n int) string

InsertEveryN inserts the rune every N characters in the string. For ex.:

InsertEveryN("Ghost", '-', 1) == "G-h-o-s-t"
InsertEveryN("Ghost", '-', 2) == "Gh-os-t"
InsertEveryN("Ghost", '-', 3) == "Gho-st"
InsertEveryN("Ghost", '-', 4) == "Ghos-t"
InsertEveryN("Ghost", '-', 5) == "Ghost"
Example
fmt.Printf("InsertEveryN(\"Ghost\", '-', 0): %#v\n", InsertEveryN("Ghost", '-', 0))
fmt.Printf("InsertEveryN(\"Ghost\", '-', 1): %#v\n", InsertEveryN("Ghost", '-', 1))
fmt.Printf("InsertEveryN(\"Ghost\", '-', 2): %#v\n", InsertEveryN("Ghost", '-', 2))
fmt.Printf("InsertEveryN(\"Ghost\", '-', 3): %#v\n", InsertEveryN("Ghost", '-', 3))
fmt.Printf("InsertEveryN(\"Ghost\", '-', 4): %#v\n", InsertEveryN("Ghost", '-', 4))
fmt.Printf("InsertEveryN(\"Ghost\", '-', 5): %#v\n", InsertEveryN("Ghost", '-', 5))
fmt.Printf("InsertEveryN(\"\\x1b[33mGhost\\x1b[0m\", '-', 0): %#v\n", InsertEveryN("\x1b[33mGhost\x1b[0m", '-', 0))
fmt.Printf("InsertEveryN(\"\\x1b[33mGhost\\x1b[0m\", '-', 1): %#v\n", InsertEveryN("\x1b[33mGhost\x1b[0m", '-', 1))
fmt.Printf("InsertEveryN(\"\\x1b[33mGhost\\x1b[0m\", '-', 2): %#v\n", InsertEveryN("\x1b[33mGhost\x1b[0m", '-', 2))
fmt.Printf("InsertEveryN(\"\\x1b[33mGhost\\x1b[0m\", '-', 3): %#v\n", InsertEveryN("\x1b[33mGhost\x1b[0m", '-', 3))
fmt.Printf("InsertEveryN(\"\\x1b[33mGhost\\x1b[0m\", '-', 4): %#v\n", InsertEveryN("\x1b[33mGhost\x1b[0m", '-', 4))
fmt.Printf("InsertEveryN(\"\\x1b[33mGhost\\x1b[0m\", '-', 5): %#v\n", InsertEveryN("\x1b[33mGhost\x1b[0m", '-', 5))
Output:

InsertEveryN("Ghost", '-', 0): "Ghost"
InsertEveryN("Ghost", '-', 1): "G-h-o-s-t"
InsertEveryN("Ghost", '-', 2): "Gh-os-t"
InsertEveryN("Ghost", '-', 3): "Gho-st"
InsertEveryN("Ghost", '-', 4): "Ghos-t"
InsertEveryN("Ghost", '-', 5): "Ghost"
InsertEveryN("\x1b[33mGhost\x1b[0m", '-', 0): "\x1b[33mGhost\x1b[0m"
InsertEveryN("\x1b[33mGhost\x1b[0m", '-', 1): "\x1b[33mG-h-o-s-t\x1b[0m"
InsertEveryN("\x1b[33mGhost\x1b[0m", '-', 2): "\x1b[33mGh-os-t\x1b[0m"
InsertEveryN("\x1b[33mGhost\x1b[0m", '-', 3): "\x1b[33mGho-st\x1b[0m"
InsertEveryN("\x1b[33mGhost\x1b[0m", '-', 4): "\x1b[33mGhos-t\x1b[0m"
InsertEveryN("\x1b[33mGhost\x1b[0m", '-', 5): "\x1b[33mGhost\x1b[0m"

func LongestLineLen

func LongestLineLen(str string) int

LongestLineLen returns the length of the longest "line" within the argument string. For ex.:

LongestLineLen("Ghost!\nCome back here!\nRight now!") == 15
Example
fmt.Printf("LongestLineLen(\"\"): %d\n", LongestLineLen(""))
fmt.Printf("LongestLineLen(\"\\n\\n\"): %d\n", LongestLineLen("\n\n"))
fmt.Printf("LongestLineLen(\"Ghost\"): %d\n", LongestLineLen("Ghost"))
fmt.Printf("LongestLineLen(\"Ghostツ\"): %d\n", LongestLineLen("Ghostツ"))
fmt.Printf("LongestLineLen(\"Winter\\nIs\\nComing\"): %d\n", LongestLineLen("Winter\nIs\nComing"))
fmt.Printf("LongestLineLen(\"Mother\\nOf\\nDragons\"): %d\n", LongestLineLen("Mother\nOf\nDragons"))
fmt.Printf("LongestLineLen(\"\\x1b[33mMother\\x1b[0m\\nOf\\nDragons\"): %d\n", LongestLineLen("\x1b[33mMother\x1b[0m\nOf\nDragons"))
Output:

LongestLineLen(""): 0
LongestLineLen("\n\n"): 0
LongestLineLen("Ghost"): 5
LongestLineLen("Ghostツ"): 7
LongestLineLen("Winter\nIs\nComing"): 6
LongestLineLen("Mother\nOf\nDragons"): 7
LongestLineLen("\x1b[33mMother\x1b[0m\nOf\nDragons"): 7

func OverrideRuneWidthEastAsianWidth added in v6.3.7

func OverrideRuneWidthEastAsianWidth(val bool)

OverrideRuneWidthEastAsianWidth can *probably* help with alignment, and length calculation issues when dealing with Unicode character-set and a non-English language set in the LANG variable.

Set this to 'false' to force the "runewidth" library to pretend to deal with English character-set. Be warned that if the text/content you are dealing with contains East Asian character-set, this may result in unexpected behavior.

References: * https://github.com/mattn/go-runewidth/issues/64#issuecomment-1221642154 * https://github.com/jedib0t/go-pretty/issues/220 * https://github.com/jedib0t/go-pretty/issues/204

func Pad

func Pad(str string, maxLen int, paddingChar rune) string

Pad pads the given string with as many characters as needed to make it as long as specified (maxLen). This function does not count escape sequences while calculating length of the string. Ex.:

Pad("Ghost", 0, ' ') == "Ghost"
Pad("Ghost", 3, ' ') == "Ghost"
Pad("Ghost", 5, ' ') == "Ghost"
Pad("Ghost", 7, ' ') == "Ghost  "
Pad("Ghost", 10, '.') == "Ghost....."
Example
fmt.Printf("%#v\n", Pad("Ghost", 0, ' '))
fmt.Printf("%#v\n", Pad("Ghost", 3, ' '))
fmt.Printf("%#v\n", Pad("Ghost", 5, ' '))
fmt.Printf("%#v\n", Pad("\x1b[33mGhost\x1b[0m", 7, '-'))
fmt.Printf("%#v\n", Pad("\x1b[33mGhost\x1b[0m", 10, '.'))
Output:

"Ghost"
"Ghost"
"Ghost"
"\x1b[33mGhost\x1b[0m--"
"\x1b[33mGhost\x1b[0m....."

func ProcessCRLF added in v6.5.2

func ProcessCRLF(str string) string

ProcessCRLF converts "\r\n" to "\n", and processes lone "\r" by moving the cursor/carriage to the start of the line and overwrites the contents accordingly. Ex.:

ProcessCRLF("abc") == "abc" ProcessCRLF("abc\r\ndef") == "abc\ndef" ProcessCRLF("abc\r\ndef\rghi") == "abc\nghi" ProcessCRLF("abc\r\ndef\rghi\njkl") == "abc\nghi\njkl" ProcessCRLF("abc\r\ndef\rghi\njkl\r") == "abc\nghi\njkl" ProcessCRLF("abc\r\ndef\rghi\rjkl\rmn") == "abc\nmnl"

Example
fmt.Printf("%#v\n", ProcessCRLF("abc"))
fmt.Printf("%#v\n", ProcessCRLF("abc\r\ndef"))
fmt.Printf("%#v\n", ProcessCRLF("abc\r\ndef\rghi"))
fmt.Printf("%#v\n", ProcessCRLF("abc\r\ndef\rghi\njkl"))
fmt.Printf("%#v\n", ProcessCRLF("abc\r\ndef\rghi\njkl\r"))
fmt.Printf("%#v\n", ProcessCRLF("abc\r\ndef\rghi\rjkl\rmn"))
Output:

"abc"
"abc\ndef"
"abc\nghi"
"abc\nghi\njkl"
"abc\nghi\njkl"
"abc\nmnl"

func RepeatAndTrim

func RepeatAndTrim(str string, maxRunes int) string

RepeatAndTrim repeats the given string until it is as long as maxRunes. For ex.:

RepeatAndTrim("", 5) == ""
RepeatAndTrim("Ghost", 0) == ""
RepeatAndTrim("Ghost", 5) == "Ghost"
RepeatAndTrim("Ghost", 7) == "GhostGh"
RepeatAndTrim("Ghost", 10) == "GhostGhost"
Example
fmt.Printf("RepeatAndTrim(\"\", 5): %#v\n", RepeatAndTrim("", 5))
fmt.Printf("RepeatAndTrim(\"Ghost\", 0): %#v\n", RepeatAndTrim("Ghost", 0))
fmt.Printf("RepeatAndTrim(\"Ghost\", 3): %#v\n", RepeatAndTrim("Ghost", 3))
fmt.Printf("RepeatAndTrim(\"Ghost\", 5): %#v\n", RepeatAndTrim("Ghost", 5))
fmt.Printf("RepeatAndTrim(\"Ghost\", 7): %#v\n", RepeatAndTrim("Ghost", 7))
fmt.Printf("RepeatAndTrim(\"Ghost\", 10): %#v\n", RepeatAndTrim("Ghost", 10))
Output:

RepeatAndTrim("", 5): ""
RepeatAndTrim("Ghost", 0): ""
RepeatAndTrim("Ghost", 3): "Gho"
RepeatAndTrim("Ghost", 5): "Ghost"
RepeatAndTrim("Ghost", 7): "GhostGh"
RepeatAndTrim("Ghost", 10): "GhostGhost"

func RuneCount deprecated

func RuneCount(str string) int

RuneCount is similar to utf8.RuneCountInString, except for the fact that it ignores escape sequences while counting. For ex.:

RuneCount("") == 0
RuneCount("Ghost") == 5
RuneCount("\x1b[33mGhost\x1b[0m") == 5
RuneCount("\x1b[33mGhost\x1b[0") == 5

Deprecated: in favor of RuneWidthWithoutEscSequences

Example
fmt.Printf("RuneCount(\"\"): %d\n", RuneCount(""))
fmt.Printf("RuneCount(\"Ghost\"): %d\n", RuneCount("Ghost"))
fmt.Printf("RuneCount(\"Ghostツ\"): %d\n", RuneCount("Ghostツ"))
fmt.Printf("RuneCount(\"\\x1b[33mGhost\\x1b[0m\"): %d\n", RuneCount("\x1b[33mGhost\x1b[0m"))
fmt.Printf("RuneCount(\"\\x1b[33mGhost\\x1b[0\"): %d\n", RuneCount("\x1b[33mGhost\x1b[0"))
Output:

RuneCount(""): 0
RuneCount("Ghost"): 5
RuneCount("Ghostツ"): 7
RuneCount("\x1b[33mGhost\x1b[0m"): 5
RuneCount("\x1b[33mGhost\x1b[0"): 5

func RuneWidth

func RuneWidth(r rune) int

RuneWidth returns the mostly accurate character-width of the rune. This is not 100% accurate as the character width is usually dependent on the typeface (font) used in the console/terminal. For ex.:

RuneWidth('A') == 1
RuneWidth('ツ') == 2
RuneWidth('⊙') == 1
RuneWidth('︿') == 2
RuneWidth(0x27) == 0
Example
fmt.Printf("RuneWidth('A'): %d\n", RuneWidth('A'))
fmt.Printf("RuneWidth('ツ'): %d\n", RuneWidth('ツ'))
fmt.Printf("RuneWidth('⊙'): %d\n", RuneWidth('⊙'))
fmt.Printf("RuneWidth('︿'): %d\n", RuneWidth('︿'))
fmt.Printf("RuneWidth(rune(27)): %d\n", RuneWidth(rune(27))) // ANSI escape sequence
Output:

RuneWidth('A'): 1
RuneWidth('ツ'): 2
RuneWidth('⊙'): 1
RuneWidth('︿'): 2
RuneWidth(rune(27)): 0

func RuneWidthWithoutEscSequences added in v6.3.3

func RuneWidthWithoutEscSequences(str string) int

RuneWidthWithoutEscSequences is similar to RuneWidth, except for the fact that it ignores escape sequences while counting. For ex.:

RuneWidthWithoutEscSequences("") == 0
RuneWidthWithoutEscSequences("Ghost") == 5
RuneWidthWithoutEscSequences("\x1b[33mGhost\x1b[0m") == 5
RuneWidthWithoutEscSequences("\x1b[33mGhost\x1b[0") == 5
Example
fmt.Printf("RuneWidthWithoutEscSequences(\"\"): %d\n", RuneWidthWithoutEscSequences(""))
fmt.Printf("RuneWidthWithoutEscSequences(\"Ghost\"): %d\n", RuneWidthWithoutEscSequences("Ghost"))
fmt.Printf("RuneWidthWithoutEscSequences(\"Ghostツ\"): %d\n", RuneWidthWithoutEscSequences("Ghostツ"))
fmt.Printf("RuneWidthWithoutEscSequences(\"\\x1b[33mGhost\\x1b[0m\"): %d\n", RuneWidthWithoutEscSequences("\x1b[33mGhost\x1b[0m"))
fmt.Printf("RuneWidthWithoutEscSequences(\"\\x1b[33mGhost\\x1b[0\"): %d\n", RuneWidthWithoutEscSequences("\x1b[33mGhost\x1b[0"))
Output:

RuneWidthWithoutEscSequences(""): 0
RuneWidthWithoutEscSequences("Ghost"): 5
RuneWidthWithoutEscSequences("Ghostツ"): 7
RuneWidthWithoutEscSequences("\x1b[33mGhost\x1b[0m"): 5
RuneWidthWithoutEscSequences("\x1b[33mGhost\x1b[0"): 5

func Snip

func Snip(str string, length int, snipIndicator string) string

Snip returns the given string with a fixed length. For ex.:

Snip("Ghost", 0, "~") == "Ghost"
Snip("Ghost", 1, "~") == "~"
Snip("Ghost", 3, "~") == "Gh~"
Snip("Ghost", 5, "~") == "Ghost"
Snip("Ghost", 7, "~") == "Ghost  "
Snip("\x1b[33mGhost\x1b[0m", 7, "~") == "\x1b[33mGhost\x1b[0m  "
Example
fmt.Printf("Snip(\"Ghost\", 0, \"~\"): %#v\n", Snip("Ghost", 0, "~"))
fmt.Printf("Snip(\"Ghost\", 1, \"~\"): %#v\n", Snip("Ghost", 1, "~"))
fmt.Printf("Snip(\"Ghost\", 3, \"~\"): %#v\n", Snip("Ghost", 3, "~"))
fmt.Printf("Snip(\"Ghost\", 5, \"~\"): %#v\n", Snip("Ghost", 5, "~"))
fmt.Printf("Snip(\"Ghost\", 7, \"~\"): %#v\n", Snip("Ghost", 7, "~"))
fmt.Printf("Snip(\"\\x1b[33mGhost\\x1b[0m\", 7, \"~\"): %#v\n", Snip("\x1b[33mGhost\x1b[0m", 7, "~"))
Output:

Snip("Ghost", 0, "~"): "Ghost"
Snip("Ghost", 1, "~"): "~"
Snip("Ghost", 3, "~"): "Gh~"
Snip("Ghost", 5, "~"): "Ghost"
Snip("Ghost", 7, "~"): "Ghost"
Snip("\x1b[33mGhost\x1b[0m", 7, "~"): "\x1b[33mGhost\x1b[0m"

func StripEscape

func StripEscape(str string) string

StripEscape strips all ANSI Escape Sequence from the string. For ex.:

StripEscape("Ghost") == "Ghost"
StripEscape("\x1b[91mGhost\x1b[0m") == "Ghost"
StripEscape("\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m") == "GhostLady"
StripEscape("\x1b[91mNymeria\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m") == "NymeriaGhostLady"
StripEscape("\x1b[91mNymeria \x1b[94mGhost\x1b[0m\x1b[91m Lady\x1b[0m") == "Nymeria Ghost Lady"
Example
fmt.Printf("StripEscape(%#v) == %#v\n", "Ghost", StripEscape("Ghost"))
fmt.Printf("StripEscape(%#v) == %#v\n", "\x1b[91mGhost\x1b[0m", StripEscape("\x1b[91mGhost\x1b[0m"))
fmt.Printf("StripEscape(%#v) == %#v\n", "\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m", StripEscape("\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m"))
fmt.Printf("StripEscape(%#v) == %#v\n", "\x1b[91mNymeria\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m", StripEscape("\x1b[91mNymeria\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m"))
fmt.Printf("StripEscape(%#v) == %#v\n", "\x1b[91mNymeria \x1b[94mGhost\x1b[0m\x1b[91m Lady\x1b[0m", StripEscape("\x1b[91mNymeria \x1b[94mGhost\x1b[0m\x1b[91m Lady\x1b[0m"))
Output:

StripEscape("Ghost") == "Ghost"
StripEscape("\x1b[91mGhost\x1b[0m") == "Ghost"
StripEscape("\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m") == "GhostLady"
StripEscape("\x1b[91mNymeria\x1b[94mGhost\x1b[0m\x1b[91mLady\x1b[0m") == "NymeriaGhostLady"
StripEscape("\x1b[91mNymeria \x1b[94mGhost\x1b[0m\x1b[91m Lady\x1b[0m") == "Nymeria Ghost Lady"

func Trim

func Trim(str string, maxLen int) string

Trim trims a string to the given length while ignoring escape sequences. For ex.:

Trim("Ghost", 3) == "Gho"
Trim("Ghost", 6) == "Ghost"
Trim("\x1b[33mGhost\x1b[0m", 3) == "\x1b[33mGho\x1b[0m"
Trim("\x1b[33mGhost\x1b[0m", 6) == "\x1b[33mGhost\x1b[0m"
Example
fmt.Printf("Trim(\"Ghost\", 0): %#v\n", Trim("Ghost", 0))
fmt.Printf("Trim(\"Ghost\", 3): %#v\n", Trim("Ghost", 3))
fmt.Printf("Trim(\"Ghost\", 6): %#v\n", Trim("Ghost", 6))
fmt.Printf("Trim(\"\\x1b[33mGhost\\x1b[0m\", 0): %#v\n", Trim("\x1b[33mGhost\x1b[0m", 0))
fmt.Printf("Trim(\"\\x1b[33mGhost\\x1b[0m\", 3): %#v\n", Trim("\x1b[33mGhost\x1b[0m", 3))
fmt.Printf("Trim(\"\\x1b[33mGhost\\x1b[0m\", 6): %#v\n", Trim("\x1b[33mGhost\x1b[0m", 6))
Output:

Trim("Ghost", 0): ""
Trim("Ghost", 3): "Gho"
Trim("Ghost", 6): "Ghost"
Trim("\x1b[33mGhost\x1b[0m", 0): ""
Trim("\x1b[33mGhost\x1b[0m", 3): "\x1b[33mGho\x1b[0m"
Trim("\x1b[33mGhost\x1b[0m", 6): "\x1b[33mGhost\x1b[0m"

func WrapHard

func WrapHard(str string, wrapLen int) string

WrapHard wraps a string to the given length using a newline. Handles strings with ANSI escape sequences (such as text color) without breaking the text formatting. Breaks all words that go beyond the line boundary.

For examples, refer to the unit-tests or GoDoc examples.

Example
str := `The quick brown fox jumped over the lazy dog.

A big crocodile died empty-fanged, gulping horribly in jerking kicking little
motions. Nonchalant old Peter Quinn ruthlessly shot the under-water vermin with
Xavier yelling Zap!`
strWrapped := WrapHard(str, 30)
for idx, line := range strings.Split(strWrapped, "\n") {
	fmt.Printf("Line #%02d: '%s'\n", idx+1, line)
}
Output:

Line #01: 'The quick brown fox jumped ove'
Line #02: 'r the lazy dog.'
Line #03: ''
Line #04: 'A big crocodile died empty-fan'
Line #05: 'ged, gulping horribly in jerki'
Line #06: 'ng kicking little motions. Non'
Line #07: 'chalant old Peter Quinn ruthle'
Line #08: 'ssly shot the under-water verm'
Line #09: 'in with Xavier yelling Zap!'

func WrapSoft

func WrapSoft(str string, wrapLen int) string

WrapSoft wraps a string to the given length using a newline. Handles strings with ANSI escape sequences (such as text color) without breaking the text formatting. Tries to move words that go beyond the line boundary to the next line.

For examples, refer to the unit-tests or GoDoc examples.

Example
str := `The quick brown fox jumped over the lazy dog.

A big crocodile died empty-fanged, gulping horribly in jerking kicking little
motions. Nonchalant old Peter Quinn ruthlessly shot the under-water vermin with
Xavier yelling Zap!`
strWrapped := WrapSoft(str, 30)
for idx, line := range strings.Split(strWrapped, "\n") {
	fmt.Printf("Line #%02d: '%s'\n", idx+1, line)
}
Output:

Line #01: 'The quick brown fox jumped    '
Line #02: 'over the lazy dog.'
Line #03: ''
Line #04: 'A big crocodile died          '
Line #05: 'empty-fanged, gulping horribly'
Line #06: 'in jerking kicking little     '
Line #07: 'motions. Nonchalant old Peter '
Line #08: 'Quinn ruthlessly shot the     '
Line #09: 'under-water vermin with Xavier'
Line #10: 'yelling Zap!'

func WrapText

func WrapText(str string, wrapLen int) string

WrapText is very similar to WrapHard except for one minor difference. Unlike WrapHard which discards line-breaks and respects only paragraph-breaks, this function respects line-breaks too.

For examples, refer to the unit-tests or GoDoc examples.

Example
str := `The quick brown fox jumped over the lazy dog.

A big crocodile died empty-fanged, gulping horribly in jerking kicking little
motions. Nonchalant old Peter Quinn ruthlessly shot the under-water vermin with
Xavier yelling Zap!`
strWrapped := WrapText(str, 30)
for idx, line := range strings.Split(strWrapped, "\n") {
	fmt.Printf("Line #%02d: '%s'\n", idx+1, line)
}
Output:

Line #01: 'The quick brown fox jumped ove'
Line #02: 'r the lazy dog.'
Line #03: ''
Line #04: 'A big crocodile died empty-fan'
Line #05: 'ged, gulping horribly in jerki'
Line #06: 'ng kicking little'
Line #07: 'motions. Nonchalant old Peter '
Line #08: 'Quinn ruthlessly shot the unde'
Line #09: 'r-water vermin with'
Line #10: 'Xavier yelling Zap!'

Types

type Align

type Align int

Align denotes how text is to be aligned horizontally.

const (
	AlignDefault Align = iota // same as AlignLeft
	AlignLeft                 // "left        "
	AlignCenter               // "   center   "
	AlignJustify              // "justify   it"
	AlignRight                // "       right"
	AlignAuto                 // AlignRight for numbers, AlignLeft for the rest
)

Align enumerations

func (Align) Apply

func (a Align) Apply(text string, maxLength int) string

Apply aligns the text as directed. For ex.:

  • AlignDefault.Apply("Jon Snow", 12) returns "Jon Snow "
  • AlignLeft.Apply("Jon Snow", 12) returns "Jon Snow "
  • AlignCenter.Apply("Jon Snow", 12) returns " Jon Snow "
  • AlignJustify.Apply("Jon Snow", 12) returns "Jon Snow"
  • AlignRight.Apply("Jon Snow", 12) returns " Jon Snow"
  • AlignAuto.Apply("Jon Snow", 12) returns "Jon Snow "
Example
fmt.Printf("AlignDefault: '%s'\n", AlignDefault.Apply("Jon Snow", 12))
fmt.Printf("AlignLeft   : '%s'\n", AlignLeft.Apply("Jon Snow", 12))
fmt.Printf("AlignCenter : '%s'\n", AlignCenter.Apply("Jon Snow", 12))
fmt.Printf("AlignJustify: '%s'\n", AlignJustify.Apply("Jon Snow", 12))
fmt.Printf("AlignRight  : '%s'\n", AlignRight.Apply("Jon Snow", 12))
fmt.Printf("AlignAuto   : '%s'\n", AlignAuto.Apply("Jon Snow", 12))
fmt.Printf("AlignAuto   : '%s'\n", AlignAuto.Apply("-5.43", 12))
Output:

AlignDefault: 'Jon Snow    '
AlignLeft   : 'Jon Snow    '
AlignCenter : '  Jon Snow  '
AlignJustify: 'Jon     Snow'
AlignRight  : '    Jon Snow'
AlignAuto   : 'Jon Snow    '
AlignAuto   : '       -5.43'

func (Align) HTMLProperty

func (a Align) HTMLProperty() string

HTMLProperty returns the equivalent HTML horizontal-align tag property.

Example
fmt.Printf("AlignDefault: '%s'\n", AlignDefault.HTMLProperty())
fmt.Printf("AlignLeft   : '%s'\n", AlignLeft.HTMLProperty())
fmt.Printf("AlignCenter : '%s'\n", AlignCenter.HTMLProperty())
fmt.Printf("AlignJustify: '%s'\n", AlignJustify.HTMLProperty())
fmt.Printf("AlignRight  : '%s'\n", AlignRight.HTMLProperty())
Output:

AlignDefault: ''
AlignLeft   : 'align="left"'
AlignCenter : 'align="center"'
AlignJustify: 'align="justify"'
AlignRight  : 'align="right"'

func (Align) MarkdownProperty

func (a Align) MarkdownProperty() string

MarkdownProperty returns the equivalent Markdown horizontal-align separator.

Example
fmt.Printf("AlignDefault: '%s'\n", AlignDefault.MarkdownProperty())
fmt.Printf("AlignLeft   : '%s'\n", AlignLeft.MarkdownProperty())
fmt.Printf("AlignCenter : '%s'\n", AlignCenter.MarkdownProperty())
fmt.Printf("AlignJustify: '%s'\n", AlignJustify.MarkdownProperty())
fmt.Printf("AlignRight  : '%s'\n", AlignRight.MarkdownProperty())
Output:

AlignDefault: ' --- '
AlignLeft   : ':--- '
AlignCenter : ':---:'
AlignJustify: ' --- '
AlignRight  : ' ---:'

type Color

type Color int

Color represents a single color to render with.

const (
	Reset Color = iota
	Bold
	Faint
	Italic
	Underline
	BlinkSlow
	BlinkRapid
	ReverseVideo
	Concealed
	CrossedOut
)

Base colors -- attributes in reality

const (
	FgBlack Color = iota + 30
	FgRed
	FgGreen
	FgYellow
	FgBlue
	FgMagenta
	FgCyan
	FgWhite
)

Foreground colors

const (
	FgHiBlack Color = iota + 90
	FgHiRed
	FgHiGreen
	FgHiYellow
	FgHiBlue
	FgHiMagenta
	FgHiCyan
	FgHiWhite
)

Foreground Hi-Intensity colors

const (
	BgBlack Color = iota + 40
	BgRed
	BgGreen
	BgYellow
	BgBlue
	BgMagenta
	BgCyan
	BgWhite
)

Background colors

const (
	BgHiBlack Color = iota + 100
	BgHiRed
	BgHiGreen
	BgHiYellow
	BgHiBlue
	BgHiMagenta
	BgHiCyan
	BgHiWhite
)

Background Hi-Intensity colors

func (Color) EscapeSeq

func (c Color) EscapeSeq() string

EscapeSeq returns the ANSI escape sequence for the color.

Example
fmt.Printf("Black Background: %#v\n", BgBlack.EscapeSeq())
fmt.Printf("Black Foreground: %#v\n", FgBlack.EscapeSeq())
Output:

Black Background: "\x1b[40m"
Black Foreground: "\x1b[30m"

func (Color) HTMLProperty

func (c Color) HTMLProperty() string

HTMLProperty returns the "class" attribute for the color.

Example
fmt.Printf("Bold: %#v\n", Bold.HTMLProperty())
fmt.Printf("Black Background: %#v\n", BgBlack.HTMLProperty())
fmt.Printf("Black Foreground: %#v\n", FgBlack.HTMLProperty())
Output:

Bold: "class=\"bold\""
Black Background: "class=\"bg-black\""
Black Foreground: "class=\"fg-black\""

func (Color) Sprint

func (c Color) Sprint(a ...interface{}) string

Sprint colorizes and prints the given string(s).

Example
fmt.Printf("%#v\n", BgBlack.Sprint("Black Background"))
fmt.Printf("%#v\n", FgBlack.Sprint("Black Foreground"))
Output:

"\x1b[40mBlack Background\x1b[0m"
"\x1b[30mBlack Foreground\x1b[0m"

func (Color) Sprintf

func (c Color) Sprintf(format string, a ...interface{}) string

Sprintf formats and colorizes and prints the given string(s).

Example
fmt.Printf("%#v\n", BgBlack.Sprintf("%s %s", "Black", "Background"))
fmt.Printf("%#v\n", FgBlack.Sprintf("%s %s", "Black", "Foreground"))
Output:

"\x1b[40mBlack Background\x1b[0m"
"\x1b[30mBlack Foreground\x1b[0m"

type Colors

type Colors []Color

Colors represents an array of Color objects to render with. Example: Colors{FgCyan, BgBlack}

func (Colors) EscapeSeq

func (c Colors) EscapeSeq() string

EscapeSeq returns the ANSI escape sequence for the colors set.

Example
fmt.Printf("Black Background: %#v\n", Colors{BgBlack}.EscapeSeq())
fmt.Printf("Black Foreground: %#v\n", Colors{FgBlack}.EscapeSeq())
fmt.Printf("Black Background, White Foreground: %#v\n", Colors{BgBlack, FgWhite}.EscapeSeq())
fmt.Printf("Black Foreground, White Background: %#v\n", Colors{FgBlack, BgWhite}.EscapeSeq())
Output:

Black Background: "\x1b[40m"
Black Foreground: "\x1b[30m"
Black Background, White Foreground: "\x1b[40;37m"
Black Foreground, White Background: "\x1b[30;47m"

func (Colors) HTMLProperty

func (c Colors) HTMLProperty() string

HTMLProperty returns the "class" attribute for the colors.

Example
fmt.Printf("Black Background: %#v\n", Colors{BgBlack}.HTMLProperty())
fmt.Printf("Black Foreground: %#v\n", Colors{FgBlack}.HTMLProperty())
fmt.Printf("Black Background, White Foreground: %#v\n", Colors{BgBlack, FgWhite}.HTMLProperty())
fmt.Printf("Black Foreground, White Background: %#v\n", Colors{FgBlack, BgWhite}.HTMLProperty())
fmt.Printf("Bold Italic Underline Red Text: %#v\n", Colors{Bold, Italic, Underline, FgRed}.HTMLProperty())
Output:

Black Background: "class=\"bg-black\""
Black Foreground: "class=\"fg-black\""
Black Background, White Foreground: "class=\"bg-black fg-white\""
Black Foreground, White Background: "class=\"bg-white fg-black\""
Bold Italic Underline Red Text: "class=\"bold fg-red italic underline\""

func (Colors) Sprint

func (c Colors) Sprint(a ...interface{}) string

Sprint colorizes and prints the given string(s).

Example
fmt.Printf("%#v\n", Colors{BgBlack}.Sprint("Black Background"))
fmt.Printf("%#v\n", Colors{BgBlack, FgWhite}.Sprint("Black Background, White Foreground"))
fmt.Printf("%#v\n", Colors{FgBlack}.Sprint("Black Foreground"))
fmt.Printf("%#v\n", Colors{FgBlack, BgWhite}.Sprint("Black Foreground, White Background"))
Output:

"\x1b[40mBlack Background\x1b[0m"
"\x1b[40;37mBlack Background, White Foreground\x1b[0m"
"\x1b[30mBlack Foreground\x1b[0m"
"\x1b[30;47mBlack Foreground, White Background\x1b[0m"

func (Colors) Sprintf

func (c Colors) Sprintf(format string, a ...interface{}) string

Sprintf formats and colorizes and prints the given string(s).

Example
fmt.Printf("%#v\n", Colors{BgBlack}.Sprintf("%s %s", "Black", "Background"))
fmt.Printf("%#v\n", Colors{BgBlack, FgWhite}.Sprintf("%s, %s", "Black Background", "White Foreground"))
fmt.Printf("%#v\n", Colors{FgBlack}.Sprintf("%s %s", "Black", "Foreground"))
fmt.Printf("%#v\n", Colors{FgBlack, BgWhite}.Sprintf("%s, %s", "Black Foreground", "White Background"))
Output:

"\x1b[40mBlack Background\x1b[0m"
"\x1b[40;37mBlack Background, White Foreground\x1b[0m"
"\x1b[30mBlack Foreground\x1b[0m"
"\x1b[30;47mBlack Foreground, White Background\x1b[0m"

type Cursor

type Cursor rune

Cursor helps move the cursor on the console in multiple directions.

const (
	// CursorDown helps move the Cursor Down X lines
	CursorDown Cursor = 'B'

	// CursorLeft helps move the Cursor Left X characters
	CursorLeft Cursor = 'D'

	// CursorRight helps move the Cursor Right X characters
	CursorRight Cursor = 'C'

	// CursorUp helps move the Cursor Up X lines
	CursorUp Cursor = 'A'

	// EraseLine helps erase all characters to the Right of the Cursor in the
	// current line
	EraseLine Cursor = 'K'
)

func (Cursor) Sprint

func (c Cursor) Sprint() string

Sprint prints the Escape Sequence to move the Cursor once.

Example
fmt.Printf("CursorDown : %#v\n", CursorDown.Sprint())
fmt.Printf("CursorLeft : %#v\n", CursorLeft.Sprint())
fmt.Printf("CursorRight: %#v\n", CursorRight.Sprint())
fmt.Printf("CursorUp   : %#v\n", CursorUp.Sprint())
fmt.Printf("EraseLine  : %#v\n", EraseLine.Sprint())
Output:

CursorDown : "\x1b[B"
CursorLeft : "\x1b[D"
CursorRight: "\x1b[C"
CursorUp   : "\x1b[A"
EraseLine  : "\x1b[K"

func (Cursor) Sprintn

func (c Cursor) Sprintn(n int) string

Sprintn prints the Escape Sequence to move the Cursor "n" times.

Example
fmt.Printf("CursorDown : %#v\n", CursorDown.Sprintn(5))
fmt.Printf("CursorLeft : %#v\n", CursorLeft.Sprintn(5))
fmt.Printf("CursorRight: %#v\n", CursorRight.Sprintn(5))
fmt.Printf("CursorUp   : %#v\n", CursorUp.Sprintn(5))
fmt.Printf("EraseLine  : %#v\n", EraseLine.Sprintn(5))
Output:

CursorDown : "\x1b[5B"
CursorLeft : "\x1b[5D"
CursorRight: "\x1b[5C"
CursorUp   : "\x1b[5A"
EraseLine  : "\x1b[K"

type Direction added in v6.3.9

type Direction int

Direction defines the overall flow of text. Similar to bidi.Direction, but simplified and specific to this package.

const (
	Default Direction = iota
	LeftToRight
	RightToLeft
)

Available Directions.

func (Direction) Modifier added in v6.3.9

func (d Direction) Modifier() string

Modifier returns a character to force the given direction for the text that follows the modifier.

type Format

type Format int

Format lets you transform the text in supported methods while keeping escape sequences in the string intact and untouched.

const (
	FormatDefault Format = iota // default_Case
	FormatLower                 // lower
	FormatTitle                 // Title
	FormatUpper                 // UPPER
)

Format enumerations

func (Format) Apply

func (tc Format) Apply(text string) string

Apply converts the text as directed.

Example
fmt.Printf("FormatDefault: %#v\n", FormatDefault.Apply("jon Snow"))
fmt.Printf("FormatLower  : %#v\n", FormatLower.Apply("jon Snow"))
fmt.Printf("FormatTitle  : %#v\n", FormatTitle.Apply("jon Snow"))
fmt.Printf("FormatUpper  : %#v\n", FormatUpper.Apply("jon Snow"))
fmt.Println()
fmt.Printf("FormatDefault (w/EscSeq): %#v\n", FormatDefault.Apply(Bold.Sprint("jon Snow")))
fmt.Printf("FormatLower   (w/EscSeq): %#v\n", FormatLower.Apply(Bold.Sprint("jon Snow")))
fmt.Printf("FormatTitle   (w/EscSeq): %#v\n", FormatTitle.Apply(Bold.Sprint("jon Snow")))
fmt.Printf("FormatUpper   (w/EscSeq): %#v\n", FormatUpper.Apply(Bold.Sprint("jon Snow")))
Output:

FormatDefault: "jon Snow"
FormatLower  : "jon snow"
FormatTitle  : "Jon Snow"
FormatUpper  : "JON SNOW"

FormatDefault (w/EscSeq): "\x1b[1mjon Snow\x1b[0m"
FormatLower   (w/EscSeq): "\x1b[1mjon snow\x1b[0m"
FormatTitle   (w/EscSeq): "\x1b[1mJon Snow\x1b[0m"
FormatUpper   (w/EscSeq): "\x1b[1mJON SNOW\x1b[0m"

type Transformer

type Transformer func(val interface{}) string

Transformer helps format the contents of an object to the user's liking.

func NewJSONTransformer

func NewJSONTransformer(prefix string, indent string) Transformer

NewJSONTransformer returns a Transformer that can format a JSON string or an object into pretty-indented JSON-strings.

func NewNumberTransformer

func NewNumberTransformer(format string) Transformer

NewNumberTransformer returns a number Transformer that:

  • transforms the number as directed by 'format' (ex.: %.2f)
  • colors negative values Red
  • colors positive values Green

func NewTimeTransformer

func NewTimeTransformer(layout string, location *time.Location) Transformer

NewTimeTransformer returns a Transformer that can format a timestamp (a time.Time) into a well-defined time format defined using the provided layout (ex.: time.RFC3339).

If a non-nil location value is provided, the time will be localized to that location (use time.Local to get localized timestamps).

func NewURLTransformer

func NewURLTransformer(colors ...Color) Transformer

NewURLTransformer returns a Transformer that can format and pretty print a string that contains a URL (the text is underlined and colored Blue).

func NewUnixTimeTransformer

func NewUnixTimeTransformer(layout string, location *time.Location) Transformer

NewUnixTimeTransformer returns a Transformer that can format a unix-timestamp into a well-defined time format as defined by 'layout'. This can handle unix-time in Seconds, MilliSeconds, Microseconds and Nanoseconds.

If a non-nil location value is provided, the time will be localized to that location (use time.Local to get localized timestamps).

type VAlign

type VAlign int

VAlign denotes how text is to be aligned vertically.

const (
	VAlignDefault VAlign = iota // same as VAlignTop
	VAlignTop                   // "top\n\n"
	VAlignMiddle                // "\nmiddle\n"
	VAlignBottom                // "\n\nbottom"
)

VAlign enumerations

func (VAlign) Apply

func (va VAlign) Apply(lines []string, maxLines int) []string

Apply aligns the lines vertically. For ex.:

  • VAlignTop.Apply({"Game", "Of", "Thrones"}, 5) returns {"Game", "Of", "Thrones", "", ""}
  • VAlignMiddle.Apply({"Game", "Of", "Thrones"}, 5) returns {"", "Game", "Of", "Thrones", ""}
  • VAlignBottom.Apply({"Game", "Of", "Thrones"}, 5) returns {"", "", "Game", "Of", "Thrones"}
Example
lines := []string{"Game", "Of", "Thrones"}
maxLines := 5
fmt.Printf("VAlignDefault: %#v\n", VAlignDefault.Apply(lines, maxLines))
fmt.Printf("VAlignTop    : %#v\n", VAlignTop.Apply(lines, maxLines))
fmt.Printf("VAlignMiddle : %#v\n", VAlignMiddle.Apply(lines, maxLines))
fmt.Printf("VAlignBottom : %#v\n", VAlignBottom.Apply(lines, maxLines))
Output:

VAlignDefault: []string{"Game", "Of", "Thrones", "", ""}
VAlignTop    : []string{"Game", "Of", "Thrones", "", ""}
VAlignMiddle : []string{"", "Game", "Of", "Thrones", ""}
VAlignBottom : []string{"", "", "Game", "Of", "Thrones"}

func (VAlign) ApplyStr

func (va VAlign) ApplyStr(text string, maxLines int) []string

ApplyStr aligns the string (of 1 or more lines) vertically. For ex.:

  • VAlignTop.ApplyStr("Game\nOf\nThrones", 5) returns {"Game", "Of", "Thrones", "", ""}
  • VAlignMiddle.ApplyStr("Game\nOf\nThrones", 5) returns {"", "Game", "Of", "Thrones", ""}
  • VAlignBottom.ApplyStr("Game\nOf\nThrones", 5) returns {"", "", "Game", "Of", "Thrones"}
Example
str := "Game\nOf\nThrones"
maxLines := 5
fmt.Printf("VAlignDefault: %#v\n", VAlignDefault.ApplyStr(str, maxLines))
fmt.Printf("VAlignTop    : %#v\n", VAlignTop.ApplyStr(str, maxLines))
fmt.Printf("VAlignMiddle : %#v\n", VAlignMiddle.ApplyStr(str, maxLines))
fmt.Printf("VAlignBottom : %#v\n", VAlignBottom.ApplyStr(str, maxLines))
Output:

VAlignDefault: []string{"Game", "Of", "Thrones", "", ""}
VAlignTop    : []string{"Game", "Of", "Thrones", "", ""}
VAlignMiddle : []string{"", "Game", "Of", "Thrones", ""}
VAlignBottom : []string{"", "", "Game", "Of", "Thrones"}

func (VAlign) HTMLProperty

func (va VAlign) HTMLProperty() string

HTMLProperty returns the equivalent HTML vertical-align tag property.

Example
fmt.Printf("VAlignDefault: '%s'\n", VAlignDefault.HTMLProperty())
fmt.Printf("VAlignTop    : '%s'\n", VAlignTop.HTMLProperty())
fmt.Printf("VAlignMiddle : '%s'\n", VAlignMiddle.HTMLProperty())
fmt.Printf("VAlignBottom : '%s'\n", VAlignBottom.HTMLProperty())
Output:

VAlignDefault: ''
VAlignTop    : 'valign="top"'
VAlignMiddle : 'valign="middle"'
VAlignBottom : 'valign="bottom"'

Jump to

Keyboard shortcuts

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