Skip to content

Commit c7a7036

Browse files
committed
fix: don't add arbitrary if some headers are skipped
1 parent ea8d420 commit c7a7036

File tree

1 file changed

+43
-3
lines changed

1 file changed

+43
-3
lines changed

pkg/toc/toc.go

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ var (
2525
finishRe = regexp.MustCompile(`(?i)\<!--\s*(end of toc|tocstop|/TOC)\s*--\>`)
2626
)
2727

28+
var skip = 0
29+
2830
// Run handles the application logic.
2931
func Run() {
3032
var toc toc
@@ -65,7 +67,7 @@ func (t *toc) logic() {
6567
os.Exit(1)
6668
}
6769

68-
if t.Options.Append != true {
70+
if !t.Options.Append {
6971
fmt.Print(t.String())
7072
return
7173
}
@@ -82,7 +84,7 @@ func (t *toc) String() (s string) {
8284
color.Red("ERROR: skip value is bigger than the length of table of contents")
8385
os.Exit(1)
8486
}
85-
for _, v := range t.Content[t.Options.Skip:] {
87+
for _, v := range t.Content {
8688
s += v
8789
}
8890

@@ -102,9 +104,33 @@ func getHeaderValue(header string) int {
102104
return headers[header]
103105
}
104106

107+
func (t *toc) Last() int {
108+
if len(t.Content) >= 1 {
109+
switch spaceCount(t.Content[len(t.Content)-1]) {
110+
case 0:
111+
return 0
112+
case 4:
113+
return 1
114+
case 8:
115+
return 2
116+
case 12:
117+
return 3
118+
case 16:
119+
return 4
120+
case 20:
121+
return 5
122+
}
123+
}
124+
return 0
125+
}
126+
127+
func spaceCount(s string) int {
128+
return len(s) - len(strings.TrimLeft(s, " "))
129+
}
130+
105131
func (t *toc) getDelimiter(header int) string {
106132
// Set delimiter
107-
if t.Options.Bulleted != true {
133+
if !t.Options.Bulleted {
108134
return "1."
109135
}
110136

@@ -130,6 +156,20 @@ func (t *toc) parseHTML(body []byte) error {
130156
headerVal := getHeaderValue(n.Data)
131157

132158
if headerVal < t.Options.Depth {
159+
if len(t.Content) == 0 && headerVal != 0 {
160+
headerVal -= 1
161+
}
162+
163+
if (headerVal - t.Last()) > 1 {
164+
headerVal -= 1
165+
}
166+
167+
if t.Options.Skip > skip {
168+
skip += 1
169+
return
170+
}
171+
172+
fmt.Println(t.Content)
133173
t.add(fmt.Sprintf("%s%s [%s](#%s)\n", strings.Repeat(tab, headerVal), t.getDelimiter(headerVal), n.FirstChild.Data, n.Attr[0].Val))
134174
}
135175
}

0 commit comments

Comments
 (0)