Skip to content

Commit

Permalink
fix(render): strip carriage returns from strings (#386)
Browse files Browse the repository at this point in the history
* fix(render): strip carriage returns from strings

* test(render): add test to reproduce carriage return issues

* feat: replace \r\n with \n instead of removing \r

Co-authored-by: Ayman Bagabas <ayman.bagabas@gmail.com>

* test(table): add test for carriage return in cell data

---------

Co-authored-by: Ayman Bagabas <ayman.bagabas@gmail.com>
  • Loading branch information
bashbunni and aymanbagabas authored Oct 11, 2024
1 parent 07d1841 commit 199d3c8
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
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 @@ -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, " ", ".")
}
Expand Down

0 comments on commit 199d3c8

Please sign in to comment.