# $Id: .zshrc,v 1.57 2006/12/17 06:33:18 han Exp $

# Below are the color init strings for the basic file types. A color init
# string consists of one or more of the following numeric codes:
# Attribute codes:
# 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
# Text color codes:
# 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
# Background color codes:
# 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white


# Show the TODO file
[ -e ~/*.please ] && < ~/*.please

# Pathes
path=(
    /sbin
    /usr/sbin
    /bin
    /usr/bin
    /usr/X11R6/bin
    /usr/local/sbin
    /usr/local/bin
)

manpath=(
    /usr/man
    /usr/share/man
    /usr/X11R6/man
    /usr/local/man
    /var/qmail/man
)

# Don't wanna know I got new mail :P
unset mailpath MAILCHECK
# mailpath=( "/usr/spool/mail/$LOGNAME?You inexplicably have new mail in /usr/spool/mail/$LOGNAME"
# "~/Mail/inbox?You have new mail in ~/Mail/inbox"
# "~/Mail/junk?You have junk mail in ~/Mail/junk" )

# Add local directory to the completer path
# fpath=($fpath ~/nfs/software)

# automatically remove duplicates from these arrays
typeset -U path cdpath fpath manpath


# Functions

saneperms()
{
    find . -type d -print0| xargs -0 chmod 755
    find . -type f -print0| xargs -0 chmod ${1:=644}
}


ur()
{
    if [ "$#" -eq 0 ]; then
        nice -n 19 unrar x *02.rar || nice -n 19 unrar x *.r01
    else
        nice -n 19 unrar x $@
    fi
}

tempwatch()
{
    while : ; do
	date "+%H:%M:%S $(sysctl hw.sensors.9|awk '{print $3}')°C"
	sleep 60
    done
}

mencode()
{

#    mencoder "$@" -vf pp=hb/vb/dr/al -oac copy -ovc xvid -xvidencopts pass=1:bitrate=700:turbo -o /dev/null
#    mencoder "$@" -vf pp=hb/vb/dr/al -oac copy -ovc xvid -xvidencopts pass=2:bitrate=700       -o ${@%.*}.avi
#     mencoder "$1" -vf pp=h1/v1/dr/tn/ci -oac copy -ovc xvid -xvidencopts pass=1:bitrate=${2:=700}:turbo -o /dev/null
#     mencoder "$1" -vf pp=h1/v1/dr/tn/ci -oac copy -ovc xvid -xvidencopts pass=2:bitrate=${2:=700}       -o ${1%.*}.avi
     mencoder "$1" -vf pp=al/c -oac copy -ovc xvid -xvidencopts pass=1:bitrate=${2:=700}:turbo -o /dev/null
     mencoder "$1" -vf pp=al/c -oac copy -ovc xvid -xvidencopts pass=2:bitrate=${2:=700}       -o ${1%.*}.avi
}

viewlatex()
{
    doc=${1%%.tex}
    latex $doc.tex && latex $doc.tex && xdvi $doc.pdf
    rm -f $doc.(dvi|aux|log|toc)
}

removeallspaces()
{
    find . -maxdepth 1 ! -name .| while read name; do
    noname=${name##*/}
    ext=${noname##*.}
    [[ $noname == ${noname// /} ]] && continue
    if [[ $ext == $noname ]]; then
	namecap=${(C)noname}
    else
	noname=${noname%.*}
	namecap=${(C)noname}.$ext
    fi
    namewos=${namecap// /}
    [[ $namewos != $noname ]] &&
    [[ $namecap != $namewos ]] &&
    mv -i $name $namewos
    done
}

# Display path in titlebar of terms.
chpwd()
{
    [[ -t 1 ]] || return 0
    case $TERM in
        *xterm*|rxvt|(dt|k|E)term)
            print -Pn "\e]2;%~\a"
            ;;
    esac
}


backup_and_edit()
{
    if [ $# -ne 1 ]; then
        echo 'What?'
        return 1
    fi
    [[ -r $1 && -f $1 ]] || {
	echo "${0##*/}: $1: no access to that file." >&2
	return 1
    }
    [ ! -r $1.orig ] && cp $1{,.orig}
    $EDITOR $1
}

doit()
{
    doithome=~/.doit
    if [ ! -d $doithome ]; then
        mkdir $doithome
    fi
    PWD_REAL=$(readlink -f $PWD)
    PWD_underscore=${PWD_REAL//\//_}
    unset doit_subdir
    for i in $doithome/*_SUBDIR(N); do
        h=${i#$doithome/}
        j=${h%_SUBDIR}
        if [[ ${PWD_underscore#$j} != $PWD_underscore ]]; then
	    PWD_underscore=$h
	    break
        fi
    done
    case $1 in
        delete)
            echo 'Removing the doit for this dir'
            rm -f $doithome/$PWD_underscore
            ;;
        edit)
            $EDITOR $doithome/$PWD_underscore
            ;;
        show)
            cat $doithome/$PWD_underscore
            ;;
        add)
            shift
            if [[ -z $1 ]]; then
                echo 'add requires an argument.'
                return 1
            fi
            echo "$@" >>! $doithome/$PWD_underscore
            ;;
        replace)
            shift
            if [[ -z $1 ]]; then
                echo 'add requires an argument.'
                return 1
            fi
            echo "$@" >! $doithome/$PWD_underscore
            ;;
        subdir)
            if [[ -e $doithome/$PWD_underscore ]]; then
                cat << EOF
$doithome/$PWD_underscore already exists, just use the normal doit
commands here.

EOF
            else
                PWD_underscore=${PWD_underscore}_SUBDIR
                echo 'What do you want to do in these subdirs? ;)'
                $EDITOR $doithome/$PWD_underscore
                echo 'Yes, lets doit again! :D'
            fi
            ;;
        help)
            cat << EOF
doit [edit|subdir|show|add|replace|delete|help] [your_doit_options]

doit creates a script which performs all the tasks you alway have
to perform in this specific directory or directorytree

EOF
            ;;
        *)
            if [[ -e $doithome/$PWD_underscore ]]; then
                echo 'Yes, lets do it! :)'
                # zsh error detection and follow up.
                TRAPZERR()
		{
                    echo 'Bah! >:(' >&2
                    return 1
                }
                case $1 in
                    log)
                        rm -f .doit_logfile
                        source $doithome/$PWD_underscore $@ >& .doit_logfile
                        ;;
                    *)
                        source $doithome/$PWD_underscore $@
                        ;;
                esac
                [ $? -eq 0 ] && echo 'Hurray! :D'
                TRAPZERR() {}
            else
                echo 'What do you want to do in this dir? ;)'
                $EDITOR $doithome/$PWD_underscore
                echo 'Yes, lets doit again! :D'
            fi

            ;;
    esac
}


viewmanpage()
{
    nroff -mandoc $1 | w3m
}


uptodate()
{
    wget --no-remove-listing $1 && cat .listing && rm .listing index.html
}


gnoort()
{
    # set -x
    PATH="/bin:/sbin:/usr/bin:/usr/local/bin"
    SUDO="sudo"
    FILENAME="$(readlink -f $1)"
    # Files may contain spaces, but they never contain a `#'
    # Sometimes \# but that's another story.

    # load the stat module for portability
    zmodload -a -i zsh/stat stat

    if [[ $UID -eq 0 ]]; then
	echo "gnoort: Don't run this script as root dummy :D" >&2
	return 1
    fi
    if [[ -z $EDITOR ]]; then
	echo "gnoort: env var \$EDITOR not set."
    fi

    if [[ -z $FILENAME ]]; then
	echo "gnoort: You want to bore me to death or what? :D" >&2
	return 1
    fi

    if [[ ! -f $FILENAME ]]; then
	echo "gnoort: $FILENAME does not exist." >&2
	return 1
    fi

    DIRNAME=${FILENAME:h}

    if [[ ! -d $DIRNAME ]]; then
	echo "gnoort: directory $DIRNAME does not exist." >&2
	return 1
    fi

    if [[ $(stat +uid $DIRNAME) -ne 0 ]]; then
	echo "gnoort: directory $DIRNAME isn't owned by root." >&2
	return 1
    fi

    if [[ $(stat +uid $FILENAME) -ne 0 ]]; then
	echo "gnoort: file $FILENAME isn't owned by root." >&2
	return 1
    fi

    TRAPEXIT()
    {
	$SUDO chown root "$FILENAME"

	echo gnoort: Original permissions on $FILENAME \
	restored. You can no longer edit it.
	return 1
    }

    if ! $SUDO chown $UID "$FILENAME"; then
	echo "gnoort: Can't chown $FILENAME back to your \$UID." >&2
	return 1
    fi

    $EDITOR "$FILENAME"

    $SUDO chown root "$FILENAME"

    TRAPEXIT(){}
    # set +x
    # unload this annoying module
    zmodload -u -i zsh/stat stat
    return 0
}

# insert-quote-magic

# If you now paste a url it will be magically quoted!
# But it only works on 4.2.0 and later.
if [ ${ZSH_VERSION//\./} -ge 420 ]; then
    autoload -U url-quote-magic
    zle -N self-insert url-quote-magic
fi




# Settings.

# set w3m as the pager and manpager if it exists
if which w3m &> /dev/null; then
    export PAGER=w3m
    # set to xterm to enable mousesupport in screen
    alias w3m='TERM=xterm LC_ALL= w3m'
    alias less='TERM=xterm LC_ALL= w3m'
    alias man='TERM=xterm LC_ALL= w3mman'
fi

umask 022

# This is default; change for other hosts.
editors=(Emacs editorwrapper emacs qe mg jed zile)

# OS specific settings
local PromptColor=$(echo '%{\e[3'$(($RANDOM%7))'m%}%{\e[01m%}')
case $OSTYPE in
    openbsd*)
        case $HOST in
            haddock*)
                editors=(emacsclient emacs mg)
                local PromptColor=$(echo '%{\e[36m%}')
                alias mutt='mutt -y'
                #alias mc='mccolor'
                export CVSROOT='/var/www/cvsroot'
                export QMAILHOST='mijncomputer.nl'
                alias spamstat="grep '===.*spam' ~/.Maildroplog|sort|uniq -c"
		alias burnaudiocd='sudo cdrecord dev=/dev/rcd1c:1,0,0 speed=24 -dao -pad -v *.wav'
		eject()
		{
		    if [ $# -eq 0 ]; then
			/bin/eject /dev/cd1c
		    else
			/bin/eject $*
		    fi
		}
                c4osync()
                {
                    (
                        TRAPINT()
			{
                            print "Caught SIGINT, aborting."
                            return 1
                        }
                        cd /usr/cruxports
			find . -name core|xargs rm
			zgrep '^[^l]....w....' **/.footprint.gz | egrep -v '(qmail)' && return 1
			zgrep '^[^l].......w.' **/.footprint.gz | egrep -v '(qmail)' && return 1
			tar czf cruxports_for_openbsd.tar.gz /usr/cruxports/core
                        chmod -R o+r *
                        if grep '# Maintainer: ' */*/Pkgfile|grep -v Boetes; then
                            echo 'fix that shit :-)' >&2
                            return 1
                        fi
			tar czf cruxports_for_openbsd.tar.gz $(find /usr/cruxports/core /usr/cruxports/INSTALL -type f ! -name '*.html')
                        makeindexhtml
                        httpup-repgen
                        rsync -p -P -L --recursive --times \
                            --delete \
			    INSTALL  PORTING  REPO  core  cruxports_for_openbsd.tar.gz  index.html  maywork  opt \
			    xs4all:WWW/software/c4o
                        TRAPINT() {}
                    )
                }
                ;;
            diodontis*)
                local PromptColor=$(echo '%{\e[01;35m%}')
		;;
	    phylon*)
		local PromptColor=$(echo '%{\e[01;34m%}')
		;;
            *)
		local PromptColor="$HOST "
		;;
        esac
	# hard to remember.
	ldd_forlibs()
	{
	    readelf -ds $1|fgrep NEEDED
	}

        alias nl='export CVSROOT=anoncvs@anoncvs.nl.openbsd.org:/cvs'
        if which gls &> /dev/null; then
            alias ls='gls --color=yes'
        elif which colorls &> /dev/null; then
            alias ls='colorls -FG'
        fi
        alias lsof='echo use fstat'
        alias sh='sh -l'
	alias ksh='ksh -l'
        export PKG_PATH='ftp://ftp.openbsd.org/pub/OpenBSD/snapshots/packages/i386/'
        ;;


    linux*)
        case $HOST in
            marsupilami*)
                cruxsync()
                {
                    (
                        TRAPINT()
			{
                            print "Caught SIGINT, aborting."
                            return 1
                        }
                        cd /usr/ports/mine
                        chmod -R o+r *
                        if grep '# Maintainer: ' */Pkgfile|grep -v Boetes; then
                            echo 'fix that shit :-)' >&2
                            return 1
                        fi
                        rm **/*~
			grep '^[^l]....w....' */.footprint | egrep -v '(pathological|gtkballs|qmail)' && return 1
			grep '^[^l].......w.' */.footprint | egrep -v '(qmail)' && return 1
                        ~/nfs/software/makeindexhtml
                        portspage \
                            --title= \
                            --header=/mnt/nfs/etc/portsindex.html.header \
                            --footer=/mnt/nfs/etc/portsindex.html.footer \
                            /usr/ports/mine |\
                            sed -e 's|/usr/ports/mine|han|' \
                            >! index.html
                        httpup-repgen
                        rsync -p -P -L --recursive --times --delete . \
			    xs4all:WWW/software/crux/han
                        TRAPINT() {}
                    )
                }

                ut_casa()
                {
		    xsetkeylock num off
                    alsactl -f ~/.tmp/sound_settings store
                    alsactl -f ~/.q3a/sound_settings restore
                    botnames=(
                        Penguin Scarab Puma Boa Widow Chicken
                        Cockroach Cobra Cougar Goose Scorpion
                        Raven Python Tiger Mantis Cheetah
                    )
                    opties=(+set fs_game q3ut3 +map ut_casa +set g_gametype 4)
                    no_bots=$#botnames
                    for (( i = 1; i <= 5; i++)); do
                        random=$((($(random_number) % $no_bots) + 1))
                        bots=($bots +addbot $botnames[$random] 4 blue)
                        botnames[$random]=()
                        no_bots=$(($no_bots - 1))
                    done
		    cd /usr/local/games/quake3
                    ./quake3 $opties $bots
                    alsactl -f ~/.tmp/sound_settings restore
                }
		q4()
		{
		    pkill unclutter
		    quake4 +disconnect
		    unclutter -idle 2 -jitter 10 -root &!
		}

                easy()
		{
		    find . -type f -exec chmod 644 {} \;
		    easytag .
		    id3v2 -s *.mp3 && normalize *.mp3
		    vorbisgain -af *.ogg
		    metaflac --add-replay-gain *.flac
		    replaygain --auto *.mpc
		    find . -type f -exec chmod 444 {} \;
		}

                local PromptColor=$(echo '%{\e[34m%}')
                alias quake3='quake3 -h'
		alias doom3='doom3'
                alias ut='quake3 +set fs_game q3ut3 +connect '
                alias mc='mccolor'
                alias grep='grep --color=auto'
		alias mvt='mv ~/.tmp/*.torrent /mnt/cd/tmp'
		alias ksh='mksh -l'
		alias klassiek='mplayer http://150.135.250.53:9000'
                export GNU_SECURE=~/.emacs.d/authorized_hosts
                # nvidia settings
                export __GL_FSAA_MODE=3 #or 4
                export __GL_DEFAULT_LOG_ANISO=1
                # export __GL_SYNC_TO_VBLANK=0
                # export MENUCONFIG_COLOR=alt
                # Lilipond
                # export TEXMF='{/usr/share/lilypond/2.4.1,/usr/share/texmf}'
                ;;
            lisa*)
                local PromptColor=$(echo '%{\e[37m%}')
		;;
	    *)
		local PromptColor="$HOST "
                ;;
        esac
        alias ls='ls -pb --color=auto --time-style=local'
        ;;

    freebsd*)
        case $HOST in
            *xs4all*)
                editors=(emacs zile)
                local PromptColor=$(echo '%{\e[33m%}')
                ;;
        esac
        export PACKAGESITE='ftp://ftp.nluug.nl/pub/FreeBSD/ports/i386/packages-4.6-stable/All/'
        if which gls &> /dev/null; then
            alias ls='gls --color=yes'
        elif which gnuls &> /dev/null; then
            alias ls='gnuls --color=yes'
        else
            alias ls='ls -FG'
        fi
        ;;

    *)
	local PromptColor="$HOST "
	;;

