#!/bin/bash

Version=1.01
Myname="${0##*/}"

:<<'DOC'
= v - edit file(s) with vim, (or gvim, emacs)

= Synopsis
v [options]		# -h --help -H --Help -V --version
v [file... ]		# edit one or more files
v -script [file...]	# edit script found in PATH plus 0 or more files
v --texfile [file... ]	# edit TeX file found with kpsewhich plus 0 or more files

= Description
This script is called v, and it runs vim. However, if installed as links to
v named *g* or *e*, then gvim or emacs are called instead. In the latter
case, if emacs is not found, xemacs is called, and if an emacs server is
running, it is used for editing.

If given one or more /file/s they let you edit those files, just like the
vim, gvim or emacs editors. However, the first of the given /file/
arguments is treated differently from the rest:

--file	(filename prefixed with two hyphens):
	they look for a TeX file using kpsewhich and let you edit it.
	
-script	(filename prefixed with a single hyphen):
	they look for a script |script| in |$PATH| and let you edit it.

The idea behind this script is laziness; for example: I very often need to
edit one of my many (mostly bash-)scripts. Instead of trusting my memory
to know where, in |$PATH|, the script is stored, I rather like this script
to find it.

= Author
[Wybo Dekker](wybo@dekkerdocumenten.nl)

= Copyright
Released under the [GNU General Public License](www.gnu.org/copyleft/gpl.html)
DOC

REd='\e[38;5;9m'
    die() { local i; for i; do echo -e "$Myname: $REd$i"; done 1>&2; exit 1; }
helpsrt() { sed -n '/^= Synopsis/,/^= /p' "$0"|sed '1d;$d'; exit; }
instscr() { instscript --zip --pdf "$Myname"; exit; }

# shellcheck disable=SC2154
helpall() { sed -n "/^:<<'DOC'$/,/^DOC/p" "$0"|sed -n '1d;$d;p'|
            less -Ps"$Myname-${Version/./·} documentation - type h for help, q to quit."
		exit
	  }

declare -A mapping=([v]=vim [g]=gvim [e]=emacs)
declare -A exts=([pdf]=ok [ods]=oo)

# find the full pathname of an executable in the PATH
# returns nil if the executable is not found

file="$1"         # first file to be edited (maybe a script if prefixed with - )
shift

case $file in
(-h|--help)
	helpsrt
	;;
(-H|--Help)
	helpall
	;;
(-V|--version)
	echo $Version
        exit
	;;
(-I)	# install - not for general use
	instscr
	;;
(--*)	# if the first argument starts with =--
	f=${file:2}
	file=$(kpsewhich "$f" 2>/dev/null) || 
	     die "No tex file $f found"
	;;
(-*)	# if the first argument starts with =-
	f=${file:1}
	file=$(command -v "$f" 2>/dev/null) || 
	     die "No executable file $f found"
	;;

esac

editor=${mapping[$Myname]}
ext=${file##*.}
case $ext in
(pdf) editor=vpp;;
(ods) editor=oo;;
(jpg|jpeg|JPG|JPEG) editor=xv;;
(png|PNG) editor=okular;;
esac
$editor -- "$file" "$@"
