forked from cli/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtruncate.go
More file actions
47 lines (38 loc) · 975 Bytes
/
truncate.go
File metadata and controls
47 lines (38 loc) · 975 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package text
import (
"strings"
"github.com/muesli/reflow/ansi"
"github.com/muesli/reflow/truncate"
)
const (
ellipsis = "..."
minWidthForEllipsis = len(ellipsis) + 2
)
// 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)
}