diff --git a/internal/ui/format.go b/internal/ui/format.go index a9300008e..1a41b61a0 100644 --- a/internal/ui/format.go +++ b/internal/ui/format.go @@ -146,6 +146,16 @@ func Quote(line string) string { return line } +// QuoteSlice quotes elements that contain terminal control characters. +// Elements that are already safe to print are left unchanged. +func QuoteSlice(vals []string) []string { + out := make([]string, len(vals)) + for i, v := range vals { + out[i] = Quote(v) + } + return out +} + // Truncate s to fit in width (number of terminal cells) w. // If w is negative, returns the empty string. func Truncate(s string, w int) string { diff --git a/internal/ui/format_test.go b/internal/ui/format_test.go index 563a38870..8dcee674a 100644 --- a/internal/ui/format_test.go +++ b/internal/ui/format_test.go @@ -129,6 +129,13 @@ func TestQuote(t *testing.T) { } } +func TestQuoteSlice(t *testing.T) { + in := []string{"ok", "a\nb", "plain"} + rtest.Equals(t, []string{"ok", strconv.Quote("a\nb"), "plain"}, QuoteSlice(in)) + rtest.Equals(t, "a\nb", in[1]) + rtest.Equals(t, []string{}, QuoteSlice(nil)) +} + func TestTruncate(t *testing.T) { var tests = []struct { input string