esac


# Editors for root.
if [ $UID -eq 0 ]; then
    editors=(mg qe jed zile jmacs emacs)
fi

# Set the editor.
for editor in $editors; do
    if which $editor >& /dev/null; then
        export EDITOR==$editor
        export VISUAL=$EDITOR
        alias e=$EDITOR
        break
    fi
done
[[ -z $EDITOR ]] && echo 'No suitable editor found. Use tramp. :-}'

alias vipw='EDITOR=sudoedit sudo vipw'

# load colors
autoload -U colors
colors

# Set the prompt.
prompt="$PromptColor%~%(!|%{$fg[yellow]%}|%{$fg_bold[black]%})%(?..%{$fg[red]%})%#%{$fg_no_bold[default]%} "

# Special setting for inside emacs.
[[ $INSIDE_EMACS = t ]] && unsetopt zle


# Environment Variables.

# Nice colors, this var is also used by gnu-ls so for consitency I prefer gnu-ls.
export LS_COLORS='no=00:fi=00:di=01;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;00:cd=40;33;00:or=40;31;00:ex=00;32:*.tar=00;31:*.tgz=00;31:*.rar=00;31:*.ace=00;31:*.zip=00;31:*.bz2=00;31:*.rpm=00;31:*.gz=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.png=00;35:*.tga=00;35:*.xpm=00;35:*.mpg=00;37:*.avi=00;37:*.mov=00;37:*.mp3=01;35:*.flac=01;35:*.ogg=01;35:*.mpc=01;35:*.wav=01;35:*.ape=01;35:*.core=00;33'
zstyle ':completion:*' list-colors $LS_COLORS

