Skip to content

Commit c5c8650

Browse files
committed
Do not add spaces in front of certain punctuation marks like '.', '?' or ')'.
But '(' would still get its space.
1 parent da410a0 commit c5c8650

2 files changed

Lines changed: 30 additions & 3 deletions

File tree

html2text.go

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,25 @@ func (ctx *textifyTraverseContext) traverseChildren(node *html.Node) error {
444444
return nil
445445
}
446446

447+
// Tests r for being a character where no space should be inserted in front of.
448+
func punctNoSpaceBefore(r rune) bool {
449+
switch r {
450+
case '.', ',', ';', '!', '?', ')', ']', '>':
451+
return true
452+
default:
453+
return false
454+
}
455+
}
456+
457+
// Tests r for being a character where no space should be inserted after.
458+
func punctNoSpaceAfter(r rune) bool {
459+
switch r {
460+
case '(', '[', '<':
461+
return true
462+
default:
463+
return false
464+
}
465+
}
447466
func (ctx *textifyTraverseContext) emit(data string) error {
448467
if data == "" {
449468
return nil
@@ -454,14 +473,14 @@ func (ctx *textifyTraverseContext) emit(data string) error {
454473
)
455474
for _, line := range lines {
456475
runes := []rune(line)
457-
startsWithSpace := unicode.IsSpace(runes[0])
458-
if !startsWithSpace && !ctx.endsWithSpace && !strings.HasPrefix(data, ".") {
476+
startsWithSpace := unicode.IsSpace(runes[0]) || punctNoSpaceBefore(runes[0])
477+
if !startsWithSpace && !ctx.endsWithSpace {
459478
if err = ctx.buf.WriteByte(' '); err != nil {
460479
return err
461480
}
462481
ctx.lineLength++
463482
}
464-
ctx.endsWithSpace = unicode.IsSpace(runes[len(runes)-1])
483+
ctx.endsWithSpace = unicode.IsSpace(runes[len(runes)-1]) || punctNoSpaceAfter(runes[len(runes)-1])
465484
for _, c := range line {
466485
if _, err = ctx.buf.WriteString(string(c)); err != nil {
467486
return err

html2text_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -542,6 +542,14 @@ func TestCitationStyleLinks(t *testing.T) {
542542
`<a href="">Link</a>`,
543543
"Link",
544544
},
545+
{
546+
`<a href="http://example1.com/">Link1</a><a href="http://example2.com/">Link2</a>`,
547+
"Link1 [1] Link2 [2]\n\n[1] http://example1.com/\n[2] http://example2.com/",
548+
},
549+
{
550+
`<a href="http://example1.com/">Link1</a> (<a href="http://example2.com/">Link2</a>)`,
551+
"Link1 [1] (Link2 [2])\n\n[1] http://example1.com/\n[2] http://example2.com/",
552+
},
545553
{
546554
`<a href="http://example1.com/">Link1</a>? <a href="http://example2.com/">Link2</a>!`,
547555
"Link1 [1]? Link2 [2]!\n\n[1] http://example1.com/\n[2] http://example2.com/",

0 commit comments

Comments
 (0)