diff --git a/indent.go b/indent.go index e603ff4..6a677de 100644 --- a/indent.go +++ b/indent.go @@ -102,7 +102,7 @@ func wrapIndentEdit(first, rest []rune, firstWidth, restWidth int) func(rune, wr return ret, state } - if ws && cl > 0 && cl+wl+il+1 > width { + if ws && cl > 0 && cl+il+1 > width { ret = append(ret, '\n') state.currentLineLength = 0 state.multipleLines = true @@ -135,7 +135,7 @@ func wrapIndentEdit(first, rest []rune, firstWidth, restWidth int) func(rune, wr } } -func wrapIndentRelease(first, rest []rune) func(wrapIndentState) []rune { +func wrapIndentRelease(first, rest []rune, firstWidth, restWidth int) func(wrapIndentState) []rune { return func(state wrapIndentState) []rune { if len(state.currentWord) == 0 { return nil @@ -143,8 +143,16 @@ func wrapIndentRelease(first, rest []rune) func(wrapIndentState) []rune { var ret []rune indent := first + width := firstWidth if state.multipleLines { indent = rest + width = restWidth + } + + if width > 0 && state.currentLineLength > 0 && + state.currentLineLength+len(state.currentWord)+1+len(indent) > width { + ret = append(ret, '\n') + state.currentLineLength = 0 } if state.currentLineLength == 0 { @@ -163,6 +171,6 @@ func wrapIndentRelease(first, rest []rune) func(wrapIndentState) []rune { func wrapIndent(first, rest []rune, firstWidth, restWidth int) Editor { return Func( wrapIndentEdit(first, rest, firstWidth, restWidth), - wrapIndentRelease(first, rest), + wrapIndentRelease(first, rest, firstWidth, restWidth), ) } diff --git a/indent_test.go b/indent_test.go index b6ed41f..7e006fe 100644 --- a/indent_test.go +++ b/indent_test.go @@ -280,5 +280,22 @@ Walking through the mixed forests of Brandenburg in early autumn, one notices th t.Fatal(b.String()) } }) + + t.Run("wrap on release", func(t *testing.T) { + var b bytes.Buffer + w := textedit.New(&b, textedit.WrapIndent(" ", " ", 15, 15)) + w.Write([]byte("Some sample text...\n on multiple lines.")) + w.Flush() + + const expect = ` + Some sample + text... on + multiple + lines.` + + if "\n"+b.String() != expect { + t.Fatal("\n" + b.String()) + } + }) }) }