#!/bin/zsh
# Filename:      qma
# Purpose:       "quick manual access"
# Authors:       grml-team (grml.org), (c) Michael Prokop <mika@grml.org>, Matthias Kopfermann <maddi@grml.org>
# Bug-Reports:   see http://grml.org/bugs/
# License:       This file is licensed under the GPL v2.
# Latest change: Mon Dez 04 22:54:47 CET 2006 [maddi]
################################################################################

. /etc/grml/lsb-functions
. /etc/grml/script-functions

check4progs man lzop vim || exit 1

VERSION='0.1'

MANDIR=${MANDIR:-$HOME/man}
if ! [ -d "$MANDIR" ] ; then
   einfo "Creating $MANDIR."
   mkdir $MANDIR ; eend $?
fi

usage() {
   eerror "Usage: qma [section] manpage" ; eend 1
   exit 1
}

case $1 in
  -h*|--h*)
    usage
    ;;
  -v*|--v*)
    einfo "qma - version $VERSION" ; eend 0
    exit 0
    ;;
  [0-9])
    SECTION="${1}"
    SECTIONFILE=".${1}"
    MANPAGE="$2"
    SEARCH="$3"
    ;;
  *)
    SECTION=''
    MANPAGE="$1"
    SEARCH="$2"
    ;;
esac


if [ -z "$MANPAGE" ] ; then
   usage
fi

QUICKMAN="${MANDIR}/${MANPAGE}${SECTIONFILE}.txt.lzo"

if ! [ -f "$QUICKMAN" ] ; then
   einfo "Writing manpage to $QUICKMAN"
   if man $SECTION $MANPAGE 1>/dev/null ; then
      man $SECTION $MANPAGE | lzop -U >$QUICKMAN ; eend $?
      einfo "Compressing manpage with lzop"
      eend $?
   else
      exit 1
      eend 1
   fi
fi

vimconfig='
 	 set filetype=man
	 "set hlsearch can be annoying so use <C-L> to dehighlight"
	 nn <silent> <C-L> :nohlsearch<cr>|redraw "shut up hlsearch when it confuses more than it helps and"
	 nn q :qa!<cr> "q should really end our document-reading like less does"
	 nn Q :q!<cr> "different than q in that it quits only the current window when multiple windows "
	 nn <F10> :qa!<cr> "honor midnight-commander addicts :) "
	 nn a ]I "use one wonderful vim feature to show all matches of the word in the document in ex-mode"
	 nn A [I "the other way round"
	 nn b <C-b>
	 nn <backspace> <C-f>
	 "nn f <C-f>
	 nn p }zz
	 nn j <C-E> "scroll the page down one line"
	 nn k <C-Y> "scroll the page up one line"
	 nn -n <ESC> :set invnumber<cr>  "the expectation of getting the next search via 'n' can not be ignored"
	 nn h :set invhlsearch<cr>
	 nn i :set invignorecase<cr> "Make toggling case-sensitive accessable via the letter i"
	 nn -i :set invignorecase<cr> "Make toggling case-sensitive accessable via the less convention via -i"
	 nn <space> <C-f>
	 nn <backspace> <C-b>
	 nn <enter> gg
	 nn S :split<cr>
	 nn V :vsplit<cr>
	set filetype=man
	set ignorecase
     	set nomodifiable "Really not modify a document here"
	set readonly
'

if [ -n "$SEARCH" ] ; then
  vim -S  =( echo $vimconfig  ) +/"$SEARCH" =( lzop -cd ${QUICKMAN} )
else
  vim -S =( echo $vimconfig  ) =( lzop -cd $QUICKMAN )
fi

einfo "Thanks for flying qma using vim and lzop." ; eend 0

## END OF FILE #################################################################
