markdown.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. package main
  2. import (
  3. "bytes"
  4. "html/template"
  5. "regexp"
  6. "strconv"
  7. "strings"
  8. "github.com/yuin/goldmark"
  9. "github.com/yuin/goldmark/ast"
  10. "github.com/yuin/goldmark/extension"
  11. "github.com/yuin/goldmark/parser"
  12. "github.com/yuin/goldmark/renderer/html"
  13. "github.com/yuin/goldmark/text"
  14. "github.com/yuin/goldmark/util"
  15. )
  16. // renderCtx is what the link pass needs to know about the page being drawn.
  17. type renderCtx struct {
  18. Root string // "" for pages at the top of docs/agi, "../" one level down
  19. Syms map[string]string // identifier or library id -> URL from the docs root
  20. Skip map[string]bool // names not to link (the card the text belongs to)
  21. }
  22. var ctxKey = parser.NewContextKey()
  23. type markdown struct {
  24. gm goldmark.Markdown
  25. }
  26. func newMarkdown() *markdown {
  27. return &markdown{gm: goldmark.New(
  28. goldmark.WithExtensions(extension.Table, extension.Strikethrough),
  29. goldmark.WithParserOptions(parser.WithASTTransformers(util.Prioritized(linkPass{}, 999))),
  30. // The Markdown is written in this repository, so raw HTML is allowed.
  31. goldmark.WithRendererOptions(html.WithUnsafe()),
  32. )}
  33. }
  34. // render turns a Markdown fragment into HTML.
  35. func (m *markdown) render(src string, rc *renderCtx) (template.HTML, error) {
  36. pc := parser.NewContext()
  37. pc.Set(ctxKey, rc)
  38. var buf bytes.Buffer
  39. if err := m.gm.Convert([]byte(src), &buf, parser.WithContext(pc)); err != nil {
  40. return "", err
  41. }
  42. return template.HTML(buf.String()), nil
  43. }
  44. // inline renders one line of Markdown (a heading) without the paragraph.
  45. func (m *markdown) inline(src string, rc *renderCtx) (template.HTML, error) {
  46. h, err := m.render(src, rc)
  47. if err != nil {
  48. return "", err
  49. }
  50. s := strings.TrimSpace(string(h))
  51. s = strings.TrimPrefix(s, "<p>")
  52. s = strings.TrimSuffix(s, "</p>")
  53. return template.HTML(s), nil
  54. }
  55. // linkPass makes relative links work from pages one folder down and turns
  56. // `code` naming a documented function or library into a link to it.
  57. type linkPass struct{}
  58. func (linkPass) Transform(doc *ast.Document, reader text.Reader, pc parser.Context) {
  59. rc, _ := pc.Get(ctxKey).(*renderCtx)
  60. if rc == nil {
  61. return
  62. }
  63. src := reader.Source()
  64. var spans []*ast.CodeSpan
  65. ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
  66. if !entering {
  67. return ast.WalkContinue, nil
  68. }
  69. switch v := n.(type) {
  70. case *ast.Link:
  71. if dest := string(v.Destination); isRelativeURL(dest) {
  72. v.Destination = []byte(rc.Root + dest)
  73. }
  74. return ast.WalkSkipChildren, nil
  75. case *ast.CodeSpan:
  76. spans = append(spans, v)
  77. return ast.WalkSkipChildren, nil
  78. }
  79. return ast.WalkContinue, nil
  80. })
  81. // Replace after the walk: swapping nodes while walking ends the loop
  82. // over their siblings early.
  83. for _, cs := range spans {
  84. url := rc.lookup(codeText(cs, src))
  85. if url == "" {
  86. continue
  87. }
  88. parent := cs.Parent()
  89. link := ast.NewLink()
  90. link.Destination = []byte(rc.Root + url)
  91. parent.ReplaceChild(parent, cs, link)
  92. link.AppendChild(link, cs)
  93. }
  94. }
  95. func codeText(n ast.Node, src []byte) string {
  96. var b strings.Builder
  97. for c := n.FirstChild(); c != nil; c = c.NextSibling() {
  98. switch t := c.(type) {
  99. case *ast.Text:
  100. b.Write(t.Segment.Value(src))
  101. case *ast.String:
  102. b.Write(t.Value)
  103. }
  104. }
  105. return b.String()
  106. }
  107. var callNameRe = regexp.MustCompile(`^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*(\(.*\))?;?$`)
  108. // lookup returns the URL documenting `code`, if any.
  109. func (rc *renderCtx) lookup(code string) string {
  110. m := callNameRe.FindStringSubmatch(strings.TrimSpace(code))
  111. if m == nil || rc.Skip[m[1]] {
  112. return ""
  113. }
  114. return rc.Syms[m[1]]
  115. }
  116. func isRelativeURL(u string) bool {
  117. if u == "" || strings.HasPrefix(u, "#") || strings.HasPrefix(u, "/") {
  118. return false
  119. }
  120. if i := strings.Index(u, ":"); i >= 0 && !strings.ContainsAny(u[:i], "/?#") {
  121. return false // has a scheme: https:, mailto:, ...
  122. }
  123. return true
  124. }
  125. // ---------- ids ----------
  126. var slugDropRe = regexp.MustCompile(`[^\p{L}\p{N}\s-]`)
  127. // slugify makes a readable element id from heading text.
  128. func slugify(s string) string {
  129. s = strings.ToLower(plainText(s))
  130. s = slugDropRe.ReplaceAllString(s, "")
  131. s = strings.Join(strings.Fields(s), "-")
  132. if s == "" {
  133. s = "section"
  134. }
  135. return s
  136. }
  137. // githubSlug is the anchor GitHub gives a heading, so links written for the
  138. // README (#dbtransactionfn--any) still land on the right card.
  139. func githubSlug(s string) string {
  140. s = strings.ToLower(plainText(s))
  141. var b strings.Builder
  142. for _, r := range s {
  143. switch {
  144. case r == ' ':
  145. b.WriteByte('-')
  146. case r == '-' || r == '_' || r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r > 127 && r != '→' && r != '—':
  147. b.WriteRune(r)
  148. }
  149. }
  150. return b.String()
  151. }
  152. var linkTextRe = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`)
  153. // plainText strips the Markdown marks of a heading.
  154. func plainText(md string) string {
  155. md = linkTextRe.ReplaceAllString(md, "$1")
  156. return strings.NewReplacer("`", "", "**", "", "*", "").Replace(md)
  157. }
  158. // idSet hands out unique element ids within a page.
  159. type idSet map[string]int
  160. func (s idSet) take(id string) string {
  161. n := s[id]
  162. s[id] = n + 1
  163. if n == 0 {
  164. return id
  165. }
  166. return id + "-" + strconv.Itoa(n+1)
  167. }
  168. // ---------- code blocks ----------
  169. var fencedRe = regexp.MustCompile("(?s)```[a-zA-Z]*\\n(.*?)\\n```")
  170. // codeBlocks returns the normalised fenced code of a Markdown body.
  171. func codeBlocks(md string) []string {
  172. var out []string
  173. for _, m := range fencedRe.FindAllStringSubmatch(md, -1) {
  174. out = append(out, normCode(m[1]))
  175. }
  176. return out
  177. }
  178. func normCode(s string) string {
  179. return strings.Join(strings.Fields(s), " ")
  180. }