# History
export HISTSIZE=5000
export HISTFILE=~/.history_zsh
export SAVEHIST=4000
export TMP=~/.tmp
export TMPDIR=$TMP
export NULLCMD=:
export PERL_BADLANG=0
export LC_ALL=en_GB

# This is for antialiasing for qt- and gtk-apps
export QT_XFT=1
export GDK_USE_XFT=1

# We always want to use ssh for rsync.
export RSYNC_RSH=ssh
# And for ssh as well.
export CVS_RSH=ssh

unset WORDCHARS

# Aliases
alias rsync='rsync -prtvLP'
alias r="source ~/.zshrc" # my shells often last longer than the settings.

# alias rm='rm -i'
alias mv='mv -i'
alias cp='cp -i'
alias p='cd -'
alias l='ls -lhA'
alias df='df -h'
alias cvsup='cvs -q up -PAd'
alias c='cd ~; clear'
alias par='parchive r *.((p|P)??|(par|PAR)2)'
alias rs=rsync
alias unrar='nice -n 19 unrar'
whence htop > /dev/null && alias top=htop


# Global aliases -- These do not have to be at the beginning of
# the command line.
alias -g L='|less'
alias -g G='|grep'
alias -g X='|xargs'
alias -g H='|head'
alias -g T='|tail'
alias -g U='|tai64nlocal'


