diff --git a/README.md b/README.md index 16fb7bf..62900f1 100644 --- a/README.md +++ b/README.md @@ -51,9 +51,9 @@ coverage: 100.0% of statements ## Benchmarks ``` -BenchmarkSmall-12 6202569 190.9 ns/op 32 B/op 1 allocs/op -BenchmarkMedium-12 1000000 1080 ns/op 512 B/op 1 allocs/op -BenchmarkLarge-12 271048 4115 ns/op 2560 B/op 2 allocs/op +BenchmarkSmall-12 5933677 190.8 ns/op 32 B/op 1 allocs/op +BenchmarkMedium-12 971929 1085 ns/op 512 B/op 1 allocs/op +BenchmarkLarge-12 277028 4075 ns/op 2560 B/op 2 allocs/op ``` ## License diff --git a/Render.go b/Render.go index 72472be..a2d353d 100644 --- a/Render.go +++ b/Render.go @@ -253,14 +253,13 @@ func (r *renderer) writeText(markdown string) { searchStart = 0 linkTextStart = -1 linkTextEnd = -1 - urlStart = -1 codeStart = -1 emStart = -1 strongStart = -1 strikeStart = -1 - parentheses = 0 ) +begin: for { i := strings.IndexAny(markdown[searchStart:], "[]()`*_~") @@ -282,30 +281,46 @@ func (r *renderer) writeText(markdown string) { linkTextEnd = i case '(': - if parentheses == 0 { - urlStart = i + if linkTextStart == -1 || linkTextEnd == -1 { + continue } - parentheses++ + level := 1 - case ')': - parentheses-- + for { + pos := strings.IndexAny(markdown[searchStart:], "()") - if parentheses == 0 && linkTextStart >= 0 && linkTextEnd >= 0 && urlStart >= 0 { - linkText := markdown[linkTextStart+1 : linkTextEnd] - linkURL := markdown[urlStart+1 : i] + if pos == -1 { + goto begin + } - r.WriteString("") - r.WriteString(html.EscapeString(linkText)) - r.WriteString("") + switch markdown[searchStart+pos] { + case '(': + level++ + case ')': + level-- - linkTextStart = -1 - linkTextEnd = -1 - urlStart = -1 + if level == 0 { + urlEnd := searchStart + pos + searchStart = urlEnd + 1 - tokenStart = i + 1 + linkText := markdown[linkTextStart+1 : linkTextEnd] + linkURL := markdown[i+1 : urlEnd] + + r.WriteString("") + r.WriteString(html.EscapeString(linkText)) + r.WriteString("") + + linkTextStart = -1 + linkTextEnd = -1 + tokenStart = urlEnd + 1 + goto begin + } + } + + searchStart += pos + 1 } case '`': diff --git a/Render_test.go b/Render_test.go index 4e98dc2..144cc60 100644 --- a/Render_test.go +++ b/Render_test.go @@ -50,6 +50,7 @@ func TestLink(t *testing.T) { assert.Equal(t, markdown.Render("[text]https://example.com/)"), "

[text]https://example.com/)

") assert.Equal(t, markdown.Render("[text(https://example.com/)"), "

[text(https://example.com/)

") assert.Equal(t, markdown.Render("text](https://example.com/)"), "

text](https://example.com/)

") + assert.Equal(t, markdown.Render("[text](https://example.com/_test_)"), "

text

") assert.Equal(t, markdown.Render("Prefix [text](https://example.com/) suffix."), "

Prefix text suffix.

") }