~ buttons /.zshrc

# .zshrc
# ZShell configuration

# Xdefaults dont work well all the time
if [[ ! -f $HOME/.Xdefaults-$(uname -n) && -f $HOME/.Xdefaults ]] ; then
    ln -s $HOME/.Xdefaults $HOME/.Xdefaults-$(uname -n)
fi

# urxvt compensation
if [[ "${TERM}" == "rxvt-unicode" ]] ; then
    export TERM=rxvt
fi

# Which implementation in shell
function ewhich() {
    while [[ -n "$1" ]] ; do
	if type -p $1 &> /dev/null ; then
            echo $(type -p $1)
      else
            echo ""
	fi
	
	shift
   done
}

# Do we have which?
if ! type -p which &> /dev/null ; then alias which="ewhich" ; fi

# Override the default variables

if [ -d ~/bin ] ; then
    PATH=~/bin:"${PATH}"
fi

if [ -d /media/home/buttons/Documents/amazonec2/ec2-api-tools-1.3-19403 ] ; then
	PATH="/media/home/buttons/Documents/amazonec2/ec2-api-tools-1.3-19403/bin:${PATH}"
fi

export HOSTNAME="$(uname -n)"
export HOSTTYPE="$(uname -m)"
export COLORTERM=yes
export CC=gcc
export PAGER=/usr/bin/less
export EDITOR="vim"

# UTF-8 Sexiness!! <cat call>
export LANG="en_US.utf8"
export LC_ALL="en_US.utf8"
export LC="en_US.utf8"
export LESSCHARSET="utf-8"

# GNU Colors
[ -f /etc/DIR_COLORS ] && eval $(dircolors -b /etc/DIR_COLORS)
export ZLSCOLORS="${LS_COLORS}"

# Alias commands
alias ls="ls -laph --color=auto"
alias mv="nocorrect mv"
alias cp="nocorrect cp"
alias man="nocorrect man"
alias mkdir="nocorrect mkdir"
alias mkcd="nocorrect mkcd"
alias rm="nocorrect rm"
alias ping="ping -c4"
alias df="df -h"
alias cgrep="grep --color=auto"
alias :q="exit"
alias :wq="exit"
alias y="tupac"
alias prun="mpirun -np 2 pyMPI"
alias nethack="telnet nethack.alt.org"

if type -p colorcvs &> /dev/null ; then alias cvs="colorcvs" ; fi
if type -p colordiff &> /dev/null ; then alias diff="colordiff" ; fi
if type -p colorgcc &> /dev/null ; then alias gcc="colorgcc" ; fi
if type -p colortail &> /dev/null ; then alias tail="colortail" ; fi
#if ! type -p ftp &> /dev/null ; then alias ftp="zftp" ; fi

# Bind keys
case $TERM in (xterm*) #Rutgers linux terminals
    bindkey "\eOH"  beginning-of-line
    bindkey "\eOF"  end-of-line
esac
bindkey "\e[7~" beginning-of-line
bindkey "\e[8~" end-of-line
bindkey '^E' end-of-line
bindkey '^A' beginning-of-line
bindkey "\e[2~" overwrite-mode
bindkey '^?' backward-delete-char
bindkey "\e[3~" delete-char
#bindkey "\e[5~" up-line-or-history
#bindkey "\e[6~" down-line-or-history
#bindkey "\e" vi-cmd-mode
#bindkey -A viins main
#set -o emacs

# Load Modules
autoload -U colors; colors
autoload -U compinit; compinit
autoload -U promptinit; promptinit

zmodload zsh/complist
zmodload zsh/termcap

#autoload -U zargs
#autoload -U zmv
#autoload -U zed
#autoload -U zcalc
#autoload -U zftp

