Skip to content
quarry Artifact [37c9eaf5d8]
Login

Artifact [37c9eaf5d8]

Artifact 37c9eaf5d8212ae5f896677b58fea2e520899615bb43f93c1e33c50d3dbe27dd:


package markup

import (
	"html"
	"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.

// ghAnchorAttr carries a heading's GitHub slug from the transformer to
// the renderer. It is not an HTML attribute and is never written out.
const ghAnchorAttr = "quarry-gh-anchor"

// 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(html.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 records each heading's GitHub slug, unless it is the id
// the heading already has or one some other heading owns.
type githubAnchors struct{}

func (githubAnchors) Transform(doc *gast.Document, reader text.Reader, _ parser.Context) {
	src := reader.Source()
	var heads []*gast.Heading
	taken := map[string]bool{}
	gast.Walk(doc, func(n gast.Node, entering bool) (gast.WalkStatus, error) {
		if h, ok := n.(*gast.Heading); ok && entering {
			heads = append(heads, h)
			if id, ok := h.AttributeString("id"); ok {
				taken[string(id.([]byte))] = true
			}
		}
		return gast.WalkContinue, nil
	})
	// github-slugger's duplicate counter: a repeat is name-1, name-2.
	seen := map[string]int{}
	for _, h := range heads {
		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 == "" || len(slug) > 120 || taken[slug] {
			continue
		}
		taken[slug] = true
		h.SetAttributeString(ghAnchorAttr, []byte(slug))
	}
}

// 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(`<a id="` + string(v.([]byte)) + `"></a>`)
		}
		_, _ = 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
}