package main import ( "bytes" "html/template" "regexp" "strconv" "strings" "github.com/yuin/goldmark" "github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/extension" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/renderer/html" "github.com/yuin/goldmark/text" "github.com/yuin/goldmark/util" ) // renderCtx is what the link pass needs to know about the page being drawn. type renderCtx struct { Root string // "" for pages at the top of docs/agi, "../" one level down Syms map[string]string // identifier or library id -> URL from the docs root Skip map[string]bool // names not to link (the card the text belongs to) } var ctxKey = parser.NewContextKey() type markdown struct { gm goldmark.Markdown } func newMarkdown() *markdown { return &markdown{gm: goldmark.New( goldmark.WithExtensions(extension.Table, extension.Strikethrough), goldmark.WithParserOptions(parser.WithASTTransformers(util.Prioritized(linkPass{}, 999))), // The Markdown is written in this repository, so raw HTML is allowed. goldmark.WithRendererOptions(html.WithUnsafe()), )} } // render turns a Markdown fragment into HTML. func (m *markdown) render(src string, rc *renderCtx) (template.HTML, error) { pc := parser.NewContext() pc.Set(ctxKey, rc) var buf bytes.Buffer if err := m.gm.Convert([]byte(src), &buf, parser.WithContext(pc)); err != nil { return "", err } return template.HTML(buf.String()), nil } // inline renders one line of Markdown (a heading) without the paragraph. func (m *markdown) inline(src string, rc *renderCtx) (template.HTML, error) { h, err := m.render(src, rc) if err != nil { return "", err } s := strings.TrimSpace(string(h)) s = strings.TrimPrefix(s, "
") s = strings.TrimSuffix(s, "
") return template.HTML(s), nil } // linkPass makes relative links work from pages one folder down and turns // `code` naming a documented function or library into a link to it. type linkPass struct{} func (linkPass) Transform(doc *ast.Document, reader text.Reader, pc parser.Context) { rc, _ := pc.Get(ctxKey).(*renderCtx) if rc == nil { return } src := reader.Source() var spans []*ast.CodeSpan ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) { if !entering { return ast.WalkContinue, nil } switch v := n.(type) { case *ast.Link: if dest := string(v.Destination); isRelativeURL(dest) { v.Destination = []byte(rc.Root + dest) } return ast.WalkSkipChildren, nil case *ast.CodeSpan: spans = append(spans, v) return ast.WalkSkipChildren, nil } return ast.WalkContinue, nil }) // Replace after the walk: swapping nodes while walking ends the loop // over their siblings early. for _, cs := range spans { url := rc.lookup(codeText(cs, src)) if url == "" { continue } parent := cs.Parent() link := ast.NewLink() link.Destination = []byte(rc.Root + url) parent.ReplaceChild(parent, cs, link) link.AppendChild(link, cs) } } func codeText(n ast.Node, src []byte) string { var b strings.Builder for c := n.FirstChild(); c != nil; c = c.NextSibling() { switch t := c.(type) { case *ast.Text: b.Write(t.Segment.Value(src)) case *ast.String: b.Write(t.Value) } } return b.String() } var callNameRe = regexp.MustCompile(`^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*(\(.*\))?;?$`) // lookup returns the URL documenting `code`, if any. func (rc *renderCtx) lookup(code string) string { m := callNameRe.FindStringSubmatch(strings.TrimSpace(code)) if m == nil || rc.Skip[m[1]] { return "" } return rc.Syms[m[1]] } func isRelativeURL(u string) bool { if u == "" || strings.HasPrefix(u, "#") || strings.HasPrefix(u, "/") { return false } if i := strings.Index(u, ":"); i >= 0 && !strings.ContainsAny(u[:i], "/?#") { return false // has a scheme: https:, mailto:, ... } return true } // ---------- ids ---------- var slugDropRe = regexp.MustCompile(`[^\p{L}\p{N}\s-]`) // slugify makes a readable element id from heading text. func slugify(s string) string { s = strings.ToLower(plainText(s)) s = slugDropRe.ReplaceAllString(s, "") s = strings.Join(strings.Fields(s), "-") if s == "" { s = "section" } return s } // githubSlug is the anchor GitHub gives a heading, so links written for the // README (#dbtransactionfn--any) still land on the right card. func githubSlug(s string) string { s = strings.ToLower(plainText(s)) var b strings.Builder for _, r := range s { switch { case r == ' ': b.WriteByte('-') case r == '-' || r == '_' || r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r > 127 && r != '→' && r != '—': b.WriteRune(r) } } return b.String() } var linkTextRe = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`) // plainText strips the Markdown marks of a heading. func plainText(md string) string { md = linkTextRe.ReplaceAllString(md, "$1") return strings.NewReplacer("`", "", "**", "", "*", "").Replace(md) } // idSet hands out unique element ids within a page. type idSet map[string]int func (s idSet) take(id string) string { n := s[id] s[id] = n + 1 if n == 0 { return id } return id + "-" + strconv.Itoa(n+1) } // ---------- code blocks ---------- var fencedRe = regexp.MustCompile("(?s)```[a-zA-Z]*\\n(.*?)\\n```") // codeBlocks returns the normalised fenced code of a Markdown body. func codeBlocks(md string) []string { var out []string for _, m := range fencedRe.FindAllStringSubmatch(md, -1) { out = append(out, normCode(m[1])) } return out } func normCode(s string) string { return strings.Join(strings.Fields(s), " ") }