#!/bin/ksh
# ve: edit a file in $EDITPATH
# @(#) ve.ksh 1.0 94/04/23
# 92/03/06 john h. dubois iii (john@armory.com)
# 92/10/16 exec editor
# 92/11/22 pass -opt and +opt to editor
# 93/04/29 pass + to vi
# 93/11/19 Added -p option
# 94/04/23 Read $HOME/.ve

typeset -i ShowPath=0

alias istrue="test 0 -ne"
alias isfalse="test 0 -eq"

name=${0##*/}
if [ "$1" = -h ]; then
    echo \
"$name: edit a file in EDITPATH.
Syntax: $name [-hp] [[-+]vi_option] filename ...
For each filename given, $name searches each directory named in the
environment variable EDITPATH in the order given and finds the first
instance of filename.  If a file is not found, a message is printed.
When all of the files have been searched for, $name invokes the editor on
them.  EDITPATH has the same format as PATH and CDPATH, except that
directories may be separated by either a ':' or whitespace, and the usual
ksh filename expansions are done.  Examples:
dir1:dir2:dir3:...
dir1{a,b} dir2/* dir3 ...
EDITPATH can also be set in a file in the user's home directory named \".ve\".
To determine what editor to use, $name first looks at the value of the
environment variable EDITOR, then VISUAL.  If neither is set, vi is used.
Initial arguments that start with '-' or '+' are passed to the editor
without interpretation.  If vi is used, the argument '+' is passed.
Options:
-h: print this help.
-p: show what EDITPATH looks like after expansion."
    exit 0
fi

if [ -z "$EDITPATH" ] ; then
    rc=$HOME/.ve
    [ -f $rc -a -r $rc ] && . $HOME/.ve
    if [ -z "$EDITPATH" ] ; then
	echo "EDITPATH not set."
	exit 1
    fi
fi

if [ "$1" = -p ]; then
    ShowPath=1
    shift
fi

typeset -i argind=0 numopts
unset args error
while [[ "$1" = [-+]* ]]; do
    args[argind]=$1
    let argind+=1
    shift
done
numopts=argind

set -A files -- "$@"
OIFS=$IFS
IFS=":$IFS"
set -- $EDITPATH
IFS=$OIFS

if istrue ShowPath; then
    IFS=:
    print -- "$*"
    exit
fi

for file in "${files[@]}"; do
    for dir; do
        if [ -f "$dir/$file" ]; then
	    args[argind]=$dir/$file
	    let argind+=1
	    continue 2
	fi
    done
    echo "$name: $file: file not found."
    error=1
done

if [ -n "$error" ]; then
    if [ argind -gt numopts ]; then
	echo -n "press return to edit other files..."
	read
    else
	exit
    fi
fi

EDITOR=${EDITOR:-${VISUAL:-vi}}
[[ "$EDITOR" = ?(*/)vi ]] && EDITOR="$EDITOR +"
exec $EDITOR "${args[@]}"