# Limits.
# ulimit unlimited
# limit stack 8192
limit core unlimited
# limit -s


# Set/unset shell options.
setopt \
    brace_ccl inc_append_history hist_ignore_space \
    hist_no_store hist_no_functions hist_ignore_all_dups \
    hist_expire_dups_first no_hup \
    no_check_jobs autocd autolist autopushd autoresume \
    cdablevars extendedglob globdots longlistjobs \
    noclobber notify pushdminus pushdsilent \
    pushdtohome rcquotes recexact sunkeyboardhack \
    complete_in_word

# setopt autocd correct correctall
unsetopt bgnice autoparamslash cdablevars

# Autoload zsh modules when they are referenced.
# zmodload -a zsh/zpty zpty
# zmodload -a zsh/zprof zprof
# zmodload -ap zsh/mapfile mapfile


# Completion Styles

# Setup new style completion system. To see examples of the old
# style -- compctl based -- programmable completion, check
# Misc/compctl-examples in the zsh distribution.
autoload -U compinit
compinit

# list of completers to use
zstyle ':completion:*::::' completer _expand _complete _ignored #_approximate

# Insert all expansions for expand completer
zstyle ':completion:*:expand:*' tag-order all-expansions

# Formatting and messages.
zstyle ':completion:*' verbose no #yes
zstyle ':completion:*:descriptions' format '%B%d%b'
zstyle ':completion:*:messages' format '%d'
zstyle ':completion:*:warnings' format 'No matches for: %d'
zstyle ':completion:*:corrections' format '%B%d (errors: %e)%b'