if [[ ${ZSH_VERSION//\./} -ge 420 ]] ; then
    autoload -U url-quote-magic
    zle -N self-insert url-quote-magic
fi

# Disable core dumps
limit coredumpsize 0

# Configure ZSH History
setopt HIST_REDUCE_BLANKS
setopt HIST_IGNORE_DUPS
setopt HIST_IGNORE_SPACE
setopt INC_APPEND_HISTORY
setopt SHARE_HISTORY
setopt BANG_HIST
HISTFILE=${HOME}/.zsh_history
SAVEHIST=1000
HISTSIZE=1600

# Terminal Options
setopt AUTO_CD		   # implicate cd for non-commands
setopt CD_ABLE_VARS	   # read vars in cd
setopt CORRECT 		   # correct spelling
setopt COMPLETE_IN_WORD	   # complete commands anywhere in the word
setopt NOTIFY              # Notify when jobs finish
setopt C_BASES             # 0xFF
setopt BASH_AUTO_LIST      # Autolist options on repeition of ambiguous args
setopt CHASE_LINKS         # Follow links in cds
setopt AUTO_PUSHD          # Push dirs into history
setopt ALWAYS_TO_END       # Move to the end on complete completion
setopt LIST_ROWS_FIRST     # Row orientation for menu
setopt MULTIOS             # Allow Multiple pipes
setopt MAGIC_EQUAL_SUBST   # Expand inside equals
setopt EXTENDED_GLOB

# We are lazy -- look up spaces too
bindkey ' ' magic-space

# Menu!!
zstyle ':completion:*' menu select=1

# Colors on completion me-ow
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#)*=0=01;31'

# Completion caching
zstyle ':completion::complete:*' use-cache on
zstyle ':completion::complete:*' cache-path ~/.zsh/cache/$HOST

# Completion Options
zstyle ':completion:*:match:*' original only
zstyle ':completion::prefix-1:*' completer _complete
zstyle ':completion:predict:*' completer _complete
zstyle ':completion:incremental:*' completer _complete _correct
zstyle ':completion:*' completer _complete _prefix _correct _prefix _match _approximate

# Ignore completions for commands that we dont have
zstyle ':completion:*:functions' ignored-patterns '_*'

# Dont complete backups as executables
zstyle ':completion:*:complete:-command-::commands' ignored-patterns '*\~'

# Path Expansion
zstyle ':completion:*' expand 'yes'
zstyle ':completion:*' squeeze-shlashes 'yes'
zstyle ':completion::complete:*' '\\'

# Allow forced showing'
zstyle '*' single-ignored show

# Case insensitivity, partial matching, substitution
zstyle ':completion:*' matcher-list 'm:{A-Z}={a-z}' 'm:{a-z}={A-Z}' 'r:|[._-]=** r:|=**' 'l:|=* r:|=*'

# Group matches and Describe
zstyle ':completion:*:matches' group 'yes'
zstyle ':completion:*:options' description 'yes'
zstyle ':completion:*:options' auto-description '%d'
zstyle ':completion:*:descriptions' format $'\e[01;33m -- %d --\e[0m'
zstyle ':completion:*:messages' format $'\e[01;35m -- %d --\e[0m'
zstyle ':completion:*:warnings' format $'\e[01;31m -- No Matches Found --\e[0m'

# Prevent re-suggestion
zstyle ':completion:*:rm:*' ignore-line yes
zstyle ':completion:*:scp:*' ignore-line yes
zstyle ':completion:*:ls:*' ignore-line yes

# Menu for KILL
zstyle ':completion:*:*:kill:*' menu yes select
zstyle ':completion:*:kill:*' force-list always

# Kill Menu Extension!
zstyle ':completion:*:processes' command 'ps -U $(whoami) | sed "/ps/d"'
zstyle ':completion:*:processes' insert-ids menu yes select 

# Remove uninteresting users
zstyle ':completion:*:*:*:users' ignored-patterns \
    adm alias apache at bin cron cyrus daemon ftp games gdm guest \
    haldaemon halt mail man messagebus mysql named news nobody nut \
    lp operator portage postfix postgres postmaster qmaild qmaill \
    qmailp qmailq qmailr qmails shutdown smmsp squid sshd sync \
    uucp vpopmail xfs

# Remove uninteresting hosts
zstyle ':completion:*:*:*:hosts-host' ignored-patterns \
    '*.*' loopback localhost
zstyle ':completion:*:*:*:hosts-domain' ignored-patterns \
    '<->.<->.<->.<->' '^*.*' '*@*'
zstyle ':completion:*:*:*:hosts-ipaddr' ignored-patterns \
    '^<->.<->.<->.<->' '127.0.0.<->'
zstyle -e ':completion:*:(ssh|scp):*' hosts 'reply=(
   ${=${${(f)"$(cat {/etc/ssh_,~/.ssh/known_}hosts(|2)(N) \
   /dev/null)"}%%[# ]*}//,/ }
   )'

# SSH Completion
zstyle ':completion:*:scp:*' tag-order \
    files users 'hosts:-host hosts:-domain:domain hosts:-ipaddr"IP\ Address *'
zstyle ':completion:*:scp:*' group-order \
    files all-files users hosts-domain hosts-host hosts-ipaddr
zstyle ':completion:*:ssh:*' tag-order \
    users 'hosts:-host hosts:-domain:domain hosts:-ipaddr"IP\ Address *'
zstyle ':completion:*:ssh:*' group-order \
    hosts-domain hosts-host users hosts-ipaddr

# Make Completion
compile=(all clean compile disclean install remove uninstall)
compctl -k compile make

# Command File Type Detection
compctl -g '*.ebuild' ebuild
compctl -g '*.tex' + -g '*(-/)' latex
compctl -g '*.dvi' + -g '*(-/)' dvipdf dvipdfm
compctl -g '*.java' + -g '*(-/)' javac
compctl -g '*.tar.bz2 *.tar.gz *.bz2 *.gz *.jar *.rar *.tar *.tbz2 *.tgz *.zip *.Z' + -g '*(-/)' extract
compctl -g '*.mp3 *.ogg *.mod *.wav *.avi *.mpg *.mpeg *.wmv' + -g '*(-/)' mplayer
compctl -g '*.py' python
compctl -g '*(-/D)' cd
compctl -g '*(-/)' mkdir

# Command Parameter Completion
compctl -z fg
compctl -j kill
compctl -j disown
compctl -u chown
compctl -u su
compctl -c sudo
compctl -c which
compctl -c type
compctl -c hash
compctl -c unhash
compctl -o setopt
compctl -o unsetopt
compctl -a alias
compctl -a unalias
compctl -A shift
compctl -v export
compctl -v unset
compctl -v echo
compctl -b bindkey

# Handle logouts
trap exit_handler 0

function exit_handler() {
   # If we have a symlink to Xdefaults .. destroy it
    if [[ -h $HOME/.Xdefaults-$(uname -n) ]] ; then
	rm -f "$HOME/.Xdefaults-$(uname -n)"
    fi
    
    clear
}

# Welcome message for login shells
if [[ $SHLVL -eq 3 ]] ; then
    echo
    print -P "\e[1;32m Welcome to: \e[1;34m%m"
    print -P "\e[1;32m Running: \e[1;34m`uname -srm`\e[1;32m on \e[1;34m%l"
    print -P "\e[1;32m It is:\e[1;34m %D{%r} \e[1;32m on \e[1;34m%D{%A %b %f %G}"
    echo
fi

# Custom commands
glob_scp() {
    emulate -L zsh
    local -a args
    local a
    for a
    do
	if [[ $a = *:* ]]
	then
            args+=($a)# args+=($a) if you have zsh 4.2+
	else
            args+=($~a)# args+=($~a)
	fi
    done
    scp $args
}
alias scp='noglob glob_scp'

extract() {
   if [[ -z "$1" ]] ; then
       print -P "usage: \e[1;36mextract\e[1;0m < filename >"
       print -P "       Extract the file specified based on the extension"
   elif [[ -f $1 ]] ; then
       case ${(L)1} in
           *.tar.bz2)  tar -jxvf $1	;;
           *.tar.gz)   tar -zxvf $1	;;
           *.bz2)      bunzip2 $1	   ;;
           *.gz)       gunzip $1	   ;;
           *.jar)      unzip $1       ;;
           *.rar)      unrar x $1	   ;;
           *.tar)      tar -xvf $1	   ;;
           *.tbz2)     tar -jxvf $1	;;
           *.tgz)      tar -zxvf $1	;;
           *.zip)      unzip $1	      ;;
           *.Z)        uncompress $1	;;
           *)          echo "Unable to extract '$1' :: Unknown extension"
       esac
   else
       echo "File ('$1') does not exist!"
   fi
}

