Implemented links

This commit is contained in:
2024-04-01 11:54:14 +02:00
parent 93d5949eff
commit 862f9837e4
3 changed files with 91 additions and 5 deletions

View File

@ -25,7 +25,7 @@ func Render(markdown string) string {
}
out.WriteString("<p>")
out.WriteString(html.EscapeString(paragraph.String()))
writeText(&out, paragraph.String())
out.WriteString("</p>")
paragraph.Reset()
}
@ -52,7 +52,7 @@ func Render(markdown string) string {
if space > 0 && space <= 6 {
out.WriteString(headerStart[space-1])
out.WriteString(html.EscapeString(line[space+1:]))
writeText(&out, line[space+1:])
out.WriteString(headerEnd[space-1])
}
@ -69,3 +69,70 @@ func Render(markdown string) string {
}
}
}
func writeText(out *strings.Builder, text string) {
var (
i = 0
tokenStart = 0
)
var (
textStart = -1
textEnd = -1
urlStart = -1
parentheses = 0
)
for {
if i == len(text) {
out.WriteString(html.EscapeString(text[tokenStart:]))
return
}
c := text[i]
switch c {
case '[':
out.WriteString(html.EscapeString(text[tokenStart:i]))
tokenStart = i
textStart = i
case ']':
textEnd = i
case '(':
if parentheses == 0 {
urlStart = i
}
parentheses++
case ')':
parentheses--
if parentheses == 0 && textStart >= 0 && textEnd >= 0 && urlStart >= 0 {
linkText := text[textStart+1 : textEnd]
linkURL := text[urlStart+1 : i]
out.WriteString("<a href=\"")
out.WriteString(formatURL(linkURL))
out.WriteString("\">")
out.WriteString(html.EscapeString(linkText))
out.WriteString("</a>")
textStart = -1
textEnd = -1
urlStart = -1
tokenStart = i + 1
}
}
i++
}
}
func formatURL(linkURL string) string {
if strings.HasPrefix(strings.ToLower(linkURL), "javascript:") {
return ""
}
return html.EscapeString(linkURL)
}