# Offer indexes before parameters in subscripts
zstyle ':completion:*:*:-subscript-:*' tag-order indexes parameters

# Command for process lists, the local web server details and host
# completion.
zstyle ':completion:*:processes' command 'ps x -o pid,nice,pcpu,tt,args'

# Hosts to use for completion, see later zstyle.
zstyle '*' hosts $(awk '/^[^#]/ {print $3" "$4" "$5}' /etc/hosts)

# Filename suffixes to ignore during completion, except after rm
# command.
zstyle ':completion:*:*:(^rm):*:*files' ignored-patterns \
    '*?.o' '*~' # '*?.orig'

# Ignore completion functions, until the _ignored completer.
zstyle ':completion:*:functions' ignored-patterns '_*'

# Disable unused completers.
compdef _default \
    apachectl apm apt apt-show-versions archie arp arping cvsup \
    debchange debfoster debpackages dict dictwords domains dpkg \
    dpkgsourceelm fetchmail figlet finger groups iconv imagemagick \
    ispell java lp mailboxes mail make-kpkg mplayer mysqldiff \
    mysqlutils ncftp nedit netscape newsgroups pine printers \
    print rlogin slrn spamassassin texi \
    texinfo tiff tin userathost users userson w3m yp urpmi rpm

# Since w3mman is aliased to man...
compdef _man w3mman


# Keysbinds
# Use ^v to find out the keynames
bindkey '^[[2~' overwrite-mode
bindkey '^[[3~' delete-char
bindkey '^[[5~' up-line-or-history
bindkey '^[[6~' down-line-or-history
bindkey '^[[7~' beginning-of-line
bindkey '^[[8~' end-of-line
bindkey '^[,'   insert-last-word # I always hit m-, instead if m-. for some reason

bindkey -e                 # emacs key bindings
bindkey ' '  magic-space   # also do history expansion on space
bindkey '^I' complete-word # complete on tab, leave expansion to _expand

# Unbind c-s and c-q
stty -ixon
