2023-11-13 09:33:28 -05:00
|
|
|
#!/bin/sh
|
|
|
|
|
2024-07-08 05:41:45 -04:00
|
|
|
## SPDX-FileCopyrightText: 2023 - 2024 Benjamin Grande M. S. <ben.grande.b@gmail.com>
|
2023-11-13 09:33:28 -05:00
|
|
|
##
|
|
|
|
## SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
|
|
|
|
## Requires: https://github.com/mzlogin/vim-markdown-toc
|
|
|
|
set -eu
|
|
|
|
|
|
|
|
usage(){
|
2024-08-06 12:15:24 -04:00
|
|
|
printf '%s\n' "Usage: ${0##*/} <file> [file ...]"
|
2023-11-13 09:33:28 -05:00
|
|
|
exit 1
|
|
|
|
}
|
|
|
|
|
|
|
|
case "${1-}" in
|
|
|
|
""|-h|--help) usage;;
|
2024-07-10 08:36:05 -04:00
|
|
|
*) ;;
|
2023-11-13 09:33:28 -05:00
|
|
|
esac
|
|
|
|
|
|
|
|
## vim-markdown-toc deletes lines if they are folded, can't rely on its native
|
|
|
|
## update on save.
|
|
|
|
if ! vim -e -c 'setf markdown' -c 'if !exists(":GenTocGFM") | cq | endif' -c q
|
|
|
|
then
|
2024-08-06 12:15:24 -04:00
|
|
|
err_msg="Error: Vim Plugin mzlogin/vim-markdown-toc isn't installed."
|
|
|
|
printf '%s\n' "${err_msg}" >&2
|
2023-11-13 09:33:28 -05:00
|
|
|
exit 1
|
|
|
|
fi
|
|
|
|
|
|
|
|
|
2024-07-10 08:36:05 -04:00
|
|
|
for f in "${@}"; do
|
|
|
|
if ! test -f "${f}"; then
|
2024-08-06 12:15:24 -04:00
|
|
|
printf '%s\n' "Error: Not a regular file: ${f}" >&2
|
2023-11-13 09:33:28 -05:00
|
|
|
exit 1
|
|
|
|
fi
|
2024-08-06 11:04:16 -04:00
|
|
|
if ! grep -q -e "^## Table of Contents$" -- "${f}"; then
|
2024-08-06 12:15:24 -04:00
|
|
|
printf '%s\n' "Could not find TOC in file: ${f}, skipping" >&2
|
2023-11-13 09:33:28 -05:00
|
|
|
continue
|
|
|
|
fi
|
|
|
|
## This is fragile, the table of contents should have at least one block
|
|
|
|
## separated by an empty line before the nest heading, else it will delete
|
|
|
|
## the rest of the file.
|
2024-07-09 11:42:07 -04:00
|
|
|
vim -c 'norm zRgg' -c '/^## Table of Contents$' -c 'norm jd}k' \
|
|
|
|
-c ':GenTocGFM' -c 'norm ddgg' -c wq -- "${f}"
|
2024-08-06 12:15:24 -04:00
|
|
|
printf '%s\n' "Updated TOC in file: ${f}"
|
2023-11-13 09:33:28 -05:00
|
|
|
done
|