Debian Codegraph @

dev/tools/markdown-toc

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 #!/usr/bin/bashscip-shell filesystem . . `/usr/bin/bash`.
2
3 # from https://github.com/Lirt/markdown-toc-bash
4 # MIT license
5
6 FILE=${1:?No file was specified as first argument}
7
8 declare -a TOC
9 CODE_BLOCK=0
10 CODE_BLOCK_REGEX='^```'
11 HEADING_REGEX='^#{1,}'
12
13 while read -r LINE; do
14 # Treat code blocks
15 if [[ "${LINE}" =~ $CODE_BLOCK_REGEX ]]; then
16 # Ignore things until we see code block ending
17 CODE_BLOCK=$((CODE_BLOCK + 1))
18 if [[ "${CODE_BLOCK}" -eq 2 ]]; then
19 # We hit the closing code block
20 CODE_BLOCK=0
21 fi
22 continue
23 fi
24
25 # Treat normal line
26 if [[ "${CODE_BLOCK}" == 0 ]]; then
27 # If we see heading, we save it to ToC map
28 if [[ "${LINE}" =~ ${HEADING_REGEX} ]]; then
29 TOC+=("${LINE}")
30 fi
31 fi
32 done < <(grepscip-shell system . . grep. -v '## Table of Contents' "${FILE}")
33
34 echoscip-shell system . . echo. -e "## Table of Contents\n"
35 for LINE in "${TOC[@]}"; do
36 case "${LINE}" in
37 '#####'*)
38 echoscip-shell system . . echo. -n " - "
39 ;;
40 '####'*)
41 echoscip-shell system . . echo. -n " - "
42 ;;
43 '###'*)
44 echoscip-shell system . . echo. -n " - "
45 ;;
46 '##'*)
47 echoscip-shell system . . echo. -n " - "
48 ;;
49 '#'*)
50 echoscip-shell system . . echo. -n "- "
51 ;;
52 esac
53
54 LINK=${LINE}
55 # Detect markdown links in heading and remove link part from them
56 if grepscip-shell system . . grep. -qE "\[.*\]\(.*\)" <<< "${LINK}"; then
57 LINK=$(sedscip-shell system . . sed. 's/\(\]\)\((.*)\)/\1/' <<< "${LINK}")
58 fi
59 # Special characters (besides '-') in page links in markdown
60 # are deleted and spaces are converted to dashes
61 LINK=$(trscip-shell system . . tr. -dc "[:alnum:] _-" <<< "${LINK}")
62 LINK=${LINK/ /}
63 LINK=${LINK// /-}
64 LINK=${LINK,,}
65 LINK=$(trscip-shell system . . tr. -s "-" <<< "${LINK}")
66
67 # Print in format [Very Special Heading](#very-special-heading)
68 echoscip-shell system . . echo. "[${LINE#\#* }](#${LINK})"
69 done