### .cshrc				-*-Mode: csh;-*- when in Emacs
### original by Greg Allen 1997
if ($?TC_VERBOSE) set verbose
if ($?TC_ECHO) set echo
if ($?TC_FAST) exit

unalias jobcmd postcmd precmd

if ( "$home" == "/" ) set home=/var/tmp/$USER

umask 2
if ($SHELL =~ /Launcher* && ! $?DUMMY) then
    setenv DUMMY
    set path=(~/bin $path)
    /usr/openwin/bin/xterm -e /usr/bin/csh -i &
endif

## switch to tcsh (doesn't return if this is csh)
# workaround for $0:t csh bug
set _0=none; if ($?0) eval 'set _0=$0'
# automatically switch to tcsh if possible
if ( ! $?NO_TCSH && $_0:t != which ) then
    # see if tcsh is available
    if ( $SHELL !~ */tcsh || $SHELL == /usr/bin/tcsh ) then
	set _shell=`set path=(~/bin $path); which tcsh`
	if ( "$_shell" =~ */tcsh ) setenv SHELL $_shell
	unset _shell
    endif
    if ( $SHELL !~ */tcsh && -x $HOME/bin/tcsh ) setenv SHELL $HOME/bin/tcsh
    # if appropriate replace this shell with a tcsh
    if ( ! $?tcsh && $?prompt && $?TERM ) then
	if ( $SHELL =~ */tcsh && -x $SHELL ) then
	    exec $SHELL
	endif
    endif
endif
#unset _0

if (! $?projname) set projname
if ($?tcsh) then
    set echo_style=both
    if ($?TERM && "$tty" != "") then
	switch ($TERM)
	    case xterm:
	    case dtterm:
		eval 'echo -n "\033]2;$user @ $HOST : $projname $cwd:s%'"$HOME"'%~% % source .cshrc\007"'
	endsw
    endif
endif

if (! $?LOGNAME && $?USER) then
    setenv LOGNAME $USER
endif

if ($?LOGNAME && $?USER) then
    if ($LOGNAME != $USER) setenv USER $LOGNAME
endif

if (! $?HOSTNAME) setenv HOSTNAME `hostname`
if (! $?HOST)     setenv HOST $HOSTNAME

## hack to pass the display through an rlogin
## set TERM to DISPLAY.TERM to use, e.g. dv_css2k.8.0.xterm
## csh bug: can only use :r:e on shell variables, not env vars
if ( $?TERM ) then
    if ( $term =~ *:[0-9]*.* ) then
	setenv DISPLAY $term:r
	set term=$term:e
    endif
endif

# $XDISPLAY is like $DISPLAY, but is guaranteed to include the hostname
if ( $?XDISPLAY ) then
    # consistency check
    if ( $XDISPLAY !~ *$DISPLAY ) unsetenv XDISPLAY
endif
if ( $?DISPLAY && ! $?XDISPLAY ) then
    if ( $DISPLAY =~ :* ) then
	setenv XDISPLAY $HOSTNAME$DISPLAY
    else
	setenv XDISPLAY $DISPLAY
    endif
endif

#unsetenv MANPATH_
if ( ! $?MANPATH_ ) then
    if ( ! $?MANPATH ) setenv MANPATH /usr/share/man
    foreach mandir ( ~/packages/man /homeusr/local/man /homeusr/local/kde/man ~/man/perl5/man ~/man/openwin/man ~/man/dt/man /usr/perl5/5.00503/man /opt/SUNWspro/man )
	if (-d $mandir) setenv MANPATH $MANPATH\:$mandir
    end
    if (-d ~/man) setenv MANPATH ~/man:$MANPATH
    setenv MANPATH_
endif

#if ( ! $?OSREV ) then
#    setenv OSREV `uname -r`
#endif

# sanity checking of the path

# canonicalize path first
if ($?tcsh) then
    set -f path=($path)
    # /apps/bin belongs only at the end of the path if anywhere
    if (":${PATH}:" =~ *:/apps/bin:*) set -l path=($path /apps/bin)
    # /usr/local/bin must come after /usr/ccs/bin
    if (":${PATH}:" =~ *:/usr/local/bin*:/apps/bin:*) set -l path=($path /usr/local/bin)
