Skip to content

Commit

Permalink
Merge pull request #135 from kinensake/fix-code-block-in-list
Browse files Browse the repository at this point in the history
Fix render nested code block in list item
  • Loading branch information
JohannesKaufmann authored Jan 13, 2025
2 parents 3d2ff94 + 87f20d3 commit 73f4145
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 2 deletions.
12 changes: 10 additions & 2 deletions plugin/commonmark/render_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/JohannesKaufmann/dom"
"github.com/JohannesKaufmann/html-to-markdown/v2/converter"
"github.com/JohannesKaufmann/html-to-markdown/v2/internal/textutils"
"github.com/JohannesKaufmann/html-to-markdown/v2/marker"
"golang.org/x/net/html"
)

Expand Down Expand Up @@ -43,20 +44,27 @@ func (c commonmark) getPrefixFunc(n *html.Node, sliceLength int) func(int) strin

func renderMultiLineListItem(w converter.Writer, content []byte, indentCount int) {
lines := bytes.Split(content, []byte("\n"))
indent := bytes.Repeat([]byte(" "), indentCount)

indentedCodeBlockNewline := append(marker.BytesMarkerCodeBlockNewline, indent...)

for i := range lines {
// Add indent to code block newlines
line := bytes.ReplaceAll(lines[i], marker.BytesMarkerCodeBlockNewline, indentedCodeBlockNewline)

if i != 0 {
// The first line is already indented through the prefix,
// all other lines need the correct amount of spaces.
w.Write(bytes.Repeat([]byte(" "), indentCount))
w.Write(indent)
}
w.Write(lines[i])
w.Write(line)

if i < len(lines)-1 {
w.WriteRune('\n')
}
}
}

func (c commonmark) renderListContainer(ctx converter.Context, w converter.Writer, n *html.Node) converter.RenderStatus {
children := dom.AllChildNodes(n)
items := make([][]byte, 0, len(children))
Expand Down
32 changes: 32 additions & 0 deletions plugin/commonmark/testdata/GoldenFiles/list.in.html
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,38 @@
</ul>


<hr />


<!-- with code block in item -->
<ul>
<li>
item:
<pre>line 1
line 2</pre>
</li>
<li>item 2</li>
</ul>

<!-- with code block in nested item -->
<ul>
<li>
item 1:
<ul>
<li>
nested item 1:
<pre>line 1
line 2</pre>
</li>
<li>nested item 2</li>
</ul>
</li>
<li>item 2</li>
</ul>


<hr />


<!--------------------------------------
Special Characters
Expand Down
29 changes: 29 additions & 0 deletions plugin/commonmark/testdata/GoldenFiles/list.out.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,35 @@ text between

End Line

* * *

<!-- with code block in item -->

- item:

```
line 1
line 2
```
- item 2

<!--THE END-->

<!-- with code block in nested item -->

- item 1:

- nested item 1:

```
line 1
line 2
```
- nested item 2
- item 2
* * *
<!--------------------------------------
Special Characters
--------------------------------------->
Expand Down

0 comments on commit 73f4145

Please sign in to comment.