Improve sections
This commit is contained in:
+26
@@ -3,6 +3,9 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"regexp"
|
||||
|
||||
"github.com/yuin/goldmark/ast"
|
||||
"github.com/yuin/goldmark/text"
|
||||
)
|
||||
|
||||
var sectionHeadingRe = regexp.MustCompile(`(?m)^#{1,6} `)
|
||||
@@ -25,6 +28,29 @@ func splitSections(raw []byte) [][]byte {
|
||||
return sections
|
||||
}
|
||||
|
||||
// headingIDs returns the auto-generated id of every heading in raw markdown,
|
||||
// in document order. The kth heading (1-indexed) corresponds to section k from
|
||||
// splitSections. Uses the package-level goldmark parser so duplicate-id
|
||||
// numbering matches what the renderer emits.
|
||||
func headingIDs(raw []byte) []string {
|
||||
doc := md.Parser().Parse(text.NewReader(raw))
|
||||
var ids []string
|
||||
ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
|
||||
if !entering {
|
||||
return ast.WalkContinue, nil
|
||||
}
|
||||
if _, ok := n.(*ast.Heading); ok {
|
||||
if v, ok := n.AttributeString("id"); ok {
|
||||
if b, ok := v.([]byte); ok {
|
||||
ids = append(ids, string(b))
|
||||
}
|
||||
}
|
||||
}
|
||||
return ast.WalkContinue, nil
|
||||
})
|
||||
return ids
|
||||
}
|
||||
|
||||
// joinSections reassembles sections produced by splitSections.
|
||||
// Inserts a newline between sections when a non-empty section lacks a
|
||||
// trailing newline, so an edited section cannot inline the next heading.
|
||||
|
||||
Reference in New Issue
Block a user