#!/bin/sh
#
# viman - start vi(1) with a manual page

set -eu
:

tmpfile="${TMPDIR:=/tmp}/vm$$"

# assure file is removed at program termination or after we received a signal:
trap 'rm -f "$tmpfile" >/dev/null 2>&1' EXIT
trap "exit 2" HUP INT QUIT PIPE TERM

EXINIT="set ignorecase nowrapscan readonly"
export EXINIT

MANWIDTH=400 man "$@" | col -b | uniq >"${tmpfile}" || exit

[ -s "${tmpfile}" ] || exit 0
head -n 1 <"${tmpfile}" \
  | grep 'No.*entry' && exit 0 # no manual page

${EDITOR:-vi} "${tmpfile}"
