#!/bin/sh

# vim features I want to use more (at top for easy access)
bookmarks="
index
ranges
sessions
expand
internal-variables
functions
motion
text-objects
cmdline-special
sub-replace-special
clipboard
ins-completion-menu
vimball
netrw
zero-width
complex-repeat
"
# Direct access to vim's help files. Including a list of help topics on
# features I'm trying to get more familiar with (sort of works as a reminder
# list).
#
# In combination with this I have a zsh completion setup. This goes in an
# appropriate place in your zsh config files.
#
#_vimhelp() {
#    local tagsfile="/usr/share/vim/vimcurrent/doc/tags"
#    _complete_tag
#}
#compdef _vimhelp vimhelp
#zstyle ':completion:*:vimhelp:*' menu yes select

# Uses my pager.vim macro which just tweaks the vim settings to behave in a
# more pager like way. Get the pager.vim macro and put it in ~/.vim/macros/.
#
# The pager.vim macro should be available on my site (probably right next to
# where you got this) at <http://zhar.net/projects/shell/>.
# If not there look around for a vim area, I'm thinking about created one.

g=""
[ $# -gt 0 ] && [ "$1" = "-g" ] && g="g" && shift
if [ $# -gt 0 ]; then
  topic="$*"
else
  menu="<s:>main\n<s>"$(echo "${bookmarks}" | sed 's/\s/\\\n<s>/g')
  keys="-kj:KEY_DOWN -kk:KEY_UP"
  topic=$(echo "${menu}" | iselect -Q "_EXIT_" -t "Vim Help" -p 1 "${keys}")
  if [ "${topic}" = "_EXIT_" ]; then exit; fi
fi

tmpfile=$(mktemp)
trap 'rm -f ${tmpfile}; exit' 0 2
cat >>"${tmpfile}" <<EOF
function! Helpexit(topic)
    try
        exe "help" a:topic
    catch /E149:/
        cq
    endtry
endfunction
EOF

"${g}"view -c "source ${tmpfile}" \
  -i NONE \
  -c "call Helpexit(\"${topic}\")" -c "silent only" \
  -c "runtime! macros/pager.vim" \
  -c "set nospell"

ret=$?
if [ "${ret}" -ne 0 ]; then
  echo "Vim help not found."
fi

# slight delay to allow vim to source the file when forking the gui
[ -n "${g}" ] && sleep .1s
