All checks were successful
check / check (pull_request) Successful in 30s
The hand written fence scanner took a line that starts with a code span for a fence and missed fences in quotes and lists. The code blocks are now the ones goldmark finds. A backslash before a placeholder is turned into a marker that survives the Markdown and the list expansion, so it works in a code span and next to a block name, and two backslashes are a literal one. The em dash rule reports the line of the body, refuses padded entities and checks the header keys by name, the feed leaves protocol-relative links alone, base_url needs a host and a language file cannot set it.
58 lines
1.7 KiB
Go
58 lines
1.7 KiB
Go
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
package mdx
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"github.com/yuin/goldmark/ast"
|
|
"github.com/yuin/goldmark/text"
|
|
|
|
"git.kmalloc.org/squid/motorino/internal/render"
|
|
)
|
|
|
|
// SubstituteMarkdown replaces the {{name}} placeholders of Markdown source like
|
|
// render.SubstituteEscaped does, but leaves the content of fenced code blocks
|
|
// as written, so an article can show a placeholder there. The blocks are found
|
|
// by the Markdown parser, so they are the ones CommonMark sees, in lists and in
|
|
// quotes too. Code spans are substituted: the pages use them to show a value in
|
|
// monospace. The result still has the markers of escaped placeholders; turn
|
|
// them back with render.Unescape after the Markdown is rendered.
|
|
func SubstituteMarkdown(name, md string, ctx map[string]string) (string, error) {
|
|
src := []byte(md)
|
|
doc := engine.Parser().Parse(text.NewReader(src))
|
|
|
|
type span struct{ start, stop int }
|
|
var fenced []span
|
|
_ = ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
|
|
if block, ok := n.(*ast.FencedCodeBlock); ok && entering {
|
|
lines := block.Lines()
|
|
for i := 0; i < lines.Len(); i++ {
|
|
segment := lines.At(i)
|
|
fenced = append(fenced, span{segment.Start, segment.Stop})
|
|
}
|
|
}
|
|
return ast.WalkContinue, nil
|
|
})
|
|
|
|
var out strings.Builder
|
|
pos := 0
|
|
for _, s := range fenced {
|
|
if s.start < pos {
|
|
continue
|
|
}
|
|
replaced, err := render.SubstituteEscaped(name, md[pos:s.start], ctx)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
out.WriteString(replaced)
|
|
out.WriteString(md[s.start:s.stop])
|
|
pos = s.stop
|
|
}
|
|
replaced, err := render.SubstituteEscaped(name, md[pos:], ctx)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
out.WriteString(replaced)
|
|
return out.String(), nil
|
|
}
|