basiccalc() {
    if [[ ! -f /usr/bin/bc ]] ; then
	echo "Please install bc before trying to use it!"
	return
    fi
    
   if [[ -z "$1" ]] ; then
       /usr/bin/bc -q
   else
       echo "$@" | /usr/bin/bc -l
   fi
}

alias bc=basiccalc

echon() {
   # Convert to normal 0th element access
    local loc=$1
    shift
    
    echo $@[(w)$loc]
}

mkcd() {
    if [[ -z "$1" ]] ; then
	echo "usage: \e[1;36mmkcd \e[1;0m< directory >"
	echo "       Creates the specified directory and then changes it to pwd"
    else
	if [[ ! -d $1 ]] ; then
            mkdir -p $1 && cd $1
	else
            cd $1
	fi
    fi
}

unkey_host() {
    if [[ -z "$1" ]] ; then
	echo "usage: \e[1;36munkey_host \e[1;0m< host >"
	echo "       Removes the specified host from ssh known host list"
    else
	sed -i -e "/$1/d" $HOME/.ssh/known_hosts
   fi
}


function precmd {
    
    local TERMWIDTH
    (( TERMWIDTH = ${COLUMNS} - 1 ))

    
    ###
    # Truncate the path if it's too long.
    
    PR_FILLBAR=""
    PR_PWDLEN=""
    
    local promptsize=${#${(%):---(%n@%m:%l)---()--}}
    local pwdsize=${#${(%):-%~}}
    
    if [[ "$promptsize + $pwdsize" -gt $TERMWIDTH ]]; then
	((PR_PWDLEN=$TERMWIDTH - $promptsize))
    else
	PR_FILLBAR="\${(l.(($TERMWIDTH - ($promptsize + $pwdsize)))..${PR_HBAR}.)}"
    fi
    
    
    ###
    # Get APM info.
    
    #if which ibam > /dev/null; then
	#PR_APM_RESULT=`ibam --percentbattery`
    #elif which apm > /dev/null; then
	#PR_APM_RESULT=`apm`
    #fi
}


setopt extended_glob
preexec () {
    if [[ "$TERM" == "screen" ]]; then
	local CMD=${1[(wr)^(*=*|sudo|-*)]}
	echo -n "\ek$CMD\e\\"
    fi
}


setprompt () {
    ###
    # Need this so the prompt will work.

    setopt prompt_subst
    

    ###
    # See if we can use colors.

    autoload colors zsh/terminfo
    if [[ "$terminfo[colors]" -ge 8 ]]; then
	colors
    fi
    for color in RED GREEN YELLOW BLUE MAGENTA CYAN WHITE; do
	eval PR_$color='%{$terminfo[bold]$fg[${(L)color}]%}'
	eval PR_LIGHT_$color='%{$fg[${(L)color}]%}'
	(( count = $count + 1 ))
    done
    PR_NO_COLOUR="%{$terminfo[sgr0]%}"
    
    
    ###
    # See if we can use extended characters to look nicer.
    
    typeset -A altchar
    set -A altchar ${(s..)terminfo[acsc]}
    PR_SET_CHARSET="%{$terminfo[enacs]%}"
    PR_SHIFT_IN="%{$terminfo[smacs]%}"
    PR_SHIFT_OUT="%{$terminfo[rmacs]%}"
    PR_HBAR=${altchar[q]:--}
    PR_ULCORNER=${altchar[l]:--}
    PR_LLCORNER=${altchar[m]:--}
    PR_LRCORNER=${altchar[j]:--}
    PR_URCORNER=${altchar[k]:--}
    
    
    ###
    # Decide if we need to set titlebar text.
    
    case $TERM in
	xterm*)
	    PR_TITLEBAR=$'%{\e]0;%(!.-=*[ROOT]*=- | .)%n@%m:%~ | ${COLUMNS}x${LINES} | %y\a%}'
	    ;;
	screen)
	    PR_TITLEBAR=$'%{\e_screen \005 (\005t) | %(!.-=[ROOT]=- | .)%n@%m:%~ | ${COLUMNS}x${LINES} | %y\e\\%}'
	    ;;
	*)
	    PR_TITLEBAR=''
	    ;;
    esac
    
    
    ###
    # Decide whether to set a screen title
    if [[ "$TERM" == "screen" ]]; then
	PR_STITLE=$'%{\ekzsh\e\\%}'
    else
	PR_STITLE=''
    fi
    
    
    ###
    # APM detection
    
    #if which ibam > /dev/null; then
	#PR_APM='$PR_RED${${PR_APM_RESULT[(f)1]}[(w)-2]}%%(${${PR_APM_RESULT[(f)3]}[(w)-1]})$PR_LIGHT_BLUE:'
    #elif which apm > /dev/null; then
	#PR_APM='$PR_RED${PR_APM_RESULT[(w)5,(w)6]/\% /%%}$PR_LIGHT_BLUE:'
    #else
    PR_APM=''
    #fi
    
    
    ###
    # Finally, the prompt.
    
    PROMPT='$PR_SET_CHARSET$PR_STITLE${(e)PR_TITLEBAR}\
$PR_CYAN$PR_SHIFT_IN$PR_ULCORNER$PR_BLUE$PR_HBAR$PR_SHIFT_OUT(\
$PR_GREEN%(!.%SROOT%s.%n)$PR_GREEN@%m:%l\
$PR_BLUE)$PR_SHIFT_IN$PR_HBAR$PR_CYAN$PR_HBAR${(e)PR_FILLBAR}$PR_BLUE$PR_HBAR$PR_SHIFT_OUT(\
$PR_MAGENTA%$PR_PWDLEN<...<%~%<<\
$PR_BLUE)$PR_SHIFT_IN$PR_HBAR$PR_CYAN$PR_URCORNER$PR_SHIFT_OUT\

