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

fix(render): strip carriage returns from strings #386

Merged
merged 4 commits into from
Oct 11, 2024
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
2 changes: 2 additions & 0 deletions style.go
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,8 @@ func (s Style) Render(strs ...string) string {

// Potentially convert tabs to spaces
str = s.maybeConvertTabs(str)
// carriage returns can cause strange behaviour when rendering.
str = strings.ReplaceAll(str, "\r\n", "\n")

// Strip newlines in single line mode
if inline {
Expand Down
14 changes: 14 additions & 0 deletions style_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package lipgloss

import (
"fmt"
"io"
"reflect"
"strings"
Expand Down Expand Up @@ -576,3 +577,16 @@ func requireNotEqual(tb testing.TB, a, b interface{}) {
tb.FailNow()
}
}

func TestCarriageReturnInRender(t *testing.T) {
out := fmt.Sprintf("%s\r\n%s\r\n", "Super duper california oranges", "Hello world")
testStyle := NewStyle().
MarginLeft(1)
got := testStyle.Render(string(out))
want := testStyle.Render(fmt.Sprintf("%s\n%s\n", "Super duper california oranges", "Hello world"))

if got != want {
t.Logf("got(detailed):\n%q\nwant(detailed):\n%q", got, want)
t.Fatalf("got(string):\n%s\nwant(string):\n%s", got, want)
}
}
28 changes: 28 additions & 0 deletions table/table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1158,6 +1158,34 @@ func TestClearRows(t *testing.T) {
table.String()
}

func TestCarriageReturn(t *testing.T) {
data := [][]string{
{"a0", "b0", "c0", "d0"},
{"a1", "b1.0\r\nb1.1\r\nb1.2\r\nb1.3\r\nb1.4\r\nb1.5\r\nb1.6", "c1", "d1"},
{"a2", "b2", "c2", "d2"},
{"a3", "b3", "c3", "d3"},
}
table := New().Rows(data...).Border(lipgloss.NormalBorder())
got := table.String()
want := `┌──┬────┬──┬──┐
│a0│b0 │c0│d0│
│a1│b1.0│c1│d1│
│ │b1.1│ │ │
│ │b1.2│ │ │
│ │b1.3│ │ │
│ │b1.4│ │ │
│ │b1.5│ │ │
│ │b1.6│ │ │
│a2│b2 │c2│d2│
│a3│b3 │c3│d3│
└──┴────┴──┴──┘`

if got != want {
t.Logf("detailed view...\ngot:\n%q\nwant:\n%q", got, want)
t.Fatalf("got:\n%s\nwant:\n%s", got, want)
}
}

func debug(s string) string {
return strings.ReplaceAll(s, " ", ".")
}
Expand Down
Loading