From c475dcc44c54bbb40c3ea2df038d308761106ce9 Mon Sep 17 00:00:00 2001 From: abdfnx Date: Thu, 3 Feb 2022 11:27:56 +0300 Subject: [PATCH] update go modfile, add `tools/text.go` file --- go.mod | 2 +- tools/text.go | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) create mode 100755 tools/text.go diff --git a/go.mod b/go.mod index ae08779..c32b379 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/charmbracelet/lipgloss v0.4.0 github.com/gorilla/websocket v1.4.2 github.com/klauspost/pgzip v1.2.5 + github.com/muesli/reflow v0.3.0 golang.org/x/crypto v0.0.0-20220131195533-30dcbda58838 ) @@ -19,7 +20,6 @@ require ( github.com/mattn/go-isatty v0.0.13 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b // indirect - github.com/muesli/reflow v0.3.0 // indirect github.com/muesli/termenv v0.9.0 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/rivo/uniseg v0.2.0 // indirect diff --git a/tools/text.go b/tools/text.go new file mode 100755 index 0000000..dc3c254 --- /dev/null +++ b/tools/text.go @@ -0,0 +1,63 @@ +package tools + +import ( + "regexp" + "strings" + + "github.com/muesli/reflow/ansi" + "github.com/muesli/reflow/truncate" +) + +var ( + ellipsis = "..." + minWidthForEllipsis = len(ellipsis) + 2 + lineRE = regexp.MustCompile(`(?m)^`) + ws = regexp.MustCompile(`\s+`) +) + +func Indent(s, indent string) string { + if len(strings.TrimSpace(s)) == 0 { + return s + } + + return lineRE.ReplaceAllLiteralString(s, indent) +} + +func ReplaceExcessiveWhitespace(s string) string { + return ws.ReplaceAllString(strings.TrimSpace(s), " ") +} + +// DisplayWidth calculates what the rendered width of a string may be +func DisplayWidth(s string) int { + return ansi.PrintableRuneWidth(s) +} + +// Truncate shortens a string to fit the maximum display width +func Truncate(maxWidth int, s string) string { + w := DisplayWidth(s) + if w <= maxWidth { + return s + } + + tail := "" + if maxWidth >= minWidthForEllipsis { + tail = ellipsis + } + + r := truncate.StringWithTail(s, uint(maxWidth), tail) + if DisplayWidth(r) < maxWidth { + r += " " + } + + return r +} + +// TruncateColumn replaces the first new line character with an ellipsis +// and shortens a string to fit the maximum display width +func TruncateColumn(maxWidth int, s string) string { + if i := strings.IndexAny(s, "\r\n"); i >= 0 { + s = s[:i] + ellipsis + } + + return Truncate(maxWidth, s) +}