Skip to content

Commit

Permalink
add optional list support with custom prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
Mario Hros committed May 10, 2023
1 parent b9e0d6e commit 23e3630
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
17 changes: 11 additions & 6 deletions html2text.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ var numericEntityRE = regexp.MustCompile(`(?i)^#(x?[a-f0-9]+)$`)
type options struct {
lbr string
linksInnerText bool
listSupport bool
listPrefix string
}

func newOptions() *options {
Expand Down Expand Up @@ -52,13 +52,18 @@ func WithLinksInnerText() Option {
}
}

// WithListSupport formats <ul> and <li> lists with dashes
func WithListSupport() Option {
// WithListSupportPrefix formats <ul> and <li> lists with the specified prefix
func WithListSupportPrefix(prefix string) Option {
return func(o *options) {
o.listSupport = true
o.listPrefix = prefix
}
}

// WithListSupport formats <ul> and <li> lists with " - " prefix
func WithListSupport() Option {
return WithListSupportPrefix(" - ")
}

func parseHTMLEntity(entName string) (string, bool) {
if r, ok := entity[entName]; ok {
return string(r), true
Expand Down Expand Up @@ -242,8 +247,8 @@ func HTML2TextWithOptions(html string, reqOpts ...Option) string {
if tagNameLowercase == "/ul" || tagNameLowercase == "/ol" {
outBuf.WriteString(opts.lbr)
} else if tagNameLowercase == "li" || tagNameLowercase == "li/" {
if opts.listSupport {
outBuf.WriteString(opts.lbr + "- ")
if opts.listPrefix != "" {
outBuf.WriteString(opts.lbr + opts.listPrefix)
} else {
outBuf.WriteString(opts.lbr)
}
Expand Down
4 changes: 2 additions & 2 deletions html2text_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,8 @@ func TestHTML2Text(t *testing.T) {
})

Convey("Optional list support", func() {
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")
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")
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")
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")
})

Convey("Custom HTML Tags", func() {
Expand Down

0 comments on commit 23e3630

Please sign in to comment.