mdtoc/tree.go

75 lines
1.5 KiB
Go
Raw Normal View History

2024-05-05 16:38:35 +02:00
package main
2024-05-06 01:09:44 +02:00
import (
"fmt"
)
2024-05-06 00:58:57 +02:00
func get_root_children(headings []heading) []int {
var root_children []int
lowest_level := 0
for index, value := range headings {
cur_level := value.level
if index == 0 || cur_level <= lowest_level {
root_children = append(root_children, index)
lowest_level = cur_level
}
}
return root_children
}
2024-05-05 19:54:43 +02:00
func get_child_indices(header_index int, headings []heading) []int {
var children []int
2024-05-06 01:09:44 +02:00
if header_index == -1 {
children = get_root_children(headings)
return children
}
parent_level := headings[header_index].level
2024-05-05 19:54:43 +02:00
if header_index >= (len(headings) - 1) {
return nil
}
2024-05-06 01:09:44 +02:00
next_level := headings[header_index+1].level
2024-05-05 19:54:43 +02:00
child_level := 0
if next_level <= parent_level {
return nil
} else {
child_level = next_level
}
cur_level := 0
for i := (header_index + 1); i < len(headings); i++ {
2024-05-06 01:09:44 +02:00
cur_level = headings[i].level
2024-05-05 19:54:43 +02:00
if cur_level == child_level {
children = append(children, i)
}
if cur_level < child_level {
break
}
}
return children
}
2024-05-06 01:09:44 +02:00
func tree(index int, prefix string, headings []heading) {
children := get_child_indices(index, headings)
for index, child_index := range children {
if index == (len(children) - 1) {
2024-05-06 01:40:29 +02:00
fmt.Printf("%s %s (%d)\n", prefix+"`--", headings[child_index].text, headings[child_index].line)
2024-05-06 01:09:44 +02:00
tree(child_index, prefix+" ", headings)
} else {
2024-05-06 01:40:29 +02:00
fmt.Printf("%s %s (%d)\n", prefix+"|--", headings[child_index].text, headings[child_index].line)
2024-05-06 01:09:44 +02:00
tree(child_index, prefix+"| ", headings)
}
}
}