@@ -2,11 +2,11 @@ package md
22
33import (
44 "fmt"
5+ "unicode"
56
67 "regexp"
78 "strconv"
89 "strings"
9- "unicode"
1010 "unicode/utf8"
1111
1212 "github.com/JohannesKaufmann/html-to-markdown/escape"
@@ -23,7 +23,7 @@ var commonmark = []Rule{
2323
2424 // we have a nested list, were the ul/ol is inside a list item
2525 // -> based on work done by @requilence from @anytypeio
26- if parent .Is ("li" ) && parent .Children ().Last ().IsSelection (selec ) {
26+ if ( parent .Is ("li" ) || parent . Is ( "ul" ) || parent . Is ( "ol" ) ) && parent .Children ().Last ().IsSelection (selec ) {
2727 // add a line break prefix if the parent's text node doesn't have it.
2828 // that makes sure that every list item is on its on line
2929 lastContentTextNode := strings .TrimRight (parent .Nodes [0 ].FirstChild .Data , " \t " )
@@ -49,21 +49,28 @@ var commonmark = []Rule{
4949 return nil
5050 }
5151
52- parent := selec .Parent ()
53- index := selec .Index ()
54-
55- var prefix string
56- if parent .Is ("ol" ) {
57- prefix = strconv .Itoa (index + 1 ) + ". "
58- } else {
59- prefix = opt .BulletListMarker + " "
60- }
6152 // remove leading newlines
6253 content = leadingNewlinesR .ReplaceAllString (content , "" )
6354 // replace trailing newlines with just a single one
6455 content = trailingNewlinesR .ReplaceAllString (content , "\n " )
65- // indent
66- content = indentR .ReplaceAllString (content , "\n " )
56+ // remove leading spaces
57+ content = strings .TrimLeft (content , " " )
58+
59+ prefix := selec .AttrOr (attrListPrefix , "" )
60+
61+ // `prefixCount` is not nessesarily the length of the empty string `prefix`
62+ // but how much space is reserved for the prefixes of the siblings.
63+ prefixCount , previousPrefixCounts := countListParents (opt , selec )
64+
65+ // if the prefix is not needed, balance it by adding the usual prefix spaces
66+ if prefix == "" {
67+ prefix = strings .Repeat (" " , prefixCount )
68+ }
69+ // indent the prefix so that the nested links are represented
70+ indent := strings .Repeat (" " , previousPrefixCounts )
71+ prefix = indent + prefix
72+
73+ content = IndentMultiLineListItem (opt , content , prefixCount + previousPrefixCounts )
6774
6875 return String (prefix + content + "\n " )
6976 },
@@ -82,6 +89,12 @@ var commonmark = []Rule{
8289 text = multipleSpacesR .ReplaceAllString (text , " " )
8390
8491 text = escape .MarkdownCharacters (text )
92+
93+ // if its inside a list, trim the spaces to not mess up the indentation
94+ if IndexWithText (selec ) == 0 && (selec .Parent ().Is ("li" ) || selec .Parent ().Is ("ol" ) || selec .Parent ().Is ("ul" )) {
95+ text = strings .Trim (text , ` ` )
96+ }
97+
8598 return & text
8699 },
87100 },
0 commit comments