endif

# /usr/ucb must not come before /usr/ccs/bin else we'll get the wrong version of ld
if ( ":${PATH}:" =~ *:/usr/ucb*:/usr/ccs/bin:* ) then
    if ($?tcsh) then
	set -l path = ( $path /usr/ucb )
    else
	setenv PATH `echo $PATH | sed 's%:/usr/ucb:%:%'`:/usr/ucb
    endif
endif

set _paths = ( /usr/sbin /usr/dt/bin )
if ( ! $?OPENWINHOME && -d /usr/openwin ) setenv OPENWINHOME /usr/openwin
if ( $?OPENWINHOME ) then
    set _paths = ( $_paths $OPENWINHOME/bin )
endif

setenv KDEDIR /homeusr/local/kde-3.0.3

set _paths = ( $_paths /usr/local/bin /opt/SUNWspro/bin /homeusr/local/bin $KDEDIR/bin /homeusr/local/gcc-3.2/bin /usr/perl5/bin )

foreach _path ( $_paths )
    if ( :${PATH}: !~ *:${_path}:* && -d $_path ) setenv PATH ${_path}:$PATH
end
unset _path _paths

# forcibly stick my bin directory at the front of the path
if ("$PATH" !~ $HOME/bin:* && -d ~/bin) setenv PATH ~/bin:$PATH

if ( -d ~/lib ) then
    if ( ! $?LD_LIBRARY_PATH ) then
	setenv LD_LIBRARY_PATH ~/lib
    else if ( :${LD_LIBRARY_PATH}: !~ *:$HOME/lib:* ) then
	setenv LD_LIBRARY_PATH ~/lib:$LD_LIBRARY_PATH
    endif
endif


if ( :${LD_LIBRARY_PATH}: !~ *:$KDEDIR/lib:* ) then
    setenv LD_LIBRARY_PATH $KDEDIR/lib:$LD_LIBRARY_PATH
endif

## fix path: remove duplicates and non-existent directories
# VALID_PATH avoids wasting time doing this again for sub-shells
if ( ! $?VALID_PATH ) setenv VALID_PATH
if ( "$VALID_PATH" != "$PATH" ) then
#    echo "Validating path"
    setenv VALID_PATH
    if ($?tcsh) then
	# tcsh can make path entries unique with set -f
	set -f path = ( $path )
	foreach _p ( $path )
	    if ( -d $_p ) setenv VALID_PATH $VALID_PATH\:$_p
	end
    else
	foreach _p ( $path )
	    if ( -d $_p && :${VALID_PATH}: !~ *:${_p}:* ) setenv VALID_PATH $VALID_PATH\:$_p
	end
    endif
    unset _p
    # hacky way to remove leading :, working around csh defects. motto: never fork
    setenv PATH $VALID_PATH
    shift path
    # workaround - shift doesn't update PATH
    set path = ( $path )
    setenv VALID_PATH $PATH
endif

unset noclobber ignoreeof

if (! $?REMOTEHOST) setenv REMOTEHOST unknown
if ("$LOGNAME" != "$USER" || "$HOST" != "$REMOTEHOST") echo "`date` on $HOST from $REMOTEHOST as $LOGNAME" >> ~/.xpc_startup.LOG 
setenv REMOTEHOST $HOST

### end of non-interactive setup ###
unalias exit
# exit if this doesn't look like an interactive session
# (might be running under at/cron or rsh though)
if ( ! $?prompt ) exit

### unless we really have a terminal to setup, exit now
if ($?tty) then
    # believe tcsh if it says we have a terminal - i.e. $tty isn't blank
    # worry about the other case, where $tty is blank - in that case use
    # the tty command to check
    if ("$tty" == "") tty -s || exit
else
    # have to test for ourselves
    tty -s || exit
endif

set history=(1000 '%S%h%s\t%B%d%D %T%b\t%% %R\n') savehist=(1000 merge) filec fignore=('~' '#' '@' .o .flc .bak .backup .orig)

# for aliases that are only needed on production, or are host specific
if ( -r ~/.aliases ) source ~/.aliases

