Merge pull request 'heading-struct' (#1) from heading-struct into master

Reviewed-on: #1
This commit is contained in:
bjoernf 2024-04-30 11:07:18 +02:00
commit 09a8626a85
2 changed files with 19 additions and 11 deletions

View File

@ -9,6 +9,6 @@ This seems intended by the creators of the language.
- count number of headings for each heading level - count number of headings for each heading level
(loop through all headings, find the highest heading level, get all used levels\ (loop through all headings, find the highest heading level, get all used levels\
then create a slice or slice of maps and append after each deeper level discovered...) then create a slice or slice of maps and append after each deeper level discovered...)
- add docs - print heading tree
- delph deeper into different Markdown implementations (like CommonMark) - delph deeper into different Markdown implementations (like CommonMark)
- add support for "Setext-style headers" - add support for "Setext-style headers"

28
main.go
View File

@ -13,6 +13,12 @@ import (
"strings" "strings"
) )
type heading struct {
text string
level int
line int
}
func is_heading(line string) bool { func is_heading(line string) bool {
if strings.HasPrefix(line, "#") { if strings.HasPrefix(line, "#") {
return true return true
@ -21,20 +27,22 @@ func is_heading(line string) bool {
} }
} }
func get_heading_level(heading string) int { func get_heading_level(heading_text string) int {
level := 0 level := 0
for i := 0; heading[i] == '#'; i++ { for i := 0; heading_text[i] == '#'; i++ {
level += 1 level += 1
} }
return level return level
} }
func print_toc(headings []string) { func print_toc(headings []heading) {
tab_count := 0 tab_count := 0
for index, value := range headings { for index, _ := range headings {
if index > 0 { if index > 0 {
prev_level := get_heading_level(headings[index-1]) prev_level := get_heading_level(headings[index-1].text)
cur_level := get_heading_level(headings[index]) cur_level := get_heading_level(headings[index].text)
headings[index].level = cur_level
if cur_level > prev_level { if cur_level > prev_level {
tab_count += (cur_level - prev_level) tab_count += (cur_level - prev_level)
@ -45,14 +53,14 @@ func print_toc(headings []string) {
fmt.Printf("\t") fmt.Printf("\t")
} }
} }
fmt.Printf("%s\n", value) fmt.Printf("%v\n", headings[index])
} }
} }
func main() { func main() {
file_content_raw, err := os.ReadFile(os.Args[1]) file_content_raw, err := os.ReadFile(os.Args[1])
var headings []string = nil var headings []heading = nil
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
@ -62,9 +70,9 @@ func main() {
file_lines := strings.Split(file_content, "\n") file_lines := strings.Split(file_content, "\n")
for _, value := range file_lines { for index, value := range file_lines {
if is_heading(value) { if is_heading(value) {
headings = append(headings, value) headings = append(headings, heading{value, 0, (index + 1)})
} }
} }