Implemented code blocks

This commit is contained in:
2024-04-01 21:27:10 +02:00
parent e19a41c792
commit f75ea823a9
3 changed files with 50 additions and 2 deletions

View File

@ -16,7 +16,9 @@ type renderer struct {
quoteLevel int
listLevel int
tableLevel int
codeLines int
tableHeaderWritten bool
inCodeBlock bool
}
// Render creates HTML from the supplied markdown text.
@ -52,6 +54,23 @@ func Render(markdown string) string {
}
func (r *renderer) processLine(line string) {
if r.inCodeBlock {
if strings.HasPrefix(line, "```") {
r.out.WriteString("</code></pre>")
r.inCodeBlock = false
r.codeLines = 0
} else {
if r.codeLines != 0 {
r.out.WriteByte('\n')
}
r.out.WriteString(html.EscapeString(line))
r.codeLines++
}
return
}
newQuoteLevel := 0
for strings.HasPrefix(line, ">") {
@ -107,6 +126,25 @@ func (r *renderer) processLine(line string) {
r.out.WriteString("</li>")
return
case '`':
if strings.HasPrefix(line, "```") {
language := line[3:]
if !r.inCodeBlock {
if language != "" {
r.out.WriteString("<pre><code class=\"language-")
r.out.WriteString(html.EscapeString(language))
r.out.WriteString("\">")
} else {
r.out.WriteString("<pre><code>")
}
r.inCodeBlock = true
}
return
}
case '|':
r.closeParagraphs()
line = line[1:]