From 356f65f4af82d76a1c2c1b6d7d2e2ee198c92a64 Mon Sep 17 00:00:00 2001 From: Carlos Alexandro Becker Date: Tue, 7 Jan 2025 03:32:04 -0300 Subject: [PATCH] feat(ansi): cut (#319) Signed-off-by: Carlos Alexandro Becker --- ansi/truncate.go | 11 +++++++++++ ansi/truncate_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/ansi/truncate.go b/ansi/truncate.go index 414826b6..1a598e25 100644 --- a/ansi/truncate.go +++ b/ansi/truncate.go @@ -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 diff --git a/ansi/truncate_test.go b/ansi/truncate_test.go index cc9eacaa..49d4fbe3 100644 --- a/ansi/truncate_test.go +++ b/ansi/truncate_test.go @@ -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) + } + }) +}