fix section parsing logic

This commit is contained in:
2026-01-04 17:00:00 +00:00
parent bc646f1aba
commit 0eaba474bf
+31 -35
View File
@@ -237,51 +237,47 @@ func parseSections(source []byte) []Section {
reader := text.NewReader(source) reader := text.NewReader(source)
doc := md.Parser().Parse(reader) doc := md.Parser().Parse(reader)
var sections []Section title := "no title"
var currentTitle string sections := make([]Section, 0)
var currentStart int = -1 lastPos := 0
for child := doc.FirstChild(); child != nil; child = child.NextSibling() { for child := doc.FirstChild(); child != nil; child = child.NextSibling() {
if child.Kind() == ast.KindHeading { if child.Kind() == ast.KindHeading {
heading := child.(*ast.Heading) if child.Lines().Len() <= 0 {
continue
if currentStart != -1 {
headingStart := heading.Lines().At(0).Start
if headingStart > currentStart {
sectionContentRaw := string(source[currentStart:headingStart])
sectionContent := strings.TrimSpace(sectionContentRaw)
sections = append(sections, Section{
Title: currentTitle,
Content: sectionContent,
Hints: extractHints(sectionContent),
})
}
} }
if heading.Lines().Len() > 0 { level := child.(*ast.Heading).Level
start := heading.Lines().At(0).Start headingStart := child.Lines().At(0).Start - level - 1
stop := heading.Lines().At(heading.Lines().Len() - 1).Stop headingEnd := child.Lines().At(child.Lines().Len() - 1).Stop
currentTitle = string(source[start:stop])
currentStart = stop
} else {
currentTitle = string(heading.Text(source))
currentStart = -1
}
} else { contentEnd := headingStart
if currentStart == -1 { if lastPos < contentEnd {
currentStart = 0 // you have a heading and a content to accumulte over
contentsRaw := source[lastPos:contentEnd]
contents := strings.TrimSpace(string(contentsRaw))
hints := extractHints(contents)
sections = append(sections, Section{
Title: title,
Content: contents,
Hints: hints,
})
lastPos = headingEnd
} }
// for the next heading
title = strings.TrimSpace(string(source[headingStart:headingEnd]))
lastPos = headingEnd
} }
} }
// last section
if currentStart != -1 && currentStart < len(source) { if lastPos < len(source) {
sectionContentRaw := string(source[currentStart:]) contentsRaw := source[lastPos:]
sectionContent := strings.TrimSpace(sectionContentRaw) contents := strings.TrimSpace(string(contentsRaw))
hints := extractHints(contents)
sections = append(sections, Section{ sections = append(sections, Section{
Title: currentTitle, Title: title,
Content: sectionContent, Content: contents,
Hints: extractHints(sectionContent), Hints: hints,
}) })
} }