-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex-gen.awk
executable file
·90 lines (86 loc) · 2.63 KB
/
index-gen.awk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/bin/awk -f
## Initialize
BEGIN {
print "\n\
###########################################\n\
# #\n\
# Index generator for markdown notes :) #\n\
# #\n\
###########################################\n\
"
in_block = 0
}
## Flag for code block detection
/^```/ {
switch (in_block) {
case 0:
in_block = 1
break
case 1:
in_block = 0
break
default:
exit 1
}
}
## If headings detected
/^#+ / && (FNR != 1) && (in_block != 1) {
# Convert headings to index link
index_link = gensub(/^#+ /, "", "g", tolower($0))
gsub(/ /, "-", index_link)
gsub(/-/, "A", index_link)
gsub(/_/, "B", index_link)
gsub(/\r|[[:punct:]]/, "", index_link)
gsub(/A/, "-", index_link)
gsub(/B/, "_", index_link)
# Store links in hashtable to check for duplicate links
if (index_hash[index_link]) {
index_hash[index_link]++
index_link = index_link "-" index_hash[index_link]-1
} else {
index_hash[index_link] = 1
}
# Convert headings to index name displayed
index_name = gensub(/^#+ ([0-9]+(\.[0-9]+)* )?|\r/, "", "g", $0)
# For different headings
if ($0 ~ /^### [0-9]+(\.[0-9]+){2} /) {
index_cnt++
index_arr[index_cnt] = " + [**" $2 "**](#" index_link ") " index_name
} else if ($0 ~ /^## [0-9]+\.[0-9]+ /) {
index_cnt++
index_arr[index_cnt] = " + [**" $2 "**](#" index_link ") " index_name
} else if ($0 ~ /^## [0-9]+ /) {
index_cnt++
index_arr[index_cnt] = "+ [**" $2 "**](#" index_link ") " index_name
} else if ($0 ~ /^# /) {
index_cnt++
index_arr[index_cnt] = "+ [**" index_name "**](#" index_link ")"
} else {
index_err_cnt++
index_err[index_err_cnt] = FNR
}
}
## Print index and check errors
END {
for (line in index_arr) {
print index_arr[line]
}
print "\n\
###########################################\n\
# #\n\
# Index generated #\n\
# #\n\
###########################################\n\
"
print "Report:"
if (index_err_cnt) {
printf "%d headings ignored at:\n", index_err_cnt
for (i in index_err) {
printf "Line %d\n", index_err[i]
}
exit 0
} else {
print "All headings printed"
exit 0
}
}