# Preferences for interactive shells
alias ..	'cd ../\!*'
alias ...	'cd ../../\!*'
alias ....	'cd ../../../\!*'
alias a2ps	'\a2ps -M0.9 -F7.5'
alias csh	env NO_TCSH= SHELL=/bin/csh csh
alias cp	'\cp -p'
alias crenv	'exec start -l'
alias df	'\df -k'
alias du	'\du -k'
alias duu	'du -sk `find * -type d -print -prune`'
alias ffind	'find . \! -name "*[~#]" -name \*\!:1\* -print'
alias ftp	'ftp \!*; stty -istrip'
alias h		history 50
alias hg	'history | grep'
alias gc	gnuclient
alias hhh	'stty erase ^h'
#alias konsole	'konsole --bg #000028'
alias ls	'gls --color=auto'
alias l		ls -F
alias la	ls -aCF
alias lf	'ls \!* `find * -prune -type f`'
alias ll	ls -lF
alias lla	ls -lFa
alias llt	ls -ltrF
alias lsd	'ls -dCF `find . \! -name . -prune -type d | sed "s|^\./||"`'
alias lt	ls -trCF
alias mwm	'win mwm; xrdb -merge ~/.Xdefaults && \mwm'
alias pd	'pushd'
alias perfmeter '\perfmeter -geometry 55x300'
alias prt	'mp -A4 -lo'
alias psg	'ps -ef | sed -n "1p;/ $$ .* sed .* $$/d;/\!:1/p"'
alias psl	'ps -ovsz,pid,ppid,user,stime,args -e | sed '\''/<defunct>$/d'\'' | sort -n | sed '\''/^ VSZ/h;$G'\'' | tail -15'
alias psme	ps -fu $USER
alias psmg	'ps -fu $USER | sed -n "1p;/ $$ .* sed .* $$/d;/\!:1/p"'
alias qrm	'mkdir -p .delete-me-$$ && mv \!* .delete-me-$$ && rm -rf .delete-me-$$ &'
alias runsql    'sqsh -Lsemicolon_hack=0 -Lprompt='\''$database $lineno> '\'' -e -a1 -i \!*'
alias sqsh	'\sqsh \!*; tput cud1'
alias so	source
#alias startkde	'set -f path=(/homeusr/local/kde-3.0.3/bin $path); env LD_LIBRARY_PATH=/homeusr/local/kde-3.0.3/lib:${LD_LIBRARY_PATH:s#/homeusr/local/kde-3.0.3/lib:##} KDEDIR=/homeusr/local/kde-3.0.3 startkde'
alias up	'cd ..'
alias vnc	'vncserver :9 -depth 24 -geometry 2560x1022'
alias xgrep	'xargs grep -ni'

alias xterm	rxvt

setenv LESS -e

# distinguish between rxvt
if ( $?COLORTERM ) then
    if ($COLORTERM == "") set Konsole
    if ($COLORTERM =~ rxvt*) set Rxvt
endif

if ($?ENV) then
    set proj="$ENV"
    set proj="$proj:t"
    set projname
    if (! $?Konsole) set projname="($proj)"
    if (-r ~/.cshrc.wlb) source ~/.cshrc.wlb
else
    set proj
endif