$PR_CYAN$PR_SHIFT_IN$PR_LLCORNER$PR_BLUE$PR_HBAR$PR_SHIFT_OUT(\
%(?..$PR_LIGHT_RED%?$PR_BLUE:)\
${(e)PR_APM}$PR_YELLOW%D{%H:%M}\
$PR_LIGHT_BLUE:%(!.$PR_RED.$PR_WHITE)%#$PR_BLUE)$PR_SHIFT_IN$PR_HBAR$PR_SHIFT_OUT\
$PR_CYAN$PR_SHIFT_IN$PR_HBAR$PR_SHIFT_OUT\
$PR_NO_COLOUR '
    
    RPROMPT=' $PR_CYAN$PR_SHIFT_IN$PR_HBAR$PR_BLUE$PR_HBAR$PR_SHIFT_OUT\
($PR_YELLOW%D{%a,%b%d}$PR_BLUE)$PR_SHIFT_IN$PR_HBAR$PR_CYAN$PR_LRCORNER$PR_SHIFT_OUT$PR_NO_COLOUR'
    
    PS2='$PR_CYAN$PR_SHIFT_IN$PR_HBAR$PR_SHIFT_OUT\
$PR_BLUE$PR_SHIFT_IN$PR_HBAR$PR_SHIFT_OUT(\
$PR_LIGHT_GREEN%_$PR_BLUE)$PR_SHIFT_IN$PR_HBAR$PR_SHIFT_OUT\
$PR_CYAN$PR_SHIFT_IN$PR_HBAR$PR_SHIFT_OUT$PR_NO_COLOUR '
}

setprompt