Skip to content

Instantly share code, notes, and snippets.

@ernstki
Last active March 4, 2022 00:04
Show Gist options
  • Save ernstki/70c110249ff784c2144656f884bdd5b5 to your computer and use it in GitHub Desktop.
Save ernstki/70c110249ff784c2144656f884bdd5b5 to your computer and use it in GitHub Desktop.
Center a man page within a wide terminal
#!/bin/bash
manc ()
{
local DEFAULT_WIDTH=100
local manpage margin pad
local width=$DEFAULT_WIDTH
local termwidth=$(tput cols)
while (( $# )); do
case $1 in
-w*|--width*)
if [[ $1 =~ --?w(idth=)?([1-9][0-9]*)$ ]];
then
width=${BASH_REMATCH[2]}
else
shift
if [[ -z ${1:-} || ! $1 =~ ^[1-9][0-9]*$ ]]; then
echo "ERROR: The -w / --width option expects an" \
"integer argument." >&2
return 1
fi
width=$1
fi
;;
-*)
echo "ERROR: Unrecognized option '$1'." >&2
return 1
;;
*)
if [[ ${manpage:-} ]]; then
echo "ERROR: One manual page at a time, please!" >&2
return 1
fi
manpage=$1
;;
esac
shift
done
if (( termwidth < width )); then
echo "WARNING: '-w $width' is wider than the terminal." >&2
width=$termwidth
else
margin=$(( (termwidth - width) / 2 ))
pad=$(printf "%${margin}s")
fi
if [[ -z $manpage ]]; then
echo "What manual page do you want?"
return # on macOS/BSD anyway, this *doesn't* return failure
fi
(
(( ${DEBUG:-} )) && set -x
set -eo pipefail
manpath=$(man -w $manpage)
groff -Tascii -rLL=${width}n -man $manpath \
| sed "s/^/$pad/" \
| ${PAGER:-less -FRX}
)
}
if [[ -z ${PS1:-} ]]; then
manc "$@"
fi
@ernstki
Copy link
Author

ernstki commented Mar 3, 2022

Installation

Assuming a reasonably default macOS or Linux box and the Bash shell:

GIST=https://gist.githubusercontent.com/ernstki/70c110249ff784c2144656f884bdd5b5/raw
mkdir -p ~/bin
curl "$GIST" > ~/bin/manc
chmod a+x ~/bin/manc

# make sure it works
manc

It's quite rare for it not to be these days, but if $HOME/bin is not in your search path, you can update that in your ~/.bash_profile or ~/.profile (whichever one you have):

export PATH=$HOME/bin:$PATH

Log (completely) out and back in in order for this change to take effect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment