Skip to content
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
14 changes: 14 additions & 0 deletions textplain_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package textplain_test

import (
"strconv"
"strings"
"testing"

Expand Down Expand Up @@ -1060,6 +1061,19 @@ func TestNestedLists(t *testing.T) {
)
}

func TestManyPreformattedBlocks(t *testing.T) {
var body, expect []string
for i := range 50 {
n := strconv.Itoa(i)
body = append(body, "<pre>block "+n+"\n indented</pre>")
expect = append(expect, "block "+n+"\n indented")
}

result, err := textplain.Convert(strings.Join(body, ""))
require.NoError(t, err)
assert.Equal(t, strings.Join(expect, "\n\n"), result)
}

func TestPreformatted(t *testing.T) {
runTestCases(t,
testCase{
Expand Down
36 changes: 33 additions & 3 deletions tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,7 @@ func Convert(document string, opts ...Option) (string, error) {

wrapped := WordWrap(strings.TrimSpace(text), cv.opts.lineLength)

for _, block := range preformatted {
wrapped = strings.Replace(wrapped, prePlaceholder, block, 1)
}
wrapped = restorePre(wrapped, preformatted)

return applyQuotes(strings.ReplaceAll(wrapped, indentMark, " ")) + cv.footnotes(), nil
}
Expand Down Expand Up @@ -408,6 +406,38 @@ func extractPre(text string) ([]string, string) {
return blocks, out.String()
}

// restorePre puts each preformatted block back in place of its placeholder, in
// one pass
func restorePre(text string, blocks []string) string {
if len(blocks) == 0 {
return text
}

size := len(text)
for _, block := range blocks {
size += len(block)
}

var out strings.Builder

out.Grow(size)

for _, block := range blocks {
before, after, found := strings.Cut(text, prePlaceholder)
if !found {
break
}

out.WriteString(before)
out.WriteString(block)
text = after
}

out.WriteString(text)

return out.String()
}

// textOf collects the raw text of a subtree, keeping whitespace as written
func textOf(n *html.Node) string {
var (
Expand Down
Loading