Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(ansi): cut #319

Merged
merged 1 commit into from
Jan 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions ansi/truncate.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ import (
"github.com/rivo/uniseg"
)

// Cut the string, without adding any prefix or tail strings.
// This function is aware of ANSI escape codes and will not break them, and
// accounts for wide-characters (such as East Asians and emojis).
// Note that the [left] parameter is inclusive, while [right] isn't.
func Cut(s string, left, right int) string {
if left == 0 {
return Truncate(s, right, "")
}
return TruncateLeft(Truncate(s, right, ""), left, "")
}

// Truncate truncates a string to a given length, adding a tail to the
// end if the string is longer than the given length.
// This function is aware of ANSI escape codes and will not break them, and
Expand Down
26 changes: 26 additions & 0 deletions ansi/truncate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -300,3 +300,29 @@ func TestTruncateLeft(t *testing.T) {
})
}
}

func TestCut(t *testing.T) {
t.Run("simple string", func(t *testing.T) {
got := Cut("This is a long string", 2, 6)
expect := "is i"
if got != expect {
t.Errorf("exptected %q, got %q", expect, got)
}
})

t.Run("with ansi", func(t *testing.T) {
got := Cut("I really \x1B[38;2;249;38;114mlove\x1B[0m Go!", 4, 25)
expect := "ally \x1b[38;2;249;38;114mlove\x1b[0m Go!"
if got != expect {
t.Errorf("exptected %q, got %q", expect, got)
}
})

t.Run("left is 0", func(t *testing.T) {
got := Cut("Foo \x1B[38;2;249;38;114mbar\x1B[0mbaz", 0, 5)
expect := "Foo \x1B[38;2;249;38;114mb\x1B[0m"
if got != expect {
t.Errorf("exptected %q, got %q", expect, got)
}
})
}
Loading