Skip to content

Commit 23e3630

Browse files
author
Mario Hros
committed
add optional list support with custom prefix
1 parent b9e0d6e commit 23e3630

File tree

2 files changed

+13
-8
lines changed

2 files changed

+13
-8
lines changed

html2text.go

+11-6
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ var numericEntityRE = regexp.MustCompile(`(?i)^#(x?[a-f0-9]+)$`)
2424
type options struct {
2525
lbr string
2626
linksInnerText bool
27-
listSupport bool
27+
listPrefix string
2828
}
2929

3030
func newOptions() *options {
@@ -52,13 +52,18 @@ func WithLinksInnerText() Option {
5252
}
5353
}
5454

55-
// WithListSupport formats <ul> and <li> lists with dashes
56-
func WithListSupport() Option {
55+
// WithListSupportPrefix formats <ul> and <li> lists with the specified prefix
56+
func WithListSupportPrefix(prefix string) Option {
5757
return func(o *options) {
58-
o.listSupport = true
58+
o.listPrefix = prefix
5959
}
6060
}
6161

62+
// WithListSupport formats <ul> and <li> lists with " - " prefix
63+
func WithListSupport() Option {
64+
return WithListSupportPrefix(" - ")
65+
}
66+
6267
func parseHTMLEntity(entName string) (string, bool) {
6368
if r, ok := entity[entName]; ok {
6469
return string(r), true
@@ -242,8 +247,8 @@ func HTML2TextWithOptions(html string, reqOpts ...Option) string {
242247
if tagNameLowercase == "/ul" || tagNameLowercase == "/ol" {
243248
outBuf.WriteString(opts.lbr)
244249
} else if tagNameLowercase == "li" || tagNameLowercase == "li/" {
245-
if opts.listSupport {
246-
outBuf.WriteString(opts.lbr + "- ")
250+
if opts.listPrefix != "" {
251+
outBuf.WriteString(opts.lbr + opts.listPrefix)
247252
} else {
248253
outBuf.WriteString(opts.lbr)
249254
}

html2text_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -128,8 +128,8 @@ func TestHTML2Text(t *testing.T) {
128128
})
129129

130130
Convey("Optional list support", func() {
131-
So(HTML2TextWithOptions(`list of items<ul><li>One</li><li>Two</li><li>Three</li></ul>`, WithListSupport()), ShouldEqual, "list of items\r\n- One\r\n- Two\r\n- Three\r\n")
132-
So(HTML2TextWithOptions(`list of items<ol><li>One</li><li>Two</li><li>Three</li></ol>`, WithListSupport()), ShouldEqual, "list of items\r\n- One\r\n- Two\r\n- Three\r\n")
131+
So(HTML2TextWithOptions(`list of items<ul><li>One</li><li>Two</li><li>Three</li></ul>`, WithListSupport()), ShouldEqual, "list of items\r\n - One\r\n - Two\r\n - Three\r\n")
132+
So(HTML2TextWithOptions(`list of items<ol><li>One</li><li>Two</li><li>Three</li></ol>`, WithListSupport()), ShouldEqual, "list of items\r\n - One\r\n - Two\r\n - Three\r\n")
133133
})
134134

135135
Convey("Custom HTML Tags", func() {

0 commit comments

Comments
 (0)