diff --git a/style.go b/style.go index 2aba56b0..0eb5c016 100644 --- a/style.go +++ b/style.go @@ -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 { diff --git a/style_test.go b/style_test.go index eacaadf5..0db740b4 100644 --- a/style_test.go +++ b/style_test.go @@ -1,6 +1,7 @@ package lipgloss import ( + "fmt" "io" "reflect" "strings" @@ -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) + } +} diff --git a/table/table_test.go b/table/table_test.go index ca8d43e1..88b5d7e0 100644 --- a/table/table_test.go +++ b/table/table_test.go @@ -1186,6 +1186,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, " ", ".") }