# this switch handles directory tracking in the prompt and title bar
# try hard to choose the most efficient method, depending on the
# capabilities of the shell and terminal
switch ( $TERM )
    case xterm:
    case aixterm:
    case dtterm:
	if ( $?tcsh ) then
	    alias _echo echo
	else
	    alias _echo /usr/5bin/echo
	endif
	alias win   '_echo "\033]0;\!*\007\c"'
	alias icon  '_echo "\033]1;\!*\007\c"'
	alias title '_echo "\033]2;\!*\007\c"'
	alias sess  '_echo "\033]30;\!*\007\c"'
	if ( $?tcsh ) then
	    # don't need win alias to set title bar - use fancy prompt
	    # the bit between %{ %} sets the title bar and icon label
	    if ($?Konsole) then
		set icon_prompt='%c05'
		set userhost=''
	    else
		set icon_prompt='%~'
		set userhost='%n @ %m : '
	    endif
	    set icon_prompt='%{\033]1;'"$userhost$icon_prompt"' - '"$proj"'\007\033]2;'"$userhost$projname"' '"$icon_prompt"'\007%}'
	    if ($TERM == dtterm || $?COLORTERM) then
		set prompt="$icon_prompt"'%B%{\033[33m%}%n@%m:%{\033[34m%}%c04 %{\033[36m%}%#%b '
	    else
		set prompt="$icon_prompt"'%B%n@%m:'"$projname"'%c03 %#%b '
	    endif
	    # recent directory tracking
	    set rdirs=(. . . . .)
	    alias cd 'chdir \!*; set rdirs=("$owd" $rdirs[1-4])'
	    alias rcd 'if ("\!*" != "") chdir `eval echo '\''$rdirs[\!*]'\''`; if ("\!*" == "") echo "1 $rdirs[1]\n2 $rdirs[2]\n3 $rdirs[3]\n4 $rdirs[4]\n5 $rdirs[5]"'
	else
	    # in csh use win alias to set title bar and icon
	    if (! $?NO_CD) alias cd 'chdir \!* >/dev/null; set prompt="$user@${HOSTNAME}:$cwd % "; title "$user @ $HOSTNAME : $projname:q $cwd"'
	endif
	breaksw
    default:
	# can't set title bar
	if ( $?tcsh ) then
	    # no need for a cd alias - do it all with the prompt
	    unalias cd
	    if ($?EMACS) then
		set prompt="$projname"':%c03 %# '
	    else
		set prompt='%B%n@%m:'"$projname"'%c03 %#%b '
	    endif
	    alias win	:
	    alias icon	:
	    alias title	:
	else
	    if (! $?NO_CD) alias cd 'chdir \!* >/dev/null; set prompt="$user@${HOSTNAME}:$projname$cwd % "'
	    # csh can't sink arguments with :, but must refer to ! somehow
	    alias win	': \!:0:e'
	    alias icon  ': \!:0:e'
	    alias title	': \!:0:e'
	endif
endsw

if ($?ENV) then
     icon "$user@$HOSTNAME : $ENV"
endif

unalias pushd popd
if ( $?tcsh ) then
    ### capabilities only available in tcsh
    # tcsh rm builtin is broken - won't remove link to read-only file
    alias rm /bin/rm
    # prompt options
    set promptchars='%#' ellipsis
    # completion options
    set complete=enhance listlinks autolist=ambiguous autoexpand recexact correct=cmd
    set dunique dextract pushdsilent
    alias pd	'pushd \!*; dirs -v'
    if (! $?EMACS ) alias dirs dirs -v

    # history options
    set histdup=erase histfile=~/.tcsh_history
    # auto-cd
    set implicitcd=verbose

    bindkey -k up	history-search-backward
    bindkey -k down	history-search-forward
    bindkey '\e[2~'	dabbrev-expand		# insert
    bindkey '\e[3~'	delete-char		# del
    bindkey '\e[5~'	complete-word-back	# page up
    bindkey '\e[6~'	complete-word-fwd	# page down
    bindkey '\e[7~'	beginning-of-line	# rxvt home
    bindkey '\e[8~'	end-of-line		# rxvt end
    bindkey '\e[20~'	complete-word-fwd	# F9
    bindkey '\e[21~'	complete-word-back	# F10
    bindkey -b M-s	i-search-fwd
    bindkey -b M-r	i-search-back
    bindkey -b M-$	expand-variables
    bindkey '\244'	expand-variables # M-$ notation seems to be broken
    bindkey -b M-*	expand-glob
    bindkey -b M-8	expand-glob
    bindkey '\e8'	expand-glob
    bindkey -b M-4	expand-variables
    bindkey '\e4'	expand-variables
    bindkey -b M-_	insert-last-word
    bindkey ' '		magic-space

    bindkey -b M-b	backward-word
    bindkey -b M-c	capitalize-word
    bindkey -b M-d	delete-word
    bindkey -b M-f	forward-word
    bindkey -b M-h	run-help
    bindkey -b M-l	downcase-word
    bindkey -b M-n	history-search-forward
    bindkey -b M-p	history-search-backward
    bindkey -b M-r	toggle-literal-history
    bindkey -b M-u	upcase-word
    bindkey -b M-w	copy-region-as-kill
    bindkey -b M-y	yank-pop
    bindkey '\377'	backward-delete-word

    bindkey '\e[\304'	backward-word		# rxvt M-left
    bindkey '\e[\303'	forward-word		# rxvt M-right
    bindkey '\e[\301'	beginning-of-line	# rxvt M-up
    bindkey '\e[\302'	end-of-line		# rxvt M-down

    bindkey '\eOd'	backward-word		# rxvt C-left
    bindkey '\eOc'	forward-word		# rxvt C-right
    bindkey '\eOa'	upcase-word		# rxvt C-up
    bindkey '\eOb'	downcase-word		# rxvt C-down

    bindkey '\e[3\376'	delete-word		# rxvt M-delete
   
    complete {,un}alias p/1/a/ p/2/c/
    complete bindkey	N/-a/b/ N/-c/c/ n/-'[ascr]'/'x:<key-sequence>'/ \
			n/-'[svedlr]'/n/ c/-'[vedl]'/n/ c/-/"(a b s k c v e d l r)"/\
			n/-k/"(left right up down)"/ p/2-/b/ \
			p/1/'x:<key-sequence or option>'/
    complete {c,push,p}d 'p/1/d/'
    complete debugger	'p/1/c/' 'p/2/`ps -u$USER -opid=`/'
    complete env	'c/*=/f/' 'C/[A-Z]/e/=/' 'p/2-/c/'
    complete find	'n/-name/f/' 'n/-newer/f/' \
			'n/-exec/c/' 'n/-ok/c/' 'n/-user/u/' 'n/-group/g/' \
			'n/-type/(b c d f l p s)/' \
			'c/-/(name newer cpio ncpio exec ok user \
			group fstype type atime ctime depth inum \
			ls mtime nogroup nouser perm print prune \
			size xdev)/ ' \
			'p/*/d/'
    complete gunzip	'p/*/f:*.{,t}gz/'
    complete kill	'c/-/S/ ' 'p/*/`ps -u$USER -opid=`/'
    complete man	'p/*/c/'
    complete set	'p/*/s/=' 'c/*=/f/'
    complete tar	'n/*f*/f:*[._]{tar{,.gz,.Z},tgz}/'
    complete unset	'p/*/s/ '
    complete setenv	'p/1/e/ ' 'c/*:/f/'
    complete uncompress	'p/*/f:*.Z/'
    complete unsetenv	'p/*/e/ '
    complete unzip	'p/*/f:*.zip/'
    complete which	'p/*/c/'    

    complete ./configure 'c/--*=/f/' 'c/--{cache-file,prefix,exec-prefix,\
    				bindir,sbindir,libexecdir,datadir,\
				sysconfdir,sharedstatedir,localstatedir,\
				libdir,includedir,oldincludedir,infodir,\
				mandir,srcdir}/(=)//' \
			 'c/--/(cache-file verbose prefix exec-prefix bindir \
			 	sbindir libexecdir datadir sysconfdir \
				sharedstatedir localstatedir libdir \
				includedir oldincludedir infodir mandir \
				srcdir)//'

    complete make \
	'n/-f/f/' \
      	'c/*=/f/' \
	'n@*@`cat -s GNUmakefile Makefile makefile |& sed -n -e "/No such file/d" -e "/^[^     #].*:/s/:.*//p"`@'

    # these deal with NIS (formerly YP)
    if (-X domainname) then
	if (! $?_domain) setenv _domain "`domainname`"
	set _ypdir  = /var/yp	# directory where NIS (YP) maps are kept
	if ("$_domain" != "" && "$_domain" != "noname") then
	    set noglob
	    complete domainname p@1@D:$_ypdir@" " n@*@n@
	    complete ypcat	c@-@"(d k t x)"@ n@-x@n@ n@-d@D:$_ypdir@" " \
				N@-d@\`\\ls\ -1\ $_ypdir/\$:-1\ \|\ sed\ -n\ s%\\\\.pag\\\$%%p\`@ \
				n@*@\`\\ls\ -1\ $_ypdir/$_domain\ \|\ sed\ -n\ s%\\\\.pag\\\$%%p\`@
	    complete ypmatch    c@-@"(d k t x)"@ n@-x@n@ n@-d@D:$_ypdir@" " \
				N@-d@x:'<key ...>'@ n@-@x:'<key ...>'@ p@1@x:'<key ...>'@ \
				n@*@\`\\ls\ -1\ $_ypdir/$_domain\ \|\ sed\ -n\ s%\\\\.pag\\\$%%p\`@
	    complete ypwhich    c@-@"(d m t x V1 V2)"@ n@-x@n@ n@-d@D:$_ypdir@" " \
				n@-m@\`\\ls\ -1\ $_ypdir/$_domain\ \|\ sed\ -n\ s%\\\\.pag\\\$%%p\`@ \
				N@-m@n@ n@*@\$hosts@
	endif
	unset _ypdir noglob
    endif

else
    ### when only plain csh capabilities are available
    alias l ls -CF
    # relying on the cd alias to set the prompt
    alias pushd 'pushd \!*; cd .'
    alias popd  'popd; cd .'
    # set the prompt for the first time
    if ($_0:t != which) then
	cd $cwd
    endif
endif

### terminal setup
# ensure TERMCAP gets reset
switch ( $TERM )
    case emacs:
	setenv TERM dumb
	# don't break
    case dumb:
	if ( $?EMACS ) then
	    if ( ! $?TERMCAP ) setenv TERMCAP emacs:tc=unknown:
	    stty cols `gnuclient -batch -eval '(1- (window-width))'`
	endif
	# This helps for rlogins from shell-mode in Emacs
	stty -echo -onlcr
	# used to have no color ls, but now we have emacs ansi-color
	#unalias ls
	breaksw
    case emacs-virtual:
	stty -echo -onlcr erase '^?'
	breaksw
    case xterm:
	# enable Meta key for tcsh
	stty -istrip -ixon
	# double check if rxvt or xterm
	if ( $?COLORTERM && ! $?KONSOLE_DCOP) then
	    if ( $?WINDOWID ) then
		if ( $COLORTERM =~ rxvt* ) then
		    if ( ! $?RXVT_WINDOWID ) setenv RXVT_WINDOWID -1
		    if ( $RXVT_WINDOWID != $WINDOWID ) then
			# ensure this really is rxvt
			set _term_class=(`xprop -id $WINDOWID WM_CLASS`)
			if ( "$_term_class" =~ *rxvt* ) then
			    setenv RXVT_WINDOWID $WINDOWID
			else
			    unsetenv COLORTERM COLORFGBG RXVT_WINDOWID
			endif
			unset _term_class
		    endif
		endif
	    else
		# WINDOWID not set - doesn't look like an X Window
		unsetenv COLORTERM COLORFGBG RXVT_WINDOWID
	    endif
	endif
	# still sure it's rxvt? or maybe konsole
	if ($?COLORTERM) then
	    stty erase '^?'
	else
	    stty erase ^h
	endif
	breaksw
    case vt320:
	# Exceed telnet from home reports vt320
	setenv TERM vt220
	breaksw
    case ansi:
	# Telnet from NT4
	setenv TERM vt220
	breaksw
endsw

if ( $TERM == xterm || $TERM == dtterm || $TERM =~ vt[12]?? || $?EMACS ) then
    set color
    # directories purple and pipes blue
    unsetenv LS_COLORS
#	setenv LS_COLORS 'di=01;35:so=01;34'
#	setenv LS_COLORS 'no=00:fi=00:di=01;35:ln=01;36:pi=40;33:so=01;34:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.deb=01;31:*.rpm=01;31:*.jpg=01;35:*.png=01;35:*.gif=01;35:*.bmp=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.png=01;35:*.mpg=01;35:*.avi=01;35:*.fli=01;35:*.gl=01;35:*.dl=01;35:'
endif

# in xterm Delete key may send ^?
if ( $?tcsh && ! $?COLORTERM ) bindkey "^?" delete-char

# for emacs shell buffers, we can pretend to be a vt220
# this gives us underlining and standout modes
if ( $?ANSI_COLOR && $?EMACS ) setenv TERM vt220

# really ought to be last
#if ($TERM == xterm || $TERM == dtterm) alias jobcmd 'echo -n "\033]2;$user @ $HOSTNAME : $projname $cwd:s%'"$HOME%~% % '\!#:q'\007"\"
