mirror of
https://github.com/crazy-max/diun.git
synced 2024-12-22 19:38:28 +00:00
6f7b5b313d
Bumps [github.com/jedib0t/go-pretty/v6](https://github.com/jedib0t/go-pretty) from 6.5.9 to 6.6.5. - [Release notes](https://github.com/jedib0t/go-pretty/releases) - [Commits](https://github.com/jedib0t/go-pretty/compare/v6.5.9...v6.6.5) --- updated-dependencies: - dependency-name: github.com/jedib0t/go-pretty/v6 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com>
58 lines
1.8 KiB
Go
58 lines
1.8 KiB
Go
package text
|
|
|
|
import "strings"
|
|
|
|
// ANSICodesSupported will be true on consoles where ANSI Escape Codes/Sequences
|
|
// are supported.
|
|
var ANSICodesSupported = areANSICodesSupported()
|
|
|
|
// 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"
|
|
func Escape(str string, escapeSeq string) string {
|
|
out := ""
|
|
if !strings.HasPrefix(str, EscapeStart) {
|
|
out += escapeSeq
|
|
}
|
|
out += strings.Replace(str, EscapeReset, EscapeReset+escapeSeq, -1)
|
|
if !strings.HasSuffix(out, EscapeReset) {
|
|
out += EscapeReset
|
|
}
|
|
if strings.Contains(out, escapeSeq+EscapeReset) {
|
|
out = strings.Replace(out, escapeSeq+EscapeReset, "", -1)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// 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"
|
|
func StripEscape(str string) string {
|
|
var out strings.Builder
|
|
out.Grow(StringWidthWithoutEscSequences(str))
|
|
|
|
isEscSeq := false
|
|
for _, sChr := range str {
|
|
if sChr == EscapeStartRune {
|
|
isEscSeq = true
|
|
}
|
|
if !isEscSeq {
|
|
out.WriteRune(sChr)
|
|
}
|
|
if isEscSeq && sChr == EscapeStopRune {
|
|
isEscSeq = false
|
|
}
|
|
}
|
|
return out.String()
|
|
}
|