337 lines
5.8 KiB
Go

package markdown
import (
"html"
"strings"
)
var (
headerStart = []string{"<h1>", "<h2>", "<h3>", "<h4>", "<h5>", "<h6>"}
headerEnd = []string{"</h1>", "</h2>", "</h3>", "</h4>", "</h5>", "</h6>"}
)
// renderer represents a Markdown to HTML renderer.
type renderer struct {
out []byte
paragraphLevel int
quoteLevel int
listLevel int
tableLevel int
codeLines int
tableHeaderWritten bool
inCodeBlock bool
}
// Render creates HTML from the supplied markdown text.
func Render(markdown string) string {
var (
r renderer
i = 0
lineStart = 0
)
r.out = make([]byte, 0, nextPowerOf2(uint32(len(markdown)+4)))
for {
if i > len(markdown) {
r.closeAll()
for range r.quoteLevel {
r.WriteString("</blockquote>")
}
return string(r.out)
}
if i != len(markdown) && markdown[i] != '\n' {
i++
continue
}
line := markdown[lineStart:i]
lineStart = i + 1
i++
r.processLine(line)
}
}
func (r *renderer) processLine(line string) {
if r.inCodeBlock {
if strings.HasPrefix(line, "```") {
r.WriteString("</code></pre>")
r.inCodeBlock = false
r.codeLines = 0
} else {
if r.codeLines != 0 {
r.WriteByte('\n')
}
r.WriteString(html.EscapeString(line))
r.codeLines++
}
return
}
newQuoteLevel := 0
for strings.HasPrefix(line, ">") {
line = strings.TrimSpace(line[1:])
newQuoteLevel++
}
if newQuoteLevel > r.quoteLevel {
r.closeParagraphs()
for range newQuoteLevel - r.quoteLevel {
r.WriteString("<blockquote>")
}
} else if newQuoteLevel < r.quoteLevel {
r.closeParagraphs()
for range r.quoteLevel - newQuoteLevel {
r.WriteString("</blockquote>")
}
}
r.quoteLevel = newQuoteLevel
if len(line) == 0 {
r.closeAll()
return
}
switch line[0] {
case '#':
r.closeAll()
space := strings.IndexByte(line, ' ')
if space > 0 && space <= 6 {
r.WriteString(headerStart[space-1])
r.writeText(line[space+1:])
r.WriteString(headerEnd[space-1])
}
return
case '-', '*':
r.closeParagraphs()
line = strings.TrimSpace(line[1:])
if r.listLevel == 0 {
r.WriteString("<ul>")
r.listLevel++
}
r.WriteString("<li>")
r.writeText(line)
r.WriteString("</li>")
return
case '`':
if strings.HasPrefix(line, "```") {
language := line[3:]
if !r.inCodeBlock {
if language != "" {
r.WriteString("<pre><code class=\"language-")
r.WriteString(html.EscapeString(language))
r.WriteString("\">")
} else {
r.WriteString("<pre><code>")
}
r.inCodeBlock = true
}
return
}
case '|':
r.closeParagraphs()
line = line[1:]
if r.tableLevel == 0 {
r.WriteString("<table><thead>")
r.tableLevel++
}
column := 0
for {
pipe := strings.IndexByte(line, '|')
if pipe == -1 {
r.WriteString("</tr>")
return
}
content := strings.TrimSpace(line[:pipe])
if strings.HasPrefix(content, "---") {
r.WriteString("</thead><tbody>")
r.tableHeaderWritten = true
return
}
if column == 0 {
r.WriteString("<tr>")
}
if r.tableHeaderWritten {
r.WriteString("<td>")
r.writeText(content)
r.WriteString("</td>")
} else {
r.WriteString("<th>")
r.writeText(content)
r.WriteString("</th>")
}
line = line[pipe+1:]
column++
}
}
if r.paragraphLevel == 0 {
r.WriteString("<p>")
r.paragraphLevel++
r.writeText(line)
return
}
r.WriteByte(' ')
r.writeText(line)
}
// closeAll closes all open tags.
func (r *renderer) closeAll() {
r.closeLists()
r.closeParagraphs()
r.closeTables()
}
// closeParagraphs closes open paragraphs.
func (r *renderer) closeParagraphs() {
for range r.paragraphLevel {
r.WriteString("</p>")
}
r.paragraphLevel = 0
}
// closeLists closes open lists.
func (r *renderer) closeLists() {
for range r.listLevel {
r.WriteString("</ul>")
}
r.listLevel = 0
}
// closeTables closes open tables.
func (r *renderer) closeTables() {
for range r.tableLevel {
r.WriteString("</tbody></table>")
}
r.tableLevel = 0
r.tableHeaderWritten = false
}
// writeText converts inline markdown to HTML.
func (r *renderer) writeText(markdown string) {
var (
i = 0
tokenStart = 0
)
var (
textStart = -1
textEnd = -1
urlStart = -1
parentheses = 0
)
for {
if i == len(markdown) {
r.WriteString(html.EscapeString(markdown[tokenStart:]))
return
}
c := markdown[i]
switch c {
case '[':
r.WriteString(html.EscapeString(markdown[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 := markdown[textStart+1 : textEnd]
linkURL := markdown[urlStart+1 : i]
r.WriteString("<a href=\"")
r.WriteString(sanitizeURL(linkURL))
r.WriteString("\">")
r.WriteString(html.EscapeString(linkText))
r.WriteString("</a>")
textStart = -1
textEnd = -1
urlStart = -1
tokenStart = i + 1
}
}
i++
}
}
// sanitizeURL makes a URL safe to use as the value for a `href` attribute.
func sanitizeURL(linkURL string) string {
linkURL = strings.TrimSpace(linkURL)
if strings.HasPrefix(strings.ToLower(linkURL), "javascript:") {
return ""
}
return html.EscapeString(linkURL)
}
// WriteByte adds a single byte to the output.
func (r *renderer) WriteByte(b byte) error {
r.out = append(r.out, b)
return nil
}
// WriteString adds a string to the output.
func (r *renderer) WriteString(text string) (int, error) {
r.out = append(r.out, text...)
return len(text), nil
}
// nextPowerOf2 calculates the next 32-bit power of 2.
func nextPowerOf2(x uint32) uint32 {
x--
x |= x >> 1
x |= x >> 2
x |= x >> 4
x |= x >> 8
x |= x >> 16
x++
return x
}