package markup
import (
"bytes"
gohtml "html"
"regexp"
"strconv"
"strings"
"unicode"
gast "github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/renderer"
ghtml "github.com/yuin/goldmark/renderer/html"
"github.com/yuin/goldmark/text"
"github.com/yuin/goldmark/util"
)
// A README written for GitHub links to its own sections by GitHub's
// anchors: [[TOC]](#anger-table-of-contents). Quarry's heading ids are a
// different slug of the same text, and existing links point at them, so
// they stay exactly as they are. Each heading whose GitHub slug differs
// from its own id also gets an empty anchor with that slug just before
// it, and both spellings resolve.
//
// The anchors are added AFTER sanitizing, as emoji spans are. A slug may
// start with a hyphen or hold non-ASCII letters and marks, which the
// sanitizer's narrow id pattern rightly refuses from a document; added
// afterwards, only the renderer ever produces such an id. The renderer
// leaves a marker in the HTML that carries a per-render nonce, and
// placeGitHubAnchors turns each into an anchor once it knows which ids
// really survived.
// ghAnchorAttr carries a heading's marker from the transformer to the
// renderer. It is not an HTML attribute and is never written out.
const ghAnchorAttr = "quarry-gh-anchor"
// ghNonceKey is the parser-context key holding the render's nonce.
var ghNonceKey = parser.NewContextKey()
// githubSlug is github-slugger's algorithm over a heading's text
// content: lowercase; drop everything but letters, numbers, marks,
// spaces, hyphens and underscores; each space becomes a hyphen. The
// text is the source's, so an emoji shortcode counts as its literal
// letters, which is how GitHub slugs it.
func githubSlug(s string) string {
s = strings.ToLower(strings.Trim(strings.ReplaceAll(s, " ", " "), " "))
var b strings.Builder
for _, r := range s {
switch {
case r == ' ':
b.WriteByte('-')
case r == '-' || r == '_' || unicode.IsLetter(r) || unicode.IsNumber(r):
b.WriteRune(r)
case unicode.IsMark(r) && r != '︎' && r != '️':
b.WriteRune(r)
}
}
return b.String()
}
// headingText is the text content of a heading as GitHub sees it: the
// words, with raw HTML tags dropped and entities ( ) resolved.
func headingText(n gast.Node, src []byte) string {
var b strings.Builder
gast.Walk(n, func(c gast.Node, entering bool) (gast.WalkStatus, error) {
if !entering {
return gast.WalkContinue, nil
}
switch v := c.(type) {
case *gast.Image, *gast.RawHTML:
return gast.WalkSkipChildren, nil
case *gast.Text:
b.WriteString(gohtml.UnescapeString(string(util.UnescapePunctuations(v.Segment.Value(src)))))
if v.SoftLineBreak() || v.HardLineBreak() {
b.WriteByte(' ')
}
case *gast.String:
b.WriteString(string(v.Value))
}
return gast.WalkContinue, nil
})
return b.String()
}
// githubAnchors marks each heading with its GitHub slug. Whether the
// slug becomes an anchor is decided later, against the ids that survived
// sanitizing (placeGitHubAnchors).
type githubAnchors struct{}
func (githubAnchors) Transform(doc *gast.Document, reader text.Reader, pc parser.Context) {
nonce, _ := pc.Get(ghNonceKey).(string)
if nonce == "" {
return
}
src := reader.Source()
// github-slugger's duplicate counter: a repeat is name-1, name-2.
seen := map[string]int{}
gast.Walk(doc, func(n gast.Node, entering bool) (gast.WalkStatus, error) {
h, ok := n.(*gast.Heading)
if !ok || !entering {
return gast.WalkContinue, nil
}
base := githubSlug(headingText(h, src))
slug := base
for {
if _, dup := seen[slug]; !dup {
break
}
seen[base]++
slug = base + "-" + strconv.Itoa(seen[base])
}
seen[slug] = 0
if slug != "" {
h.SetAttributeString(ghAnchorAttr, []byte(ghMarker(nonce, slug)))
}
return gast.WalkContinue, nil
})
}
func ghMarker(nonce, slug string) string { return "qgh" + nonce + ":" + slug + ";" }
var (
sanitizedID = regexp.MustCompile(`\bid="([^"]*)"`)
// What a slug can hold: letters, numbers, marks, hyphen, underscore.
// Anything else in a marker is not ours.
ghSlugBody = `[\p{L}\p{N}\p{M}_-]+`
)
// placeGitHubAnchors turns the markers renderHeading left into empty
// anchors, ahead of their headings. A slug is skipped when some id in
// the sanitized document already is it — the heading's own, or another's
// — so no id is written twice; an id the sanitizer stripped does not
// count, which is what lets "-fire" through for a heading "🔥 Fire".
// ghMarkerRe matches any render's marker; placeGitHubAnchors keeps only
// those carrying this render's nonce (16 hex digits from crypto/rand).
var ghMarkerRe = regexp.MustCompile(`qgh([0-9a-f]{16}):(` + ghSlugBody + `);`)
func placeGitHubAnchors(h []byte, nonce string) []byte {
if !bytes.Contains(h, []byte("qgh"+nonce+":")) {
return h
}
taken := map[string]bool{}
for _, m := range sanitizedID.FindAllSubmatch(h, -1) {
taken[gohtml.UnescapeString(string(m[1]))] = true
}
return ghMarkerRe.ReplaceAllFunc(h, func(m []byte) []byte {
sub := ghMarkerRe.FindSubmatch(m)
if string(sub[1]) != nonce {
return m // another render's text, typed by a document: not ours
}
slug := string(sub[2])
if taken[slug] || len(slug) > 120 || slug == "__proto__" {
return nil
}
taken[slug] = true
return []byte(`<a id="` + slug + `"></a>`)
})
}
// headingRenderer is goldmark's own heading, preceded by the anchor
// githubAnchors asked for.
type headingRenderer struct{}
func (headingRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
reg.Register(gast.KindHeading, renderHeading)
}
func renderHeading(w util.BufWriter, _ []byte, node gast.Node, entering bool) (gast.WalkStatus, error) {
n := node.(*gast.Heading)
if entering {
if v, ok := n.AttributeString(ghAnchorAttr); ok {
_, _ = w.WriteString(string(v.([]byte)))
}
_, _ = w.WriteString("<h" + strconv.Itoa(n.Level))
ghtml.RenderAttributes(w, node, ghtml.HeadingAttributeFilter)
_ = w.WriteByte('>')
} else {
_, _ = w.WriteString("</h" + strconv.Itoa(n.Level) + ">\n")
}
return gast.WalkContinue, nil
}