Skip to content

Commit

Permalink
update go modfile, add tools/text.go file
Browse files Browse the repository at this point in the history
  • Loading branch information
abdfnx committed Feb 3, 2022
1 parent c1922f3 commit c475dcc
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
)

Expand All @@ -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
Expand Down
63 changes: 63 additions & 0 deletions tools/text.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit c475dcc

Please # to comment.