Skip to content

Commit 53021d5

Browse files
findleyrgopherbot
authored andcommitted
internal/cmd/weave: keep track of minimum header depth
Allow for outlines that start at a header level greater than 1, by keeping track of the minimum header level encountered in the table of contents. Change-Id: I779726531883ecae3f980eb47cefe886ffef8b4f Reviewed-on: https://go-review.googlesource.com/c/example/+/703895 Reviewed-by: Alan Donovan <[email protected]> Auto-Submit: Robert Findley <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]>
1 parent ca27133 commit 53021d5

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

internal/cmd/weave/weave.go

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,19 @@ func main() {
8787
printf("<!-- Autogenerated by weave; DO NOT EDIT -->\n")
8888

8989
// Pass 1: extract table of contents.
90-
var toc []string
90+
type tocEntry struct {
91+
depth int
92+
text string
93+
anchor string
94+
}
95+
var (
96+
toc []tocEntry
97+
// We indent toc items according to their header depth, so that nested
98+
// headers result in nested lists. However, we want the lowest header depth
99+
// to correspond to the root of the list. Otherwise, the entire list is
100+
// indented, which turns it into a code block rather than an outline.
101+
minTocDepth int
102+
)
91103
scanner := bufio.NewScanner(in)
92104
for scanner.Scan() {
93105
line := scanner.Text()
@@ -97,18 +109,21 @@ func main() {
97109
line = strings.TrimSpace(line)
98110
if line == "%toc" {
99111
toc = nil
112+
minTocDepth = 0
100113
} else if strings.HasPrefix(line, "# ") || strings.HasPrefix(line, "## ") {
101114
words := strings.Fields(line)
102115
depth := len(words[0])
116+
if minTocDepth == 0 || depth < minTocDepth {
117+
minTocDepth = depth
118+
}
103119
words = words[1:]
104120
text := strings.Join(words, " ")
105121
anchor := strings.Join(words, "-")
106122
anchor = strings.ToLower(anchor)
107123
anchor = strings.ReplaceAll(anchor, "**", "")
108124
anchor = strings.ReplaceAll(anchor, "`", "")
109125
anchor = strings.ReplaceAll(anchor, "_", "")
110-
line = fmt.Sprintf("%s1. [%s](#%s)", strings.Repeat("\t", depth-1), text, anchor)
111-
toc = append(toc, line)
126+
toc = append(toc, tocEntry{depth: depth, text: text, anchor: anchor})
112127
}
113128
}
114129
if scanner.Err() != nil {
@@ -125,7 +140,7 @@ func main() {
125140
switch {
126141
case strings.HasPrefix(line, "%toc"): // ToC
127142
for _, h := range toc {
128-
printf("%s\n", h)
143+
printf("%s1. [%s](#%s)\n", strings.Repeat("\t", h.depth-minTocDepth), h.text, h.anchor)
129144
}
130145
case strings.HasPrefix(line, "%include"):
131146
words := strings.Fields(line)

0 commit comments

Comments
 (0)