Skip to content

Commit

Permalink
fix(ansi): truncate: truncate string when input length is equal to ou…
Browse files Browse the repository at this point in the history
…tput

Fixes: charmbracelet/lipgloss#324
Fixes: #106
  • Loading branch information
aymanbagabas committed Jul 8, 2024
1 parent 61cb1b1 commit ba4d1ad
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
4 changes: 4 additions & 0 deletions ansi/truncate.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ import (
// This function is aware of ANSI escape codes and will not break them, and
// accounts for wide-characters (such as East Asians and emojis).
func Truncate(s string, length int, tail string) string {
if sw := StringWidth(s); sw <= length {
return s
}

tw := StringWidth(tail)
length -= tw
if length < 0 {
Expand Down
7 changes: 5 additions & 2 deletions ansi/truncate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ var tcases = []struct {
expect string
}{
{"empty", "", "", 0, ""},
{"equalascii", "one", ".", 3, "one"},
{"equalemoji", "on👋", ".", 3, "on."},
{"equalcontrolemoji", "one\x1b[0m", ".", 3, "one\x1b[0m"},
{"simple", "foobar", "", 3, "foo"},
{"passthrough", "foobar", "", 10, "foobar"},
{"ascii", "hello", "", 3, "hel"},
Expand All @@ -29,8 +32,8 @@ var tcases = []struct {
{"double_width_runes", "你好", "", 2, "你"},
{"spaces_only", " ", "…", 2, " …"},
{"longer_tail", "foo", "...", 2, ""},
{"same_tail_width", "foo", "...", 3, "..."},
{"same_tail_width_control", "\x1b[31mfoo\x1b[0m", "...", 3, "\x1b[31m...\x1b[0m"},
{"same_tail_width", "foo", "...", 3, "foo"},
{"same_tail_width_control", "\x1b[31mfoo\x1b[0m", "...", 3, "\x1b[31mfoo\x1b[0m"},
{"same_width", "foo", "", 3, "foo"},
{"truncate_with_tail", "foobar", ".", 4, "foo."},
{"style", "I really \x1B[38;2;249;38;114mlove\x1B[0m Go!", "", 8, "I really\x1B[38;2;249;38;114m\x1B[0m"},
Expand Down

0 comments on commit ba4d1ad

Please sign in to comment.