mantoc/mantoc

68 lines
1.4 KiB
Bash
Executable file

#!/bin/sh
usage() {
printf 'Usage: %s [section] name\n' "$(basename "$0")" >&2
exit 1
}
case $# in
1)
;;
2)
case "$1" in
[0-9]*)
;;
*)
printf '%s: Error: Section not recognized: %s\n' "$(basename "$0")" "$1" >&2
usage
;;
esac
;;
*)
usage
;;
esac
select_best() {
[ $# -eq 0 ] && return
# Follow mandoc's default section ordering.
for section in 1 8 6 2 3 5 7 4 9 3p
do
for page in "$@"
do
dir="$(basename "$(dirname "$page")")"
if [ "${dir#man}" = "$section" ]
then
printf '%s' "$page"
return
fi
done
done
printf '%s' "$1"
}
IFS='
'
# shellcheck disable=SC2046
file="$(select_best $(man -w "$@"))"
[ -z "$file" ] && exit 1
cat="cat"
case "$file" in
*.gz)
cat="zcat"
;;
esac
# Both mdoc(7) and man(7) use two-level headings with .Sh/.SH for top-level
# headings and .Ss/.SS for subheadings, but other markup on the line might be
# parsed differently depending on which markup language the document uses. Thus,
# we rely on man(1) to automatically detect the language.
#
# Well-formed mdoc(7) files must start with .Dd, .Dt, .Os in that order.
# Technically both mandoc's and man's autodetect work as long as .Dd is present,
# but if we are including some of the preamble, we might as well include it
# fully and get correct header and footer.
# Similarly, for consistency we pass through man(7) .TH, which sets the heading.
"$cat" "$file" | grep -E '^\.(S[HhSs]|TH|D[dt]|Os)' | man -l /dev/stdin