You are not logged in.

#26 2009-09-15 01:37:48

Arm-the-Homeless
Member
Registered: 2008-12-22
Posts: 273

Re: Zsh(rc) Tips Thread

# Options for zsh
HISTFILE=~/.zsh_history
HISTSIZE=1000
SAVEHIST=1000
bindkey -v
zstyle :compinstall filename '/home/andy/.zshrc'
autoload -Uz compinit promptinit
setopt correctall
set -o noclobber
compinit
promptinit
fortune && echo
PROMPT=$'%{\e[0;34m%}%B┌─[%b%{\e[0m%}%{\e[1;32m%}%n%{\e[0m%} @ %{\e[0m%}%{\e[0;36m%}%B%m%{\e[0;34m%}%B]%b%{\e[0m%}-%{\e[0;34m%}%B[%b%{\e[0;34m%}'%B%*%b$'%{\e[0;34m%}%B]%b%{\e[0m%}
%{\e[0;34m%}%B└─[%b%{\e[0m%}%~%{\e[0;34m%}%B]%b%{\e[0;34m%}-%B[%{\e[1;35m%}$%{\e[0;34m%}%B]>%{\e[0m%}%b '

source ~/.shellrc

# The following lines were added by compinstall
zstyle ':completion:*' completer _complete _ignored
zstyle :compinstall filename '/home/andy/.zshrc'
# End of lines added by compinstall

I have `source ~/.shellrc` in there to keep some bash and zsh stuff in sync.
To be fair, here it is:

# Stuff 
export EDITOR='vim'
export BROWSER='firefox'
export MOZ_DISABLE_PANGO=1
export PAGER='vimpager'
eval `dircolors -b`
export GREP_COLOR="1;33"
alias grep='grep --color=auto'
source /etc/profile

# DevkitPPC stuff
export DEVKITPRO=/home/andy/devkitPro
export DEVKITPPC=$DEVKITPRO/devkitPPC
export DEVKITARM=$DEVKITPRO/devkitARM
export WIIDEV=$DEVKITPRO/wiidev
PATH=$PATH:$DEVKITPPC/bin:$DEVKITARM/bin:$WIIDEV/bin

# Aliases
alias ls='ls --color'
alias pacman='powerpill'
alias su="su -"

# For the really bullish processes
function murder(){
    while [[ $? = 0 ]]; do
        kill -9 $@
    done
}

# Extract archived files (maybe)
extract () {
    if [ -f $1 ]; then
            case $1 in
            *.tar.bz2)  tar -jxvf $1        ;;
            *.tar.gz)   tar -zxvf $1        ;;
            *.bz2)      bzip2 -d $1         ;;
            *.gz)       gunzip -d $1        ;;
            *.tar)      tar -xvf $1         ;;
            *.tgz)      tar -zxvf $1        ;;
            *.zip)      unzip $1            ;;
            *.Z)        uncompress $1       ;;
            *.rar)      unrar x $1            ;;
            *)          echo "'$1' Error. Please go away" ;;
            esac
            else
            echo "'$1' is not a valid file"
  fi
  }

I took the extract function from this thread.
Mostly because I thought the "Error. Please go away" was hilarious. tongue

Offline

#27 2009-09-15 02:26:44

leprosys
Member
From: El Salvador
Registered: 2009-02-23
Posts: 75
Website

Re: Zsh(rc) Tips Thread

My .zshrc lol

ZSHDIR=/etc/zsh/setups
export X11HOME=/usr/X11
export TEXHOME=/usr/share/texmf
 
. ${ZSHDIR}/zle
. ${ZSHDIR}/style
. ${ZSHDIR}/opts
. ${ZSHDIR}/aliases
. ${ZSHDIR}/prompt
 
for config_file in ${ZSHDIR}/functions/* ; do
   . ${config_file}
donet

The other files are here:
http://github.com/leprosys/thinkpad-t40 … r/etc/zsh/

Last edited by leprosys (2010-03-04 19:12:20)

Offline

#28 2009-09-17 03:39:42

YamiFrankc
Member
From: Mexico
Registered: 2009-06-19
Posts: 177
Website

Re: Zsh(rc) Tips Thread

I get

yami-laptop% zsh
/home/yamifrankc/.zshrc:19: parse error near `\n'

With that.
But,anywas i now have a good idea of what i want for prompt tongue.
Whats the code to make it be 2 lines? I remember seeing it somewhere but idk where hmm.

Last edited by YamiFrankc (2009-09-17 03:40:02)


Thanks and greetings.

Offline

#29 2009-09-23 04:23:12

YamiFrankc
Member
From: Mexico
Registered: 2009-06-19
Posts: 177
Website

Re: Zsh(rc) Tips Thread

YAY I got the prompt of my dreams smile.

I where messed up cause of codes like \n and colors dont working with PS1,but i changed to PROMPT and tahdah!

Just a one more question. Are the %B and %b codes bolders?

PROMPT=$'%B%{\e[0;36m%}┌─[%{\e[0;31m%}%n%{\e[0;36m%}]──(%{\e[0;33m%}%~%{\e[0;36m%})\n└─|%{\e[0;32m%} %# %{\e[0;36m%}>%b'

Nothing on it is bold


Thanks and greetings.

Offline

#30 2009-09-26 17:38:48

lymphatik
Member
From: Somewhere else
Registered: 2009-03-07
Posts: 119

Re: Zsh(rc) Tips Thread

Here is mine it is basically a compilation of different zsh script and a little research to fit my need

http://pastebin.com/fb6ef34c

Offline

#31 2009-09-27 20:27:48

crankyadmin
Member
Registered: 2009-09-27
Posts: 117
Website

Re: Zsh(rc) Tips Thread

# zsh options

HISTFILE=~/.histfile
HISTSIZE=2000
SAVEHIST=2000
PAGER=most

setopt correct
setopt extendedglob
setopt autopushd pushdminus pushdsilent pushdtohome
setopt no_clobber           # don't overwrite files when redirect
setopt share_history
setopt hist_verify          # verify when using !
setopt hist_ignore_space    # prepend ' ' to not be saved
setopt nohup               # don't kill bg jobs when tty quits
setopt nocheckjobs          # don't complain about background jobs on exit
setopt printexitvalue       # print exit value from jobs

unsetopt bgnice            # don't nice bg command

autoload -U compinit
compinit

#___________________________________________________________________________
# zsh zle key bindings

bindkey -e                      # emacs since vi just doesn't fit here :(

bindkey ' ' magic-space         # also do history expansion on space

bindkey '^z' undo               # C-x-u is overkill

bindkey ';5D' backward-word     # C-left
bindkey ';5C' forward-word      # C-right

# vi-ish bindings
bindkey '^w' kill-word
bindkey '^b' backward-kill-word

# fish/ipython-ish bindings
bindkey '\e[A' history-beginning-search-backward    # up arrow
bindkey '\e[B' history-beginning-search-forward     # down arrow

#___________________________________________________________________________
# alias

# zsh global aliases
alias -g H='--help'
alias -g L='| less'
alias -g M='| most'
alias -g G='| grep'
alias -g GC='| grep -C 2'

# zsh suffix aliases
alias -s conf=vim
alias -s cnf=vim
alias -s com=links
alias -s org=links
#Some more useful stuff
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
alias .....='cd ../../../..'

alias ls='ls -G'
alias ll='ls -lh'
alias la='ls -A'
alias lal='ls -Alh'

alias dirs='dirs -v'                    # zsh dir stack
alias T='tail -f'

alias hist='history | grep'             # take an argument

alias cp='cp -iv'
alias mv='mv -iv'

alias du='du -h'
alias df='df -h'

alias pscpu='ps -eo pcpu,nice,stat,time,pid,cmd --sort=-pcpu,-time \
             | sed "/^ 0.0 /d"'
alias psmem='ps -eo rss,vsz,pid,cmd --sort=-rss,-vsz \
             | awk "{ if (\$1 > 10000) print }"'

alias rcconf='sudo vim /etc/rc.conf'
alias zshrc='vim ~/.zshrc && source ~/.zshrc'
alias updatesys='sudo pacman -Syu'
alias homewireless='sudo netcfg -u wireless-open'
alias vi='vim'
alias mtr='mtr -t'
alias flashrom='sudo flashrom'
alias pacman='sudo pacman'
alias cranky='ssh -l dave www.crankyadmin.net'
alias man='PM man'
alias x='startx'
alias hidemouse='unclutter -root -idle 1 -jitter 200 &'
alias glinks='links -g'
alias panic='sudo shutdown -h now'
#___________________________________________________________________________
# generic functions

# do ls right after cd
cd () {
  if [ -n $1 ]; then
    builtin cd "$@" && ls
  else
    builtin cd ~ && ls
  fi
}

# list files only
lf () { ls -1p $@ | grep -v '\/$' }

# grep process by name and list the results nicely
pg () {
    if pgrep -f $@ > /dev/null;
    then
        pgrep -f $@ | xargs ps -o user,pid,stat,rss,vsz,pcpu,args \
                               --sort -pcpu,-rss;
    else 
        exit 1;
    fi
}

# compile lilypond file and view pdf
ly () { lilypond $@ && evince $(basename $1 .ly).pdf; }

# look in WordNet and Webster
d () { curl dict://dict.org/d:${1}:wn; }
wd () { curl dict://dict.org/d:${1}:web1913; } 

# find matches of $1, with optional strat $2 and optional db $3
ref () 
{
    if [[ -z $3 ]]; then
        curl dict://dict.org/m:${1}:english:${2};
    else
        curl dict://dict.org/m:${1}:${3}:${2};
    fi
}

# define $1 using optional db of $2
def () { curl dict://dict.org/d:${1}:${2} }

# local WordNet lookups
syn () { wn $1 -synsn; wn $1 -synsv; wn $1 -synsa; wn $1 -synsr; }
ant () { wn $1 -antsn; wn $1 -antsv; wn $1 -antsa; wn $1 -antsr; }

# Set a pretty zsh prompt, taking 0..5 args as colors
setprompt ()
{
    # load this to use $fg
    autoload -U colors
    colors
    c1="%{${1:-"$fg[green]"}%}"             # main color for cmd, cwd, hist
    c2="%{${2:-"$fg_no_bold[cyan]"}%}"      # color for user@host
    c3="%{${3:-"$fg_bold[white]"}%}"         # color for =,()
    c4="%{${4:-"$fg[white]"}%}"             # time and arrow color
    c5="%{${5:-"$fg[red]"}%}"               # root color
    CPUSPEED=`cat /proc/cpuinfo | awk '/MHz/ {print $4}' | grep -E -m 1 -o "^[[:digit:]]{3,4}"`
    now="$c3($c4%D{%H:%M} %D{%a %b %d}$c3)"
    userhost="%(!.$c5.$c2)%n$c3@$c2%m"

    line2="$userhost ${c3}[$c1%h$c3] ${c4}--> %(!.$c5.$c1)"
    newline=$'\n%{\r%}'

    # truncate and pad line1 appropiately
    precmd () {
        local cwdrealwidth=${#${(%):-%~}}
        
        # length of $line1 w/o $cwd = 22
        if [[ "$cwdrealwidth + 22" -gt $COLUMNS ]]; 
        then
            # truncate
            local cwdwidth = (( $COLUMNS - 22 ))
        else
            # pad
            local padding="${(l.(($COLUMNS - 22 - $cwdrealwidth )))..-.)}"
        fi
        
        local cwd="$c1%$cwdwidth<...<%~%<<"
        local line1="$c3-($cwd$c3)-${padding}$now"
        export PROMPT="${line1}$newline$line2"
    }
       
    preexec () { print -n "$reset_color" }
}
extract () {
       if [ -f $1 ] ; then
            case $1 in
                *.tar.bz2)   tar xvjf $1    ;;
                *.tar.gz)    tar xvzf $1    ;;
                *.bz2)       bunzip2 $1     ;;
                *.rar)       unrar x $1     ;;
                *.gz)        gunzip $1      ;;
                *.tar)       tar xvf $1     ;;
                *.tbz2)      tar xvjf $1    ;;
                *.tgz)       tar xvzf $1    ;;
                *.zip)       unzip $1       ;;
                *.Z)         uncompress $1  ;;
                *.7z)        7z x $1        ;;
                *)           echo "don't know how to extract '$1'..." ;;
            esac
                                                                                    else
           echo "'$1' is not a valid file!"
fi
}

#___________________________________________________________________________
# env

export EDITOR=vi
export LS_COLORS='di=92:ex=33'
export GREP_OPTIONS='--color=auto'

# e.g. do 'PM man $@' to read colorized man pages
alias PM='PAGER=most' 

safecolors () 
{
    setprompt $fg[green] $fg[blue] $fg[white]
    export LS_COLORS='di=32:ex=35'
}

#___________________________________________________________________________
# execute
PATH=$PATH:$HOME/bin/:/usr/local/bin/:/opt/local/bin/
uptime
echo ${(l.77..-.)}
setprompt

I love zsh


:: Github :: My AUR :: Coreboot ::

Offline

#32 2010-02-18 10:18:31

MindTooth
Member
From: Norway
Registered: 2008-11-11
Posts: 331

Re: Zsh(rc) Tips Thread

A really nice collection. Much appreciated to everyone that shar theirs wink

Offline

#33 2010-03-01 18:14:59

jhvid
Member
From: /dev/denmark
Registered: 2009-08-19
Posts: 52

Re: Zsh(rc) Tips Thread

Nice thread... DONT LET IT DIE!! wink
Anyway, here's my .zshrc smile:

#
# ~/.zshrc
# Written by Jonas Hvid using the archlinux forum and -wiki.
# Last Edited: 01/03/2010
#

# {{{ OPTIONS & AUTOLOADS
autoload colors; colors
setopt prompt_subst
setopt share_history
# }}}

# {{{ VARIABLES
export DATA_DIR="/home/jonas-data"
export SCRIPT_DIR="$DATA_DIR/code"
export SCRIPT_BIN="$SCRIPT_DIR/execs"
export SCRIPT_LIB="$SCRIPT_DIR/lib"
export PATH="$PATH:$SCRIPT_BIN"
export RUBYLIB="$SCRIPT_LIB/ruby"
export BROWSER="chromium"
#export FONT="inconsolata"
export FONT="terminus"
export LS_COLORS="fi=00;34:di=01;31:ln=01;32"
export PAGER="less"
# }}}

# {{{ FUNCTIONS
function precmd {
  exit_status=$?
  prompt=""

  if [ $exit_status = 0 ]; then
    col="$fg[green]"
    col2="$fg[blue]"
    prompt+="$col:)"
    b_prompt='>>> '
  else
    col="$fg[red]"
    col2="$fg[purple]"
    prompt+="$col:("
    b_prompt=">>> "
  fi

  prompt+="  $col2%/"
  prompt+="  $col%T"
  prompt+="  $col2$USER"
  prompt+="  $col$exit_status"

  # TODO: make newline a '\n' or something...
  PROMPT="$prompt
$b_prompt%{$fg[white]%}"
}
function remind {
  (
    sleep $1
    echo "$2" | dzen2 -fg white -bg red -fn $FONT-20 -p
  ) & disown
}
# }}}

# {{{ ALIASES
# Aliases to automaticly give some options.
alias "ls"="ls --color=auto -F"
alias "grep"="grep --color=auto -i"
# Those make my life easyer.
alias "e"="exit"
alias "c"="clear"
alias "home"="cd $DATA_DIR"
# Some cd-up aliases.
alias ..="cd .."
alias ...="cd ../.."
alias ....="cd ../../.."
alias .....="cd ../../../.."
# }}}

# {{{ MICS
HISTFILE="~/.zshell.hist"
HISTSIZE=1000
SAVEHIST=1000
# }}}

# {{{ KEYBINDINGS
# Delete:
bindkey "^[[3~" delete-char
# Home:
bindkey "^[[7~" beginning-of-line
# End:
bindkey "^[[8~" end-of-line
# Up/Down:
bindkey '\e[A' history-beginning-search-backward
bindkey '\e[B' history-beginning-search-forward
# Others:
bindkey "^X" menu-complete
# }}}

# {{{ WELCOME
note print
echo 
cd $DATA_DIR
# }}}

GCS d- s-:+ a12 C++++ U++++ L+++ P--- E--- W+++ N+ o K- w--- O? M-- V? PS PE
Y- PGP? t? 5? X? R tv b+++ DI+ D- G++ e++ h! !r !y

Please ignore me... I'm pretty weird...

Offline

#34 2010-03-01 18:57:20

JohannesSM64
Member
From: Norway
Registered: 2009-10-11
Posts: 623
Website

Re: Zsh(rc) Tips Thread

Yeah, this thread mustn't die. I'll post the most interesting parts of my zshrc:

have() {for i in $@; type $i &>/dev/null || return 1}
mkf() {mkdir -p $1 && cd $1}
pathgrep() {find $(sed 's/:/ /g' <<<$PATH) | grep --color $1}
dstart() {for d in $@; sudo /etc/rc.d/$d start || return 1}
dstop() {for d in $@; sudo /etc/rc.d/$d stop || return 1}
drestart() {for d in $@; sudo /etc/rc.d/$d restart || return 1}
dedit() {sudo vim /etc/rc.d/$^@}
dshow() {ls /var/run/daemons}
pubip() {curl http://whatismyip.org/ 2>/dev/null} 
ipc() {pubip | xclip -i}
ripdvd() {handbrake -i /dev/dvd -o ~/${1:-result.mp4} -L -U -F -f mp4 -e x264 -b 4000 -B 192}

mvf()
{             
    if [[ -d $*[-1] ]]; then
        mv $* && cd $*[-1]
    elif [[ -d ${*[-1]%/*} ]]; then
        mv $* && cd ${*[-1]%/*}
    fi
}
cpf()
{             
    if [[ -d $*[-1] ]]; then
        cp $* && cd $*[-1]
    elif [[ -d ${*[-1]%/*} ]]; then
        cp $* && cd ${*[-1]%/*}
    fi
}
md5name()
{
    if [[ -z $* ]]; then
        echo "$0: Provide at least one input file, you lemonade head."
    else
        for i in $@; do
            mv $i ${$(md5sum $i)[1]}.${i##*.}
        done
    fi
}
fiximageexts()
{
    zmv '(*).(#i)(jpeg|jpg)' '$1.jpg'
    zmv '(*).(#i)(gif)' '$1.gif'
    zmv '(*).(#i)(png)' '$1.png'
    zmv '(*).(#i)(bmp)' '$1.bmp'
}
pyserv()
{
    echo "http://$(pubip):8000" | xclip -i
    python -m SimpleHTTPServer
}
pacnews()
{
    for n in /etc/**/*.pacnew; do 
        if [[ -r ${n%.*} ]]; then 
            sudo vimdiff $n ${n%.*} &&
            echo "Replace?"; read -q && sudo mv $n ${n%.*}
        fi 
    done
}
mpdload() 
{
    local _FILE="$HOME/Collection/Music/`mpc --format %file%|head -n1`" 
    cp $_FILE /tmp
    ompload "/tmp/`basename $_FILE`"
}

if have packer; then
    alias y=packer
elif have yaourt; then
    alias y=yaourt
fi
alias bgx='unsetopt bgnice; x &! exit'
alias z=zcalc
have mplayer && alias -g HW10='-ao alsa:device=hw=1.0'

# sudo
alias sudo='sudo '
alias -- +=sudo
alias sv='+ vim'
if have pacman-color; then 
    alias sp='+ pacman-color'
elif have pacman; then
    alias sp='+ pacman'
fi
alias smic='make && + make install && make clean'
alias smuc='+ make uninstall && make clean'

zle -C ft-complete-tilde expand-or-complete _generic

ft-complete() 
{
    setopt extendedglob localoptions 
    local action context widget word

    if [[ -z ${BUFFER} ]]; then
        context=empty
        zstyle -s ":zle:ft-complete:${context}" action action || action=empty
        zstyle -s ":zle:ft-complete:${context}" widget widget || widget=expand-or-complete
        case ${action} in
            dot-slash-complete)
                BUFFER='./'
                CURSOR=2
                zle ${widget} -w
                ;;
            empty)
                ;;
            *)
                zle ${widget} -w
                ;;
        esac

        return 0
    fi

    word=${LBUFFER##* }
    if [[ ${word} == \~* ]] ; then
        context=tilde
        zstyle -s ":zle:ft-complete:${context}" widget widget || widget=expand-or-complete
        zle ${widget} -w
        return 0
    fi
    context=default
    zstyle -s ":zle:ft-complete:${context}" widget widget || widget=expand-or-complete
    zle ${widget} -w
    return 0
}
zle -N ft-complete
bindkey '^i' ft-complete

autoload -Uz compinit zmv zcalc
compinit
zstyle ':completion:*' group-name ''
zstyle ':completion:*:functions' ignored-patterns '_*'
zstyle ':completion:*:descriptions' format '%U%B%d%b%u'
zstyle ':completion:*:warnings' format '%U%Bno matches: %d%b%u'
zstyle ':completion:*:*:kill:*' menu yes select
zstyle ':completion:*:*:kill:*:processes' command 'ps xw -o pid,tty,time,args'
zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#)*=0=01;31'
zstyle ':completion:*:kill:*' force-list always
zstyle ':zle:ft-complete:empty' action dot-slash-complete
zstyle ':completion:ft-complete-tilde:*' completer _tilde _expand _complete _ignored _approximate
compdef _pacman pacman-color=pacman
setopt extendedglob interactivecomments histignorealldups correct completeinword noclobber

Last edited by JohannesSM64 (2010-03-01 18:59:27)

Offline

#35 2010-03-01 19:23:15

xenofungus
Member
From: Spain
Registered: 2009-10-17
Posts: 63

Re: Zsh(rc) Tips Thread

jhvid wrote:

alias "c"="clear"

Do you know about ctr+l?

Offline

#36 2010-04-23 21:37:18

demian
Member
From: Frankfurt, Germany
Registered: 2009-05-06
Posts: 709

Re: Zsh(rc) Tips Thread

I'm really glad i switched to ZSH, it's got a lot of very cool features.
I used the opportunity to skim through many .zshrc and .bashrc on dotfiles.org and these forums. So... my .zshrc got quite long roll.
Here it is: http://pastebin.com/dYSVkb1D
It took me almost a week to copy it all together, correct mistakes, make adjustments and add own parts. I hope it'll be useful to someone here who doesn't want to go through the same trouble.

Greets,
demian

Last edited by demian (2010-04-23 21:44:06)


no place like /home
github

Offline

#37 2010-04-23 22:33:26

bobdob
Member
Registered: 2008-06-13
Posts: 138

Re: Zsh(rc) Tips Thread

xenofungus wrote:
jhvid wrote:

alias "c"="clear"

Do you know about ctr+l?

Only just saw this. Awesome, should save me sometime.

Offline

#38 2010-04-24 11:15:16

JohannesSM64
Member
From: Norway
Registered: 2009-10-11
Posts: 623
Website

Re: Zsh(rc) Tips Thread

demian wrote:

I'm really glad i switched to ZSH, it's got a lot of very cool features.
I used the opportunity to skim through many .zshrc and .bashrc on dotfiles.org and these forums. So... my .zshrc got quite long roll.
Here it is: http://pastebin.com/dYSVkb1D
It took me almost a week to copy it all together, correct mistakes, make adjustments and add own parts. I hope it'll be useful to someone here who doesn't want to go through the same trouble.

Greets,
demian

Awesome rc! I have a few suggestions, though:
- autoload more stuff. zmv, zargs, zcalc and colors are useful.
- Learn zle widgets, I just learned them and they've saved me heaps of time already. Here are some of mine:

integrate_ranger()
{
     ranger <$TTY
     cd "$(grep \^\' ~/.ranger/bookmarks | cut -b3-)"
     precmd
     zle redisplay
}
zle -N integrated-ranger integrate_ranger
bindkey '^F' integrated-ranger
insert_sudo()
{
    if [[ $BUFFER != "sudo "* ]]; then
        BUFFER="sudo $BUFFER"; CURSOR+=5
    fi
}
zle -N insert-sudo insert_sudo
bindkey '^[r' insert-sudo
insert_git()
{
    if [[ $BUFFER != "git "* ]]; then
        BUFFER="git $BUFFER"
    fi
    zle accept-line
}

- Here's a cleaner replacement for your cd():

setopt AUTO_PUSHD
cd () { builtin cd $@ && ls }

- And you have "reload a daemon" as your description for all your /etc/rc.d functions smile

Last edited by JohannesSM64 (2010-04-24 11:28:58)

Offline

#39 2010-04-25 03:28:05

demian
Member
From: Frankfurt, Germany
Registered: 2009-05-06
Posts: 709

Re: Zsh(rc) Tips Thread

Thanks for the suggestions. I've done a lot of work today on my .zshrc so here's the new file: http://pastebin.com/rYPEPZgp (older: http://pastebin.com/hqxNnyVe)

I guess i have to thank elasticdog, from whom i took the very cool ls aliases, and buttons (or phil!, or both), from whom i copied more or less the whole zstyle completions part (with a few adjustments). It's a great completion system.
I also added some more from this thread. I especially liked the pathgrep function. I've always needed that but never took the time to actually write it.

I spent most of the time though working on the following four functions. Maybe they're helpful to someone.

ac() { # compress a file or folder
    case "$1" in
           tar.bz2|.tar.bz2) tar cvjf "${2%%/}.tar.bz2" "${2%%/}/"  ;;
       tbz2|.tbz2)       tar cvjf "${2%%/}.tbz2" "${2%%/}/"     ;;
       tbz|.tbz)         tar cvjf "${2%%/}.tbz" "${2%%/}/"      ;;       
       tar.gz|.tar.gz)   tar cvzf "${2%%/}.tar.gz" "${2%%/}/"   ;;
       tgz|.tgz)         tar cvjf "${2%%/}.tgz" "${2%%/}/"      ;;
       tar|.tar)         tar cvf  "${2%%/}.tar" "${2%%/}/"        ;;
           rar|.rar)         rar a "${2}.rar" "$2"            ;;
       zip|.zip)         zip -9 "${2}.zip" "$2"            ;;
       7z|.7z)         7z a "${2}.7z" "$2"            ;;
       lzo|.lzo)         lzop -v "$2"                ;;   
       gz|.gz)         gzip -v "$2"                ;;
       bz2|.bz2)         bzip2 -v "$2"                ;;
       xz|.xz)         xz -v "$2"                    ;; 
       lzma|.lzma)         lzma -v "$2"                ;;  
           *)           echo "ac(): compress a file or directory."
            echo "Usage:   ac <archive type> <filename>"
                echo "Example: ac tar.bz2 PKGBUILD"
            echo "Please specify archive type and source."
            echo "Valid archive types are:"
            echo "tar.bz2, tar.gz, tar, bz2, gz, tbz2, tbz,"
            echo "tgz, lzo, rar, zip, 7z, xz and lzma." ;;
    esac
}
ad() { # decompress archive (to directory $2 if wished for and possible)
   if [ -f "$1" ] ; then
       case "$1" in
           *.tar.bz2|*.tgz|*.tbz2|*.tbz) mkdir -v "$2" 2>/dev/null ; tar xvjf "$1" -C "$2" ;;
       *.tar.gz)             mkdir -v "$2" 2>/dev/null ; tar xvzf "$1" -C "$2" ;;
       *.tar)             mkdir -v "$2" 2>/dev/null ; tar xvf "$1"  -C "$2" ;;
           *.rar)             mkdir -v "$2" 2>/dev/null ; rar x   "$1"     "$2" ;;
       *.zip)             mkdir -v "$2" 2>/dev/null ; unzip   "$1"  -d "$2" ;;
       *.7z)             mkdir -v "$2" 2>/dev/null ; 7z x    "$1"   -o"$2" ;;
       *.lzo)             mkdir -v "$2" 2>/dev/null ; lzop -d "$1"   -p"$2" ;;  
       *.gz)             gunzip "$1"                       ;;
       *.bz2)             bunzip2 "$1"                       ;;
           *.Z)                 uncompress "$1"                       ;;
       *.xz|*.txz|*.lzma|*.tlz)     xz -d "$1"                           ;; 
       *)               
       esac
   else
                      echo "Sorry, '$2' could not be decompressed."
              echo "Usage: ad <archive> <destination>"
              echo "Example: ad PKGBUILD.tar.bz2 ."
              echo "Valid archive types are:"
              echo "tar.bz2, tar.gz, tar, bz2,"
              echo "gz, tbz2, tbz, tgz, lzo,"
              echo "rar, zip, 7z, xz and lzma"
   fi
}
al() { # list content of archive but don't unpack
    if [ -f "$1" ]; then
         case "$1" in
       *.tar.bz2|*.tbz2|*.tbz) tar -jtf "$1"     ;;
       *.tar.gz)                     tar -ztf "$1"     ;;
       *.tar|*.tgz)                 tar -tf "$1"     ;;
       *.gz)                 gzip -l "$1"     ;;    
       *.rar)                 rar vb "$1"     ;;
       *.zip)                 unzip -l "$1"     ;;
       *.7z)                 7z l "$1"     ;;
       *.lzo)                 lzop -l "$1"     ;;  
       *.xz|*.txz|*.lzma|*.tlz)      xz -l "$1"     ;;
         esac
    else
         echo "Sorry, '$1' is not a valid archive."
     echo "Valid archive types are:"
     echo "tar.bz2, tar.gz, tar, gz,"
     echo "tbz2, tbz, tgz, lzo, rar"
     echo "zip, 7z, xz and lzma"
    fi
}

And although i don't plan on reinstalling anytime soon i completed my setup function:

  setup() { # run as root on a fresh system to install base and gui packages and create user
    echo -n "Is your network up and running? (y/n) "
    read answer
    case "$answer" in
    yes|y|'') echo "Good. Proceeding."
    ;;
    no|n)      echo "You'll need internet access."
              echo "Please configure your network before calling this script again."
          echo "Exiting now."
          return 0
    ;;
    esac
    echo -n "Did you configure pacman.conf to include [archlinuxfr]? "
    read answer
    case "$answer" in
    yes|y|'') echo "Good. Proceeding."
    ;;
    no|n) echo "Don't worry. I'll do it for you."
         echo " " >> /etc/pacman.conf
         echo "[archlinuxfr]" >> /etc/pacman.conf
         if [[ `uname --machine` = i686 ]];then
           echo "Server = http://repo.archlinux.fr/i686" >> /etc/pacman.conf
           echo "Your pacman.conf is now updated to include the 32bit repository of archlinuxfr."
         elif [[ `uname --machine` = x86_64 ]];then
           echo "Server = http://repo.archlinux.fr/x86_64" >> /etc/pacman.conf
           echo "Your pacman.conf is now updated to include the 64bit repository of archlinuxfr."
         else
           echo "Sorry, but i can't read the system architecture."
           echo "Please configure pacman.conf manually."
           echo "Exiting now."
           return 0
         fi 
    ;;
    esac
    echo -n "Are you using a fast and up-to-date mirror? "
    read answer
    case "$answer" in
    yes|y|'') echo "Good. Proceeding."
          echo -n "Did you sync the mirrorlist yet? "
          read answer
          case "$answer" in
            yes|y|'') echo "Good. Proceeding."
            ;;
            no|n)      echo "Okay. Let's do it now."
                  pacman -Syy
                  echo "Done. Proceeding with setup."
            ;;
          esac
    ;;
    no|n)     echo "NP. Doing it for you. I may need input though."
         echo "Checking if reflector is installed."
         if [[ `pacman -Qsl | grep reflector | wc -l` = 0 ]];then
         echo "Not installed. Downloading reflector."
         pacman -Sy reflector
         else
         echo "Good. Reflector is installed."
         fi
         echo "Updating your mirrorlist now."
         reflector -l 8 -r -o /etc/pacman.d/mirrorlist
         echo "Your mirrorlist should now be updated."
         echo "Proceeding."
    ;;
    esac
    echo -n "Download and install Base and GUI now? (base/both/none) "
    read answer
    case "$answer" in
        both)   echo "Both basic system and gui packages will now be installed and downloaded."
        echo "No input needed for the next ~30 minutes. Go do some work."
        pacman -S    alsa-utils acpid pm-utils cpufrequtils nfs-utils rpcbind rsync tree \
                     calc bc dosfstools ntfsprogs abs cups pmount samba openssh    ntfs-3g  \
                 ethtool lm_sensors stress reflector                 \
                 lzop unzip rar p7zip unrar zip xz-utils unace             \
                 zsh grc cowsay fortune-mod vim htop screen                 \
                             irssi wgetpaste scrot curl clamav powertop laptop-mode-tools slock     \
                 mpc moc imagemagick yaourt                         \
                 xorg xf86-input-evdev xf86-video-intel                 \
                 openbox openbox-themes obconf obmenu                 \
                 gamin transset-df gxmessage xdg-user-dirs xcompmgr             \
                 ttf-dejavu ttf-ms-fonts ttf-bitstream-vera                 \
                 terminal galculator gvim feh pcmanfm gmrun medit xarchiver epdfview \
                 mirage conky sonata gmpc firefox thunderbird flashplugin vlc
        echo "Delete libxft and cairo to replace them with lcd packages later on."
        pacman -Rd   libxft cairo             
        echo "Some more packages from the AUR."
        yaourt -S    fortune-mod-tbbt fortune-mod-montypython fortune-mod-himym         \
                 fortune-mod-chucknorris tupac zsh-tupac zsh-yaourt zsh-lovers     \
                 fontconfig-lcd cairo-lcd                         \
                 aurvote firebrand thunderbrand sir
        pacman -S    libxft-lcd
        ;;
        base)   echo "Only basic system packages will now be downloaded and installed."
        echo "Downloading basic packages"
        pacman -S    alsa-utils acpid pm-utils cpufrequtils nfs-utils rpcbind rsync tree \
                     calc bc dosfstools ntfsprogs abs cups pmount samba openssh    ntfs-3g  \
                 ethtool lm_sensors stress reflector                 \
                 lzop unzip rar p7zip unrar zip xz-utils unace             \
                 zsh grc cowsay fortune-mod vim htop screen                 \
                             irssi wgetpaste scrot curl clamav powertop laptop-mode-tools slock     \
                 mpc moc yaourt
        echo "Some fun stuff from the AUR."
        yaourt -Sy --aur fortune-mod-tbbt fortune-mod-montypython fortune-mod-himym     \
                     fortune-mod-chucknorris tupac zsh-tupac zsh-yaourt zsh-lovers
        ;;
    none)   echo "Skipping download and installation."
        ;;
    esac
    echo -n "Setup User now? "
    read answer
    case "$answer" in
    yes|y|'') echo "Preparing to create user."
        echo -n "Setup demian or slave? "
        read answer
        case "$answer" in
            demian|d|1) echo "Proceeding for demian."
                        echo "Creating user demian, his password and some directories."
                    useradd -m -G users,audio,lp,optical,storage,video,wheel,power -s /bin/zsh demian
                    echo "Please specify a password:"
                    passwd demian
                    echo "Creating directories in /media:"
                    mkdir -v /media/share /media/daten
                    echo "Downloading some last packages:"
                    yaourt -S tp_smapi phc-intel
                    echo "System is installed and ready to configure."
                    ;;
            slave|s|2)  echo "Proceeding for slave."
                    echo "Creating user slave, his password and some directories"
                    useradd -m -G users,audio,lp,optical,storage,video,wheel,power -s /bin/zsh slave
                    echo "Please specify a password:"
                    passwd slave
                    echo "Creating directories in /media:"
                    mkdir -v /media/movies /media/music /media/series /media/share /media/usbhdd
                    echo "Downloading some last packages:"
                    pacman -S lighttpd fcgi php php-cgi mpd rtorrent
                    yaourt -S phc-intel eaccelerator
                    echo "System is installed and ready to configure."
                    ;;
        esac
        ;;
    no|n) echo "Skipping user creation. Setup is done."
        ;;
    esac
  }

Still open for suggestions, of course smile.

Regards,
demian

Last edited by demian (2010-04-25 18:37:07)


no place like /home
github

Offline

#40 2010-04-25 12:10:46

JohannesSM64
Member
From: Norway
Registered: 2009-10-11
Posts: 623
Website

Re: Zsh(rc) Tips Thread

You can replace this:

read answer
case "$answer" in
yes|y|'') echo "Good. Proceeding."
;;
no|n) echo "Don't worry. I'll do it for you."
..

with:

if read -q; then
    echo "Good. Proceeding."
else
    echo "Don't worry. I'll do it for you."
    ..
fi

Offline

#41 2010-04-25 12:37:55

fgr
Member
From: Italy
Registered: 2009-02-12
Posts: 20

Re: Zsh(rc) Tips Thread

Here's my «.zshrc»:

# mostly taken from <http://grml.org/zsh/#grmlzshconfig>

#f1# are we running within an utf environment?
isutfenv() {
    case "$LANG $CHARSET $LANGUAGE" in
        *utf*) return 0 ;;
        *UTF*) return 0 ;;
        *)     return 1 ;;
    esac
}

# check for user, if not running as root set $SUDO to sudo
(( EUID != 0 )) && SUDO='sudo' || SUDO=''

# autoload wrapper - use this one instead of autoload directly
function zrcautoload() {
    emulate -L zsh
    setopt extended_glob
    local fdir ffile
    local -i ffound

    ffile=$1
    (( found = 0 ))
    for fdir in ${fpath} ; do
        [[ -e ${fdir}/${ffile} ]] && (( ffound = 1 ))
    done

    (( ffound == 0 )) && return 1
    if [[ $ZSH_VERSION == 3.1.<6-> || $ZSH_VERSION == <4->* ]] ; then
        autoload -U ${ffile} || return 1
    else
        autoload ${ffile} || return 1
    fi
    return 0
}

# Load is-at-least() for more precise version checks
# Note that this test will *always* fail, if the is-at-least
# function could not be marked for autoloading.
zrcautoload is-at-least || is-at-least() { return 1 }

## zshoptions(1)
setopt NO_BEEP
# Changing Directories
setopt AUTO_CD
setopt AUTO_PUSHD
setopt CDABLE_VARS
setopt PUSHD_MINUS
setopt PUSHD_SILENT
setopt PUSHD_TO_HOME
setopt NO_SH_WORD_SPLIT # use zsh style word splitting
# Completion
setopt HASH_LIST_ALL
setopt COMPLETE_IN_WORD # not just at the end
setopt ALWAYS_TO_END # when complete from middle, move cursor
# Expansion and Globbing
setopt EXTENDED_GLOB # weird & wacky pattern matching
#setopt GLOB_DOTS # find dotfiles easier
setopt NO_GLOB_DOTS # shouldn't match dotfiles. ever.
setopt NUMERIC_GLOB_SORT
setopt MARK_DIRS # adds slash to end of completed dirs
setopt NONOMATCH # try to avoid the 'zsh: no matches found...'
# History
setopt APPEND_HISTORY # append history list to the history file (important for multiple parallel zsh sessions!)
setopt NO_BANG_HIST
setopt HIST_IGNORE_SPACE
setopt HIST_IGNORE_ALL_DUPS
setopt HIST_IGNORE_DUPS
setopt PUSHD_IGNORE_DUPS
setopt HIST_SAVE_NO_DUPS
setopt HIST_REDUCE_BLANKS
setopt HIST_IGNORE_SPACE
setopt HIST_REDUCE_BLANKS
setopt INC_APPEND_HISTORY # append history as command are entered
setopt HIST_NO_STORE # don't save 'history' cmd in history
# Input/Output
setopt NO_CLOBBER
setopt CORRECT # spelling correction
setopt HASH_CMDS
setopt HASH_DIRS
setopt IGNORE_EOF
setopt INTERACTIVE_COMMENTS
#setopt PRINT_EXIT_VALUE
# Job Control
setopt LONG_LIST_JOBS # display PID when suspending processes as well
setopt NO_HUP
setopt NOTIFY
# Shell Emulation
setopt INTERACTIVE_COMMENTS

# setting some default values {{{

NOCOR=${NOCOR:-0}
NOMENU=${NOMENU:-0}
NOPRECMD=${NOPRECMD:-0}
COMMAND_NOT_FOUND=${COMMAND_NOT_FOUND:-0}
GRML_ZSH_CNF_HANDLER=${GRML_ZSH_CNF_HANDLER:-/usr/share/command-not-found/command-not-found}
BATTERY=${BATTERY:-0}

# }}}

# Start the GnuPG agent and enable OpenSSH agent emulation
# eval "$(killall gpg-agent; gpg-agent --enable-ssh-support --daemon)"
# export GPG_AGENT_INFO
# export SSH_AUTH_SOCK
# export SSH_AGENT_PID

# GPG_TTY=$(tty)
# export GPG_TTY

export OOO_FORCE_DESKTOP=gnome
export CVS_RSH=ssh
export PYTHONDOCS=/usr/share/doc/python/html/

export PATH=$PATH:$HOME/bin
export HISTFILE=~/.zsh_history
export HISTSIZE=10000
export SAVEHIST=10000
export EDITOR=nano
#export VISUAL="emacsclient -c --alternate-editor=nano"
#export ALTERNATE_EDITOR="emacs -Q"

#export LC_ALL=C

alias td='date "+%Y-%m-%d %H:%M %:z %A"'
alias em=emacsclient
alias emc='emacsclient -c'

export PAGER=${PAGER:-less}
export LESS=-R

# support colors in less
export LESS_TERMCAP_mb=$'\E[01;31m'
export LESS_TERMCAP_md=$'\E[01;31m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[01;44;33m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[01;32m'

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

# {{{ keybindings
if [[ "$TERM" != emacs ]] ; then
    [[ -z "$terminfo[kdch1]" ]] || bindkey -M emacs "$terminfo[kdch1]" delete-char
    [[ -z "$terminfo[khome]" ]] || bindkey -M emacs "$terminfo[khome]" beginning-of-line
    [[ -z "$terminfo[kend]"  ]] || bindkey -M emacs "$terminfo[kend]"  end-of-line
    [[ -z "$terminfo[kdch1]" ]] || bindkey -M vicmd "$terminfo[kdch1]" vi-delete-char
    [[ -z "$terminfo[khome]" ]] || bindkey -M vicmd "$terminfo[khome]" vi-beginning-of-line
    [[ -z "$terminfo[kend]"  ]] || bindkey -M vicmd "$terminfo[kend]"  vi-end-of-line
    [[ -z "$terminfo[cuu1]"  ]] || bindkey -M viins "$terminfo[cuu1]"  vi-up-line-or-history
    [[ -z "$terminfo[cuf1]"  ]] || bindkey -M viins "$terminfo[cuf1]"  vi-forward-char
    [[ -z "$terminfo[kcuu1]" ]] || bindkey -M viins "$terminfo[kcuu1]" vi-up-line-or-history
    [[ -z "$terminfo[kcud1]" ]] || bindkey -M viins "$terminfo[kcud1]" vi-down-line-or-history
    [[ -z "$terminfo[kcuf1]" ]] || bindkey -M viins "$terminfo[kcuf1]" vi-forward-char
    [[ -z "$terminfo[kcub1]" ]] || bindkey -M viins "$terminfo[kcub1]" vi-backward-char
    # ncurses stuff:
    [[ "$terminfo[kcuu1]" == $'\eO'* ]] && bindkey -M viins "${terminfo[kcuu1]/O/[}" vi-up-line-or-history
    [[ "$terminfo[kcud1]" == $'\eO'* ]] && bindkey -M viins "${terminfo[kcud1]/O/[}" vi-down-line-or-history
    [[ "$terminfo[kcuf1]" == $'\eO'* ]] && bindkey -M viins "${terminfo[kcuf1]/O/[}" vi-forward-char
    [[ "$terminfo[kcub1]" == $'\eO'* ]] && bindkey -M viins "${terminfo[kcub1]/O/[}" vi-backward-char
    [[ "$terminfo[khome]" == $'\eO'* ]] && bindkey -M viins "${terminfo[khome]/O/[}" beginning-of-line
    [[ "$terminfo[kend]"  == $'\eO'* ]] && bindkey -M viins "${terminfo[kend]/O/[}"  end-of-line
    [[ "$terminfo[khome]" == $'\eO'* ]] && bindkey -M emacs "${terminfo[khome]/O/[}" beginning-of-line
    [[ "$terminfo[kend]"  == $'\eO'* ]] && bindkey -M emacs "${terminfo[kend]/O/[}"  end-of-line
fi

# keybindings (run 'bindkeys' for details, more details via man zshzle)
# use emacs style per default:
bindkey -e
# use vi style:
# bindkey -v

#if [[ "$TERM" == screen ]] ; then
bindkey '\e[1~' beginning-of-line       # home
bindkey '\e[4~' end-of-line             # end
bindkey '\e[A'  up-line-or-search       # cursor up
bindkey '\e[B'  down-line-or-search     # <ESC>-

bindkey '^xp'   history-beginning-search-backward
bindkey '^xP'   history-beginning-search-forward
# bindkey -s '^L' "|less\n"             # ctrl-L pipes to less
# bindkey -s '^B' " &\n"                # ctrl-B runs it in the background
# if terminal type is set to 'rxvt':
bindkey '\e[7~' beginning-of-line       # home
bindkey '\e[8~' end-of-line             # end
#fi

# for rxvt
bindkey "\e[8~" end-of-line
bindkey "\e[7~" beginning-of-line
# for non RH/Debian xterm, can't hurt for RH/DEbian xterm
bindkey "\eOH" beginning-of-line
bindkey "\eOF" end-of-line
# for freebsd console
bindkey "\e[H" beginning-of-line
bindkey "\e[F" end-of-line

# completion in the middle of a line
bindkey '^i' expand-or-complete-prefix

# also do history expansion on space
bindkey ' ' magic-space
# Trigger menu-complete
bindkey '\ei' menu-complete # menu completion via esc-i

# insert unicode character
# usage example: 'ctrl-x i' 00A7 'ctrl-x i' will give you an §
# See for example http://unicode.org/charts/ for unicode characters code
zrcautoload insert-unicode-char
zle -N insert-unicode-char
#k# Insert Unicode character
bindkey '^Xi' insert-unicode-char

#m# k Shift-tab Perform backwards menu completion
if [[ -n "$terminfo[kcbt]" ]]; then
    bindkey "$terminfo[kcbt]" reverse-menu-complete
elif [[ -n "$terminfo[cbt]" ]]; then # required for GNU screen
    bindkey "$terminfo[cbt]"  reverse-menu-complete
fi

# only slash should be considered as a word separator:
slash-backward-kill-word() {
    local WORDCHARS="${WORDCHARS:s@/@}"
    # zle backward-word
    zle backward-kill-word
}
zle -N slash-backward-kill-word

#k# Kill everything in a word up to its last \kbd{/}
bindkey '\ev' slash-backward-kill-word

if [[ -n ${(k)modules[zsh/complist]} ]] ; then
    #k# menu selection: pick item but stay in the menu
    bindkey -M menuselect '\e^M' accept-and-menu-complete

    # accept a completion and try to complete again by using menu
    # completion; very useful with completing directories
    # by using 'undo' one's got a simple file browser
    bindkey -M menuselect '^o' accept-and-infer-next-history
fi

# }}}

eval $(dircolors -b)
# set colors for use in prompts
BLUE=$'%{\e[1;34m%}'
RED=$'%{\e[1;31m%}'
GREEN=$'%{\e[1;32m%}'
CYAN=$'%{\e[1;36m%}'
WHITE=$'%{\e[1;37m%}'
MAGENTA=$'%{\e[1;35m%}'
YELLOW=$'%{\e[1;33m%}'
NO_COLOUR=$'%{\e[0m%}'

# a generic accept-line wrapper {{{

# This widget can prevent unwanted autocorrections from command-name
# to _command-name, rehash automatically on enter and call any number
# of builtin and user-defined widgets in different contexts.
#
# For a broader description, see:
# <http://bewatermyfriend.org/posts/2007/12-26.11-50-38-tooltime.html>
#
# The code is imported from the file 'zsh/functions/accept-line' from
# <http://ft.bewatermyfriend.org/comp/zsh/zsh-dotfiles.tar.bz2>, which
# distributed under the same terms as zsh itself.

# A newly added command will may not be found or will cause false
# correction attempts, if you got auto-correction set. By setting the
# following style, we force accept-line() to rehash, if it cannot
# find the first word on the command line in the $command[] hash.
zstyle ':acceptline:*' rehash true

function Accept-Line() {
    emulate -L zsh
    local -a subs
    local -xi aldone
    local sub

    zstyle -a ":acceptline:${alcontext}" actions subs

    (( ${#subs} < 1 )) && return 0

    (( aldone = 0 ))
    for sub in ${subs} ; do
        [[ ${sub} == 'accept-line' ]] && sub='.accept-line'
        zle ${sub}

        (( aldone > 0 )) && break
    done
}

function Accept-Line-getdefault() {
    emulate -L zsh
    local default_action

    zstyle -s ":acceptline:${alcontext}" default_action default_action
    case ${default_action} in
        ((accept-line|))
            printf ".accept-line"
            ;;
        (*)
            printf ${default_action}
            ;;
    esac
}

function accept-line() {
    emulate -L zsh
    local -a cmdline
    local -x alcontext
    local buf com fname format msg default_action

    alcontext='default'
    buf="${BUFFER}"
    cmdline=(${(z)BUFFER})
    com="${cmdline[1]}"
    fname="_${com}"

    zstyle -t ":acceptline:${alcontext}" rehash \
        && [[ -z ${commands[$com]} ]]           \
        && rehash

    if    [[ -n ${reswords[(r)$com]} ]] \
       || [[ -n ${aliases[$com]}     ]] \
       || [[ -n ${functions[$com]}   ]] \
       || [[ -n ${builtins[$com]}    ]] \
       || [[ -n ${commands[$com]}    ]] ; then

        # there is something sensible to execute, just do it.
        alcontext='normal'
        zle Accept-Line

        default_action=$(Accept-Line-getdefault)
        zstyle -T ":acceptline:${alcontext}" call_default \
            && zle ${default_action}
        return
    fi

    if    [[ -o correct              ]] \
       || [[ -o correctall           ]] \
       && [[ -n ${functions[$fname]} ]] ; then

        # nothing there to execute but there is a function called
        # _command_name; a completion widget. Makes no sense to
        # call it on the commandline, but the correct{,all} options
        # will ask for it nevertheless, so warn the user.
        if [[ ${LASTWIDGET} == 'accept-line' ]] ; then
            # Okay, we warned the user before, he called us again,
            # so have it his way.
            alcontext='force'
            zle Accept-Line

            default_action=$(Accept-Line-getdefault)
            zstyle -T ":acceptline:${alcontext}" call_default \
                && zle ${default_action}
            return
        fi

        # prepare warning message for the user, configurable via zstyle.
        zstyle -s ":acceptline:${alcontext}" compwarnfmt msg

        if [[ -z ${msg} ]] ; then
            msg="%c will not execute and completion %f exists."
        fi

        zformat -f msg "${msg}" "c:${com}" "f:${fname}"

        zle -M -- "${msg}"
        return
    elif [[ -n ${buf//[$' \t\n']##/} ]] ; then
        # If we are here, the commandline contains something that is not
        # executable, which is neither subject to _command_name correction
        # and is not empty. might be a variable assignment
        alcontext='misc'
        zle Accept-Line

        default_action=$(Accept-Line-getdefault)
        zstyle -T ":acceptline:${alcontext}" call_default \
            && zle ${default_action}
        return
    fi

    # If we got this far, the commandline only contains whitespace, or is empty.
    alcontext='empty'
    zle Accept-Line

    default_action=$(Accept-Line-getdefault)
    zstyle -T ":acceptline:${alcontext}" call_default \
        && zle ${default_action}
}

zle -N accept-line
zle -N Accept-Line

# }}}

# dirstack handling {{{

DIRSTACKSIZE=${DIRSTACKSIZE:-20}
DIRSTACKFILE=${DIRSTACKFILE:-${HOME}/.zdirs}

if [[ -f ${DIRSTACKFILE} ]] && [[ ${#dirstack[*]} -eq 0 ]] ; then
    dirstack=( ${(f)"$(< $DIRSTACKFILE)"} )
    # "cd -" won't work after login by just setting $OLDPWD, so
    [[ -d $dirstack[0] ]] && cd $dirstack[0] && cd $OLDPWD
fi

chpwd() {
    local -ax my_stack
    my_stack=( ${PWD} ${dirstack} )
    #if is42 ; then
        builtin print -l ${(u)my_stack} >! ${DIRSTACKFILE}
    #else
    #    uprint my_stack >! ${DIRSTACKFILE}
    #fi
}

# }}}

# gather version control information for inclusion in a prompt {{{

# The following code is imported from the file 'zsh/functions/vcs_info'
# from <http://ft.bewatermyfriend.org/comp/zsh/zsh-dotfiles.tar.bz2>,
# which distributed under the same terms as zsh itself.

# we will be using two variables, so let the code know now
zstyle ':vcs_info:*' max-exports 2

# vcs_info() documentation:
#{{{
# REQUIREMENTS:
#{{{
#     This functionality requires zsh version >= 4.1.*.
#}}}
#
# LOADING:
#{{{
# To load vcs_info(), copy this file to your $fpath[] and do:
#   % autoload -Uz vcs_info && vcs_info
#
# To work, vcs_info() needs 'setopt prompt_subst' in your setup.
#}}}
#
# QUICKSTART:
#{{{
# To get vcs_info() working quickly (including colors), you can do the
# following (assuming, you loaded vcs_info() properly - see above):
#
# % RED=$'%{\e[31m%}'
# % GR=$'%{\e[32m%}'
# % MA=$'%{\e[35m%}'
# % YE=$'%{\e[33m%}'
# % NC=$'%{\e[0m%}'
#
# % zstyle ':vcs_info:*' actionformats \
#       "${MA}(${NC}%s${MA})${YE}-${MA}[${GR}%b${YE}|${RED}%a${MA}]${NC} "
#
# % zstyle ':vcs_info:*' formats       \
#       "${MA}(${NC}%s${MA})${Y}-${MA}[${GR}%b${MA}]${NC}%} "
#
# % zstyle ':vcs_info:(sv[nk]|bzr):*' branchformat "%b${RED}:${YE}%r"
#
# % precmd () { vcs_info }
# % PS1='${MA}[${GR}%n${MA}] ${MA}(${RED}%!${MA}) ${YE}%3~ ${VCS_INFO_message_0_}${NC}%# '
#
# Obviously, the las two lines are there for demonstration: You need to
# call vcs_info() from your precmd() function (see 'SPECIAL FUNCTIONS' in
# 'man zshmisc'). Once that is done you need a *single* quoted
# '${VCS_INFO_message_0_}' in your prompt.
#
# Now call the 'vcs_info_printsys' utility from the command line:
#
# % vcs_info_printsys
# # list of supported version control backends:
# # disabled systems are prefixed by a hash sign (#)
# git
# hg
# bzr
# darcs
# svk
# mtn
# svn
# cvs
# cdv
# tla
# # flavours (cannot be used in the disable style; they
# # are disabled with their master [git-svn -> git]):
# git-p4
# git-svn
#
# Ten version control backends as you can see. You may not want all
# of these. Because there is no point in running the code to detect
# systems you do not use. ever. So, there is a way to disable some
# backends altogether:
#
# % zstyle ':vcs_info:*' disable bzr cdv darcs mtn svk tla
#
# If you rerun 'vcs_info_printsys' now, you will see the backends listed
# in the 'disable' style marked as diabled by a hash sign. That means the
# detection of these systems is skipped *completely*. No wasted time there.
#
# For more control, read the reference below.
#}}}
#
# CONFIGURATION:
#{{{
# The vcs_info() feature can be configured via zstyle.
#
# First, the context in which we are working:
#       :vcs_info:<vcs-string>:<user-context>
#
# ...where <vcs-string> is one of:
#   - git, git-svn, git-p4, hg, darcs, bzr, cdv, mtn, svn, cvs, svk or tla.
#
# ...and <user-context> is a freely configurable string, assignable by the
# user as the first argument to vcs_info() (see its description below).
#
# There is are three special values for <vcs-string>: The first is named
# 'init', that is in effect as long as there was no decision what vcs
# backend to use. The second is 'preinit; it is used *before* vcs_info()
# is run, when initializing the data exporting variables. The third
# special value is 'formats' and is used by the 'vcs_info_lastmsg' for
# looking up its styles.
#
# There are two pre-defined values for <user-context>:
#   default  - the one used if none is specified
#   command  - used by vcs_info_lastmsg to lookup its styles.
#
# You may *not* use 'print_systems_' as a user-context string, because it
# is used internally.
#
# You can of course use ':vcs_info:*' to match all VCSs in all
# user-contexts at once.
#
# Another special context is 'formats', which is used by the
# vcs_info_lastmsg() utility function (see below).
#
#
# This is a description of all styles, that are looked up:
#   formats             - A list of formats, used when actionformats is not
#                         used (which is most of the time).
#   actionformats       - A list of formats, used if a there is a special
#                         action going on in your current repository;
#                         (like an interactive rebase or a merge conflict)
#   branchformat        - Some backends replace %b in the formats and
#                         actionformats styles above, not only by a branch
#                         name but also by a revision number. This style
#                         let's you modify how that string should look like.
#   nvcsformats         - These "formats" are exported, when we didn't detect
#                         a version control system for the current directory.
#                         This is useful, if you want vcs_info() to completely
#                         take over the generation of your prompt.
#                         You would do something like
#                           PS1='${VCS_INFO_message_0_}'
#                         to accomplish that.
#   max-exports         - Defines the maximum number if VCS_INFO_message_*_
#                         variables vcs_info() will export.
#   enable              - Checked in the 'init' context. If set to false,
#                         vcs_info() will do nothing.
#   disable             - Provide a list of systems, you don't want
#                         the vcs_info() to check for repositories
#                         (checked in the 'init' context, too).
#   disable-patterns    - A list of patterns that are checked against $PWD.
#                         If the pattern matches, vcs_info will be disabled.
#                         Say, ~/.zsh is a directory under version control,
#                         in which you do not want vcs_info to be active, do:
#                         zstyle ':vcs_info:*' disable-patterns "$HOME/.zsh+(|/*)"
#   use-simple          - If there are two different ways of gathering
#                         information, you can select the simpler one
#                         by setting this style to true; the default
#                         is to use the not-that-simple code, which is
#                         potentially a lot slower but might be more
#                         accurate in all possible cases.
#   use-prompt-escapes  - determines if we assume that the assembled
#                         string from vcs_info() includes prompt escapes.
#                         (Used by vcs_info_lastmsg().
#
# The use-simple style is only available for the bzr backend.
#
# The default values for these in all contexts are:
#   formats             " (%s)-[%b|%a]-"
#   actionformats       " (%s)-[%b]-"
#   branchformat        "%b:%r" (for bzr, svn and svk)
#   nvcsformats         ""
#   max-exports         2
#   enable              true
#   disable             (empty list)
#   disable-patterns    (empty list)
#   use-simple          false
#   use-prompt-escapes  true
#
#
# In normal formats and actionformats, the following replacements
# are done:
#   %s  - The vcs in use (git, hg, svn etc.)
#   %b  - Information about the current branch.
#   %a  - An identifier, that describes the action.
#         Only makes sense in actionformats.
#   %R  - base directory of the repository.
#   %r  - repository name
#         If %R is '/foo/bar/repoXY', %r is 'repoXY'.
#   %S  - subdirectory within a repository. if $PWD is
#         '/foo/bar/reposXY/beer/tasty', %S is 'beer/tasty'.
#
#
# In branchformat these replacements are done:
#   %b  - the branch name
#   %r  - the current revision number
#
# Not all vcs backends have to support all replacements.
# nvcsformat does not perform *any* replacements. It is just a string.
#}}}
#
# ODDITIES:
#{{{
# If you want to use the %b (bold off) prompt expansion in 'formats', which
# expands %b itself, use %%b. That will cause the vcs_info() expansion to
# replace %%b with %b. So zsh's prompt expansion mechanism can handle it.
# Similarly, to hand down %b from branchformat, use %%%%b. Sorry for this
# inconvenience, but it cannot be easily avoided. Luckily we do not clash
# with a lot of prompt expansions and this only needs to be done for those.
# See 'man zshmisc' for details about EXPANSION OF PROMPT SEQUENCES.
#}}}
#
# FUNCTION DESCRIPTIONS (public API):
#{{{
#   vcs_info()
#       The main function, that runs all backends and assembles
#       all data into ${VCS_INFO_message_*_}. This is the function
#       you want to call from precmd() if you want to include
#       up-to-date information in your prompt (see VARIABLE
#       DESCRIPTION below).
#
#   vcs_info_printsys()
#       Prints a list of all supported version control systems.
#       Useful to find out possible contexts (and which of them are enabled)
#       or values for the 'disable' style.
#
#   vcs_info_lastmsg()
#       Outputs the last ${VCS_INFO_message_*_} value. Takes into account
#       the value of the use-prompt-escapes style in ':vcs_info:formats'.
#       It also only prints max-exports values.
#
# All functions named VCS_INFO_* are for internal use only.
#}}}
#
# VARIABLE DESCRIPTION:
#{{{
#   ${VCS_INFO_message_N_}    (Note the trailing underscore)
#       Where 'N' is an integer, eg: VCS_INFO_message_0_
#       These variables are the storage for the informational message the
#       last vcs_info() call has assembled. These are strongly connected
#       to the formats, actionformats and nvcsformats styles described
#       above. Those styles are lists. the first member of that list gets
#       expanded into ${VCS_INFO_message_0_}, the second into
#       ${VCS_INFO_message_1_} and the Nth into ${VCS_INFO_message_N-1_}.
#       These parameters are exported into the environment.
#       (See the max-exports style above.)
#}}}
#
# EXAMPLES:
#{{{
#   Don't use vcs_info at all (even though it's in your prompt):
#   % zstyle ':vcs_info:*' enable false
#
#   Disable the backends for bzr and svk:
#   % zstyle ':vcs_info:*' disable bzr svk
#
#   Provide a special formats for git:
#   % zstyle ':vcs_info:git:*' formats       ' GIT, BABY! [%b]'
#   % zstyle ':vcs_info:git:*' actionformats ' GIT ACTION! [%b|%a]'
#
#   Use the quicker bzr backend (if you do, please report if it does
#   the-right-thing[tm] - thanks):
#   % zstyle ':vcs_info:bzr:*' use-simple true
#
#   Display the revision number in yellow for bzr and svn:
#   % zstyle ':vcs_info:(svn|bzr):*' branchformat '%b%{'${fg[yellow]}'%}:%r'
#
# If you want colors, make sure you enclose the color codes in %{...%},
# if you want to use the string provided by vcs_info() in prompts.
#
# Here is how to print the vcs infomation as a command:
#   % alias vcsi='vcs_info command; vcs_info_lastmsg'
#
#   This way, you can even define different formats for output via
#   vcs_info_lastmsg() in the ':vcs_info:command:*' namespace.
#}}}
#}}}
# utilities
VCS_INFO_adjust () { #{{{
    [[ -n ${vcs_comm[overwrite_name]} ]] && vcs=${vcs_comm[overwrite_name]}
    return 0
}
# }}}
VCS_INFO_check_com () { #{{{
    (( ${+commands[$1]} )) && [[ -x ${commands[$1]} ]] && return 0
    return 1
}
# }}}
VCS_INFO_formats () { # {{{
    setopt localoptions noksharrays
    local action=$1 branch=$2 base=$3
    local msg
    local -i i

    if [[ -n ${action} ]] ; then
        zstyle -a ":vcs_info:${vcs}:${usercontext}" actionformats msgs
        (( ${#msgs} < 1 )) && msgs[1]=' (%s)-[%b|%a]-'
    else
        zstyle -a ":vcs_info:${vcs}:${usercontext}" formats msgs
        (( ${#msgs} < 1 )) && msgs[1]=' (%s)-[%b]-'
    fi

    (( ${#msgs} > maxexports )) && msgs[$(( maxexports + 1 )),-1]=()
    for i in {1..${#msgs}} ; do
        zformat -f msg ${msgs[$i]}                      \
                        a:${action}                     \
                        b:${branch}                     \
                        r:${base:t}                     \
                        s:${vcs}                        \
                        R:${base}                       \
                        S:"$(VCS_INFO_reposub ${base})"
        msgs[$i]=${msg}
    done
    return 0
}
# }}}
VCS_INFO_maxexports () { #{{{
    zstyle -s ":vcs_info:${vcs}:${usercontext}" "max-exports" maxexports || maxexports=2
    if [[ ${maxexports} != <-> ]] || (( maxexports < 1 )); then
        printf 'vcs_info(): expecting numeric arg >= 1 for max-exports (got %s).\n' ${maxexports}
        printf 'Defaulting to 2.\n'
        maxexports=2
    fi
}
# }}}
VCS_INFO_nvcsformats () { #{{{
    setopt localoptions noksharrays
    local c v

    if [[ $1 == 'preinit' ]] ; then
        c=default
        v=preinit
    fi
    zstyle -a ":vcs_info:${v:-$vcs}:${c:-$usercontext}" nvcsformats msgs
    (( ${#msgs} > maxexports )) && msgs[${maxexports},-1]=()
}
# }}}
VCS_INFO_realpath () { #{{{
    # a portable 'readlink -f'
    # forcing a subshell, to ensure chpwd() is not removed
    # from the calling shell (if VCS_INFO_realpath() is called
    # manually).
    (
        (( ${+functions[chpwd]} )) && unfunction chpwd
        setopt chaselinks
        cd $1 2>/dev/null && pwd
    )
}
# }}}
VCS_INFO_reposub () { #{{{
    setopt localoptions extendedglob
    local base=${1%%/##}

    [[ ${PWD} == ${base}/* ]] || {
        printf '.'
        return 1
    }
    printf '%s' ${PWD#$base/}
    return 0
}
# }}}
VCS_INFO_set () { #{{{
    setopt localoptions noksharrays
    local -i i j

    if [[ $1 == '--clear' ]] ; then
        for i in {0..9} ; do
            unset VCS_INFO_message_${i}_
        done
    fi
    if [[ $1 == '--nvcs' ]] ; then
        [[ $2 == 'preinit' ]] && (( maxexports == 0 )) && (( maxexports = 1 ))
        for i in {0..$((maxexports - 1))} ; do
            typeset -gx VCS_INFO_message_${i}_=
        done
        VCS_INFO_nvcsformats $2
    fi

    (( ${#msgs} - 1 < 0 )) && return 0
    for i in {0..$(( ${#msgs} - 1 ))} ; do
        (( j = i + 1 ))
        typeset -gx VCS_INFO_message_${i}_=${msgs[$j]}
    done
    return 0
}
# }}}
# information gathering
VCS_INFO_bzr_get_data () { # {{{
    setopt localoptions noksharrays
    local bzrbase bzrbr
    local -a bzrinfo

    if zstyle -t ":vcs_info:${vcs}:${usercontext}" "use-simple" ; then
        bzrbase=${vcs_comm[basedir]}
        bzrinfo[2]=${bzrbase:t}
        if [[ -f ${bzrbase}/.bzr/branch/last-revision ]] ; then
            bzrinfo[1]=$(< ${bzrbase}/.bzr/branch/last-revision)
            bzrinfo[1]=${${bzrinfo[1]}%% *}
        fi
    else
        bzrbase=${${(M)${(f)"$( bzr info )"}:# ##branch\ root:*}/*: ##/}
        bzrinfo=( ${${${(M)${(f)"$( bzr version-info )"}:#(#s)(revno|branch-nick)*}/*: /}/*\//} )
        bzrbase="$(VCS_INFO_realpath ${bzrbase})"
    fi

    zstyle -s ":vcs_info:${vcs}:${usercontext}" branchformat bzrbr || bzrbr="%b:%r"
    zformat -f bzrbr "${bzrbr}" "b:${bzrinfo[2]}" "r:${bzrinfo[1]}"
    VCS_INFO_formats '' "${bzrbr}" "${bzrbase}"
    return 0
}
# }}}
VCS_INFO_cdv_get_data () { # {{{
    local cdvbase

    cdvbase=${vcs_comm[basedir]}
    VCS_INFO_formats '' "${cdvbase:t}" "${cdvbase}"
    return 0
}
# }}}
VCS_INFO_cvs_get_data () { # {{{
    local cvsbranch cvsbase basename

    cvsbase="."
    while [[ -d "${cvsbase}/../CVS" ]]; do
        cvsbase="${cvsbase}/.."
    done
    cvsbase="$(VCS_INFO_realpath ${cvsbase})"
    cvsbranch=$(< ./CVS/Repository)
    basename=${cvsbase:t}
    cvsbranch=${cvsbranch##${basename}/}
    [[ -z ${cvsbranch} ]] && cvsbranch=${basename}
    VCS_INFO_formats '' "${cvsbranch}" "${cvsbase}"
    return 0
}
# }}}
VCS_INFO_darcs_get_data () { # {{{
    local darcsbase

    darcsbase=${vcs_comm[basedir]}
    VCS_INFO_formats '' "${darcsbase:t}" "${darcsbase}"
    return 0
}
# }}}
VCS_INFO_git_getaction () { #{{{
    local gitaction='' gitdir=$1
    local tmp

    for tmp in "${gitdir}/rebase-apply" \
               "${gitdir}/rebase"       \
               "${gitdir}/../.dotest" ; do
        if [[ -d ${tmp} ]] ; then
            if   [[ -f "${tmp}/rebasing" ]] ; then
                gitaction="rebase"
            elif [[ -f "${tmp}/applying" ]] ; then
                gitaction="am"
            else
                gitaction="am/rebase"
            fi
            printf '%s' ${gitaction}
            return 0
        fi
    done

    for tmp in "${gitdir}/rebase-merge/interactive" \
               "${gitdir}/.dotest-merge/interactive" ; do
        if [[ -f "${tmp}" ]] ; then
            printf '%s' "rebase-i"
            return 0
        fi
    done

    for tmp in "${gitdir}/rebase-merge" \
               "${gitdir}/.dotest-merge" ; do
        if [[ -d "${tmp}" ]] ; then
            printf '%s' "rebase-m"
            return 0
        fi
    done

    if [[ -f "${gitdir}/MERGE_HEAD" ]] ; then
        printf '%s' "merge"
        return 0
    fi

    if [[ -f "${gitdir}/BISECT_LOG" ]] ; then
        printf '%s' "bisect"
        return 0
    fi
    return 1
}
# }}}
VCS_INFO_git_getbranch () { #{{{
    local gitbranch gitdir=$1
    local gitsymref='git symbolic-ref HEAD'

    if    [[ -d "${gitdir}/rebase-apply" ]] \
       || [[ -d "${gitdir}/rebase" ]]       \
       || [[ -d "${gitdir}/../.dotest" ]]   \
       || [[ -f "${gitdir}/MERGE_HEAD" ]] ; then
        gitbranch="$(${(z)gitsymref} 2> /dev/null)"
        [[ -z ${gitbranch} ]] && [[ -r ${gitdir}/rebase-apply/head-name ]] \
            && gitbranch="$(< ${gitdir}/rebase-apply/head-name)"

    elif   [[ -f "${gitdir}/rebase-merge/interactive" ]] \
        || [[ -d "${gitdir}/rebase-merge" ]] ; then
        gitbranch="$(< ${gitdir}/rebase-merge/head-name)"

    elif   [[ -f "${gitdir}/.dotest-merge/interactive" ]] \
        || [[ -d "${gitdir}/.dotest-merge" ]] ; then
        gitbranch="$(< ${gitdir}/.dotest-merge/head-name)"

    else
        gitbranch="$(${(z)gitsymref} 2> /dev/null)"

        if [[ $? -ne 0 ]] ; then
            gitbranch="$(git describe --exact-match HEAD 2>/dev/null)"

            if [[ $? -ne 0 ]] ; then
                gitbranch="${${"$(< $gitdir/HEAD)"}[1,7]}..."
            fi
        fi
    fi

    printf '%s' "${gitbranch##refs/heads/}"
    return 0
}
# }}}
VCS_INFO_git_get_data () { # {{{
    setopt localoptions extendedglob
    local gitdir gitbase gitbranch gitaction

    gitdir=${vcs_comm[gitdir]}
    gitbranch="$(VCS_INFO_git_getbranch ${gitdir})"

    if [[ -z ${gitdir} ]] || [[ -z ${gitbranch} ]] ; then
        return 1
    fi

    VCS_INFO_adjust
    gitaction="$(VCS_INFO_git_getaction ${gitdir})"
    gitbase=${PWD%/${$( git rev-parse --show-prefix )%/##}}
    VCS_INFO_formats "${gitaction}" "${gitbranch}" "${gitbase}"
    return 0
}
# }}}
VCS_INFO_hg_get_data () { # {{{
    local hgbranch hgbase file

    hgbase=${vcs_comm[basedir]}

    file="${hgbase}/.hg/branch"
    if [[ -r ${file} ]] ; then
        hgbranch=$(< ${file})
    else
        hgbranch='default'
    fi

    VCS_INFO_formats '' "${hgbranch}" "${hgbase}"
    return 0
}
# }}}
VCS_INFO_mtn_get_data () { # {{{
    local mtnbranch mtnbase

    mtnbase=${vcs_comm[basedir]}
    mtnbranch=${${(M)${(f)"$( mtn status )"}:#(#s)Current branch:*}/*: /}
    VCS_INFO_formats '' "${mtnbranch}" "${mtnbase}"
    return 0
}
# }}}
VCS_INFO_svk_get_data () { # {{{
    local svkbranch svkbase

    svkbase=${vcs_comm[basedir]}
    zstyle -s ":vcs_info:${vcs}:${usercontext}" branchformat svkbranch || svkbranch="%b:%r"
    zformat -f svkbranch "${svkbranch}" "b:${vcs_comm[branch]}" "r:${vcs_comm[revision]}"
    VCS_INFO_formats '' "${svkbranch}" "${svkbase}"
    return 0
}
# }}}
VCS_INFO_svn_get_data () { # {{{
    setopt localoptions noksharrays
    local svnbase svnbranch
    local -a svninfo

    svnbase="."
    while [[ -d "${svnbase}/../.svn" ]]; do
        svnbase="${svnbase}/.."
    done
    svnbase="$(VCS_INFO_realpath ${svnbase})"
    svninfo=( ${${${(M)${(f)"$( svn info )"}:#(#s)(URL|Revision)*}/*: /}/*\//} )

    zstyle -s ":vcs_info:${vcs}:${usercontext}" branchformat svnbranch || svnbranch="%b:%r"
    zformat -f svnbranch "${svnbranch}" "b:${svninfo[1]}" "r:${svninfo[2]}"
    VCS_INFO_formats '' "${svnbranch}" "${svnbase}"
    return 0
}
# }}}
VCS_INFO_tla_get_data () { # {{{
    local tlabase tlabranch

    tlabase="$(VCS_INFO_realpath ${vcs_comm[basedir]})"
    # tree-id gives us something like 'foo@example.com/demo--1.0--patch-4', so:
    tlabranch=${${"$( tla tree-id )"}/*\//}
    VCS_INFO_formats '' "${tlabranch}" "${tlabase}"
    return 0
}
# }}}
# detection
VCS_INFO_detect_by_dir() { #{{{
    local dirname=$1
    local basedir="." realbasedir

    realbasedir="$(VCS_INFO_realpath ${basedir})"
    while [[ ${realbasedir} != '/' ]]; do
        [[ -r ${realbasedir} ]] || return 1
        if [[ -n ${vcs_comm[detect_need_file]} ]] ; then
            [[ -d ${basedir}/${dirname} ]] && \
            [[ -e ${basedir}/${dirname}/${vcs_comm[detect_need_file]} ]] && \
                break
        else
            [[ -d ${basedir}/${dirname} ]] && break
        fi

        basedir=${basedir}/..
        realbasedir="$(VCS_INFO_realpath ${basedir})"
    done

    [[ ${realbasedir} == "/" ]] && return 1
    vcs_comm[basedir]=${realbasedir}
    return 0
}
# }}}
VCS_INFO_bzr_detect() { #{{{
    VCS_INFO_check_com bzr || return 1
    vcs_comm[detect_need_file]=branch/format
    VCS_INFO_detect_by_dir '.bzr'
    return $?
}
# }}}
VCS_INFO_cdv_detect() { #{{{
    VCS_INFO_check_com cdv || return 1
    vcs_comm[detect_need_file]=format
    VCS_INFO_detect_by_dir '.cdv'
    return $?
}
# }}}
VCS_INFO_cvs_detect() { #{{{
    VCS_INFO_check_com svn || return 1
    [[ -d "./CVS" ]] && [[ -r "./CVS/Repository" ]] && return 0
    return 1
}
# }}}
VCS_INFO_darcs_detect() { #{{{
    VCS_INFO_check_com darcs || return 1
    vcs_comm[detect_need_file]=format
    VCS_INFO_detect_by_dir '_darcs'
    return $?
}
# }}}
VCS_INFO_git_detect() { #{{{
    if VCS_INFO_check_com git && git rev-parse --is-inside-work-tree &> /dev/null ; then
        vcs_comm[gitdir]="$(git rev-parse --git-dir 2> /dev/null)" || return 1
        if   [[ -d ${vcs_comm[gitdir]}/svn ]]             ; then vcs_comm[overwrite_name]='git-svn'
        elif [[ -d ${vcs_comm[gitdir]}/refs/remotes/p4 ]] ; then vcs_comm[overwrite_name]='git-p4' ; fi
        return 0
    fi
    return 1
}
# }}}
VCS_INFO_hg_detect() { #{{{
    VCS_INFO_check_com hg || return 1
    vcs_comm[detect_need_file]=store
    VCS_INFO_detect_by_dir '.hg'
    return $?
}
# }}}
VCS_INFO_mtn_detect() { #{{{
    VCS_INFO_check_com mtn || return 1
    vcs_comm[detect_need_file]=revision
    VCS_INFO_detect_by_dir '_MTN'
    return $?
}
# }}}
VCS_INFO_svk_detect() { #{{{
    setopt localoptions noksharrays extendedglob
    local -a info
    local -i fhash
    fhash=0

    VCS_INFO_check_com svk || return 1
    [[ -f ~/.svk/config ]] || return 1

    # This detection function is a bit different from the others.
    # We need to read svk's config file to detect a svk repository
    # in the first place. Therefore, we'll just proceed and read
    # the other information, too. This is more then any of the
    # other detections do but this takes only one file open for
    # svk at most. VCS_INFO_svk_get_data() get simpler, too. :-)
    while IFS= read -r line ; do
        if [[ -n ${vcs_comm[basedir]} ]] ; then
            line=${line## ##}
            [[ ${line} == depotpath:* ]] && vcs_comm[branch]=${line##*/}
            [[ ${line} == revision:* ]] && vcs_comm[revision]=${line##*[[:space:]]##}
            [[ -n ${vcs_comm[branch]} ]] && [[ -n ${vcs_comm[revision]} ]] && break
            continue
        fi
        (( fhash > 0 )) && [[ ${line} == '  '[^[:space:]]*:* ]] && break
        [[ ${line} == '  hash:'* ]] && fhash=1 && continue
        (( fhash == 0 )) && continue
        [[ ${PWD}/ == ${${line## ##}%:*}/* ]] && vcs_comm[basedir]=${${line## ##}%:*}
    done < ~/.svk/config

    [[ -n ${vcs_comm[basedir]} ]]  && \
    [[ -n ${vcs_comm[branch]} ]]   && \
    [[ -n ${vcs_comm[revision]} ]] && return 0
    return 1
}
# }}}
VCS_INFO_svn_detect() { #{{{
    VCS_INFO_check_com svn || return 1
    [[ -d ".svn" ]] && return 0
    return 1
}
# }}}
VCS_INFO_tla_detect() { #{{{
    VCS_INFO_check_com tla || return 1
    vcs_comm[basedir]="$(tla tree-root 2> /dev/null)" && return 0
    return 1
}
# }}}
# public API
vcs_info_printsys () { # {{{
    vcs_info print_systems_
}
# }}}
vcs_info_lastmsg () { # {{{
    emulate -L zsh
    local -i i

    VCS_INFO_maxexports
    for i in {0..$((maxexports - 1))} ; do
        printf '$VCS_INFO_message_%d_: "' $i
        if zstyle -T ':vcs_info:formats:command' use-prompt-escapes ; then
            print -nP ${(P)${:-VCS_INFO_message_${i}_}}
        else
            print -n ${(P)${:-VCS_INFO_message_${i}_}}
        fi
        printf '"\n'
    done
}
# }}}
vcs_info () { # {{{
    emulate -L zsh
    setopt extendedglob

    [[ -r . ]] || return 1

    local pat
    local -i found
    local -a VCSs disabled dps
    local -x vcs usercontext
    local -ix maxexports
    local -ax msgs
    local -Ax vcs_comm

    vcs="init"
    VCSs=(git hg bzr darcs svk mtn svn cvs cdv tla)
    case $1 in
        (print_systems_)
            zstyle -a ":vcs_info:${vcs}:${usercontext}" "disable" disabled
            print -l '# list of supported version control backends:' \
                     '# disabled systems are prefixed by a hash sign (#)'
            for vcs in ${VCSs} ; do
                [[ -n ${(M)disabled:#${vcs}} ]] && printf '#'
                printf '%s\n' ${vcs}
            done
            print -l '# flavours (cannot be used in the disable style; they' \
                     '# are disabled with their master [git-svn -> git]):'   \
                     git-{p4,svn}
            return 0
            ;;
        ('')
            [[ -z ${usercontext} ]] && usercontext=default
            ;;
        (*) [[ -z ${usercontext} ]] && usercontext=$1
            ;;
    esac

    zstyle -T ":vcs_info:${vcs}:${usercontext}" "enable" || {
        [[ -n ${VCS_INFO_message_0_} ]] && VCS_INFO_set --clear
        return 0
    }
    zstyle -a ":vcs_info:${vcs}:${usercontext}" "disable" disabled

    zstyle -a ":vcs_info:${vcs}:${usercontext}" "disable-patterns" dps
    for pat in ${dps} ; do
        if [[ ${PWD} == ${~pat} ]] ; then
            [[ -n ${vcs_info_msg_0_} ]] && VCS_INFO_set --clear
            return 0
        fi
    done

    VCS_INFO_maxexports

    (( found = 0 ))
    for vcs in ${VCSs} ; do
        [[ -n ${(M)disabled:#${vcs}} ]] && continue
        vcs_comm=()
        VCS_INFO_${vcs}_detect && (( found = 1 )) && break
    done

    (( found == 0 )) && {
        VCS_INFO_set --nvcs
        return 0
    }

    VCS_INFO_${vcs}_get_data || {
        VCS_INFO_set --nvcs
        return 1
    }

    VCS_INFO_set
    return 0
}

VCS_INFO_set --nvcs preinit
# }}}

# Change vcs_info formats for the grml prompt. The 2nd format sets up
# $vcs_info_msg_1_ to contain "zsh: repo-name" used to set our screen title.
# TODO: The included vcs_info() version still uses $VCS_INFO_message_N_.
#       That needs to be the use of $VCS_INFO_message_N_ needs to be changed
#       to $vcs_info_msg_N_ as soon as we use the included version.
if [[ "$TERM" == dumb ]] ; then
    zstyle ':vcs_info:*' actionformats "(%s%)-[%b|%a] " "zsh: %r"
    zstyle ':vcs_info:*' formats       "(%s%)-[%b] "    "zsh: %r"
else
    # these are the same, just with a lot of colours:
    zstyle ':vcs_info:*' actionformats "${MAGENTA}(${NO_COLOUR}%s${MAGENTA})${YELLOW}-${MAGENTA}[${GREEN}%b${YELLOW}|${RED}%a${MAGENTA}]${NO_COLOUR} " \
                                       "zsh: %r"
    zstyle ':vcs_info:*' formats       "${MAGENTA}(${NO_COLOUR}%s${MAGENTA})${YELLOW}-${MAGENTA}[${GREEN}%b${MAGENTA}]${NO_COLOUR}%} " \
                                       "zsh: %r"
    zstyle ':vcs_info:(sv[nk]|bzr):*' branchformat "%b${RED}:${YELLOW}%r"
fi

# }}}

# command not found handling {{{

(( ${COMMAND_NOT_FOUND} == 1 )) &&
function command_not_found_handler() {
    emulate -L zsh
    if [[ -x ${GRML_ZSH_CNF_HANDLER} ]] ; then
        ${GRML_ZSH_CNF_HANDLER} $1
    fi
    return 1
}

# }}}

# {{{ set prompt
#autoload -U promptinit
#promptinit

if zrcautoload promptinit && promptinit 2>/dev/null ; then
    promptinit # people should be able to use their favourite prompt
else
    print 'Notice: no promptinit available :('
fi

setopt PROMPT_SUBST

# make sure to use right prompt only when not running a command
setopt TRANSIENT_RPROMPT

function ESC_print () {
    info_print $'\ek' $'\e\\' "$@"
}
function set_title () {
    info_print  $'\e]0;' $'\a' "$@"
}

function info_print () {
    local esc_begin esc_end
    esc_begin="$1"
    esc_end="$2"
    shift 2
    printf '%s' ${esc_begin}
    for item in "$@" ; do
        printf '%s ' "$item"
    done
    printf '%s' "${esc_end}"
}

# TODO: revise all these NO* variables and especially their documentation
#       in zsh-help() below.
[[ $NOPRECMD -eq 0 ]] && precmd () {
    [[ $NOPRECMD -gt 0 ]] && return 0
    # update VCS information
    vcs_info

    if [[ $TERM == screen* ]] ; then
        if [[ -n ${VCS_INFO_message_1_} ]] ; then
            print -nP "\ek${VCS_INFO_message_1_}\e\\"
        else
            print -nP "\ekzsh\e\\"
        fi
    fi
    # just use DONTSETRPROMPT=1 to be able to overwrite RPROMPT
    if [[ $DONTSETRPROMPT -eq 0 ]] ; then
        if [[ $BATTERY -gt 0 ]] ; then
            # update battery (dropped into $PERCENT) information
            battery
            RPROMPT="%(?..:() ${PERCENT}"
        else
            RPROMPT="%(?..:() "
        fi
    fi
    # adjust title of xterm
    # see http://www.faqs.org/docs/Linux-mini/Xterm-Title.html
    [[ ${NOTITLE} -gt 0 ]] && return 0
    case $TERM in
        (xterm*|rxvt*)
            print -Pn "\e]0;%n@%m: %~\a"
            ;;
    esac
}

# preexec() => a function running before every command
[[ $NOPRECMD -eq 0 ]] && \
preexec () {
    [[ $NOPRECMD -gt 0 ]] && return 0
# set hostname if not running on host with name 'grml'
    if [[ -n "$HOSTNAME" ]] && [[ "$HOSTNAME" != $(hostname) ]] ; then
       NAME="@$HOSTNAME"
    fi
# get the name of the program currently running and hostname of local machine
# set screen window title if running in a screen
    if [[ "$TERM" == screen* ]] ; then
        # local CMD=${1[(wr)^(*=*|sudo|ssh|-*)]}       # don't use hostname
        local CMD="${1[(wr)^(*=*|sudo|ssh|-*)]}$NAME" # use hostname
        echo -ne "\ek$CMD\e\\"
    fi
# adjust title of xterm
    [[ ${NOTITLE} -gt 0 ]] && return 0
    case $TERM in
        (xterm*|rxvt*)
            print -Pn "\e]0;%n@%m: $1\a"
            ;;
    esac
}

EXITCODE="%(?..%?%1v )"
PS2='\`%_> '      # secondary prompt, printed when the shell needs more information to complete a command.
PS3='?# '         # selection prompt used within a select loop.
PS4='+%N:%i:%_> ' # the execution trace prompt (setopt xtrace). default: '+%N:%i>'

#GRMLPROMPT='1'
# don't use colors on dumb terminals (like emacs):
if [[ "$TERM" == dumb ]] ; then
    PROMPT="${EXITCODE}${debian_chroot:+($debian_chroot)}%n@%m %40<...<%B%~%b%<< "'${VCS_INFO_message_0_}'"%# "
else
    # only if $GRMLPROMPT is set (e.g. via 'GRMLPROMPT=1 zsh') use the extended prompt
    # set variable identifying the chroot you work in (used in the prompt below)
    if [[ $GRMLPROMPT -gt 0 ]] ; then
        PROMPT="${RED}${EXITCODE}${CYAN}[%j running job(s)] ${GREEN}{history#%!} ${RED}%(3L.+.) ${BLUE}%* %D
${BLUE}%n${NO_COLOUR}@%m %40<...<%B%~%b%<< "'${VCS_INFO_message_0_}'"%# "
    else
        # This assembles the primary prompt string
        if (( EUID != 0 )); then
            PROMPT="${RED}${EXITCODE}${WHITE}${debian_chroot:+($debian_chroot)}${BLUE}%n${NO_COLOUR}@%m %40<...<%B%~%b%<< "'${VCS_INFO_message_0_}'"%# "
        else
            PROMPT="${BLUE}${EXITCODE}${WHITE}${debian_chroot:+($debian_chroot)}${RED}%n${NO_COLOUR}@%m %40<...<%B%~%b%<< "'${VCS_INFO_message_0_}'"%# "
        fi
    fi
fi

# }}}

## completion settings

autoload -U compinit
compinit
autoload -U colors
colors

# :completion:<func>:<completer>:<command>:<argument>:<tag>
#zstyle ':completion:*' completer _all_matches _list _oldlist _menu _expand _complete _match _ignored _correct _approximate _prefix
#zstyle ':completion:*' completer _list _menu _expand _complete _match _ignored _correct _approximate _prefix

# allow one error for every three characters typed in approximate completer
zstyle ':completion:*:approximate:' max-errors 'reply=( $((($#PREFIX+$#SUFFIX)/3 )) numeric )'

# start menu completion only if it could find no unambiguous initial string
zstyle ':completion:*:correct:*' insert-unambiguous true
zstyle ':completion:*:corrections' format $'%{\e[0;31m%}%d (errors: %e)%{\e[0m%}'
zstyle ':completion:*:correct:*' original true

# activate color-completion
zstyle ':completion:*:default' list-colors ${(s.:.)LS_COLORS}

# format on completion
zstyle ':completion:*:descriptions' format $'%{\e[0;31m%}completing %B%d%b%{\e[0m%}'

# complete 'cd -<tab>' with menu
zstyle ':completion:*:*:cd:*:directory-stack' menu yes select
#zstyle ':completion:*:*:cd:*' tag-order local-directories path-directories

# insert all expansions for expand completer
zstyle ':completion:*:expand:*' tag-order all-expansions
zstyle ':completion:*:history-words' list false

# activate menu
zstyle ':completion:*:history-words' menu yes

# ignore duplicate entries
zstyle ':completion:*:history-words' remove-all-dups yes
zstyle ':completion:*:history-words' stop yes

# match uppercase from lowercase
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}'

# separate matches into groups
zstyle ':completion:*:matches' group 'yes'
zstyle ':completion:*' group-name ''

zstyle ':completion:*' menu select=2
zstyle ':completion:*' select-prompt %SScrolling active: current selection at %p%s

zstyle ':completion:*:messages' format '%d'
zstyle ':completion:*:options' auto-description '%d'

# describe options in full
zstyle ':completion:*:options' description 'yes'

# on processes completion complete all user processes
zstyle ':completion:*:processes' command 'ps -au$USER'

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

# provide verbose completion information
zstyle ':completion:*' verbose true
# recent (as of Dec 2007) zsh versions are able to provide
# descriptions for commands (read: 1st word in the line) that it will
# list for the user to choose from. The following disables that,
# because it's not exactly fast.
zstyle ':completion:*:-command-:*:' verbose false

# set format for warnings
zstyle ':completion:*:warnings' format $'%{\e[0;31m%}No matches for:%{\e[0m%} %d'

# define files to ignore for zcompile
zstyle ':completion:*:*:zcompile:*' ignored-patterns '(*~|*.zwc)'
zstyle ':completion:correct:' prompt 'correct to: %e'

# ignore completion functions for commands you don't have
zstyle ':completion::(^approximate*):*:functions' ignored-patterns '_*'

# provide more processes in completion of programs like killall
zstyle ':completion:*:processes-names' command 'ps c -u ${USER} -o command | uniq'

# complete manual by their section
zstyle ':completion:*:manuals' separate-sections true
zstyle ':completion:*:manuals.*' insert-sections true
zstyle ':completion:*:man:*' menu yes select

# provide '..' as a completion
zstyle ':completion:*' special-dirs ..

# remove the trailing slash for directory argumentl-expansions
zstyle ':completion:*' squeeze-slashes true

# completing process IDs with menu selection
zstyle ':completion:*:*:kill:*' menu yes select
zstyle ':completion:*:kill:*'   force-list always
zstyle ':completion:*:*:killall:*' menu yes select
zstyle ':completion:*:killall:*'   force-list always

# run rehash on completion so new installed program are found automatically:
function _force_rehash() {
    (( CURRENT == 1 )) && rehash
    return 1
}

# zstyle -e ':completion:*' completer '
#             if [[ $_last_try != "$HISTNO$BUFFER$CURSOR" ]] ; then
#                 _last_try="$HISTNO$BUFFER$CURSOR"
#                 reply=(_complete _match _ignored _prefix _files)
#             else
#                 if [[ $words[1] == (rm|mv) ]] ; then
#                     reply=(_complete _files)
#                 else
#                     reply=(_oldlist _expand _force_rehash _complete _ignored _correct _approximate _files)
#                     #reply=(_oldlist _expand _complete _ignored _correct _approximate _files)
#                 fi
#             fi'

## correction
    # some people don't like the automatic correction - so run 'NOCOR=1 zsh' to deactivate it
if [[ "$NOCOR" -gt 0 ]] ; then
    zstyle ':completion:*' completer _oldlist _expand _force_rehash _complete _files _ignored
    setopt nocorrect
else
    # try to be smart about when to use what completer...
    setopt correct
    zstyle -e ':completion:*' completer '
            if [[ $_last_try != "$HISTNO$BUFFER$CURSOR" ]] ; then
                _last_try="$HISTNO$BUFFER$CURSOR"
                reply=(_complete _match _ignored _prefix _files)
            else
                if [[ $words[1] == (rm|mv) ]] ; then
                    reply=(_complete _files)
                else
                    reply=(_oldlist _expand _force_rehash _complete _ignored _correct _approximate _files)
                fi
            fi'
fi

# caching
# [[ -d $HOME/.cache/zsh ]] && zstyle ':completion:*' use-cache on && \
#     zstyle ':completion::complete:*' cache-path $HOME/.cache/zsh/
zstyle ':completion:*' use-cache on
zstyle ':completion:*' cache-path ~/.cache/zsh

## alias
# Global aliases (expand whatever their position) -- e.g.: find . L
alias -g BG='& exit'
alias -g C='| wc -l'
alias -g E='emacs -nw'
alias -g G='|& grep --color=auto'
alias -g H='| head'
alias -g Hl=' --help |& less -r' # (display help in pager)
alias -g L='| less'
alias -g LL='|& less -r'
alias -g N='&>/dev/null' # no output
alias -g NE='2> /dev/null'
alias -g S='| sort -u'
alias -g SL='| sort | less'
alias -g T='| tail'

alias dir='ls -lSrah'
alias ls='ls -b -CF --color=auto'
alias la='ls -hla --color=auto'
alias ll='ls -hl --color=auto'
alias lh='ls -hAl --color=auto'
alias l='ls -hlF --color=auto'

alias lad='ls -d .*(/)' # only show dot-directories
alias lsa='ls -a .*(.)' # only show dot-files
alias lss='ls -l *(s,S,t)' # only files with setgid/setuid/sticky flag
alias lsl='ls -l *(@)' # only symlinks
alias lsx='ls -l *(*)' # only executables
alias lsw='ls -ld *(R,W,X.^ND/)' # world-{readable,writable,executable} files
alias lsbig="ls -flh *(.OL[1,10])" # display the biggest files
alias lsd='ls -d *(/)'  # only show directories
alias lse='ls -d *(/^F)' # only show empty directories
alias lsnew="ls -rl *(D.om[1,10])" # display the newest files
alias lsold="ls -rtlh *(D.om[1,10])" # display the oldest files
alias lssmall="ls -Srl *(.oL[1,10])" # display the smallest files
alias lsdir="for dir in *;do;if [ -d \$dir ];then;du -hsL \$dir;fi;done" # do a du -hs on each dir on current path
alias lld='ls -ld *(-/DN)' # only directories and symbolic links that point to directories

alias rm='nocorrect rm -i'
alias cp='nocorrect cp -i'
alias mv='nocorrect mv -i'
alias mkdir='nocorrect mkdir'

alias ..='cd ..'
alias ...='cd ../../'
alias diff='diff -Naur'
alias grep='grep -i --color=auto'
alias free='free -mt'
alias da='du -sch'
alias df='df -h'
alias pg="pg -n -p 'page %d:'"
alias rmold='rm -vf .*~ *~ \#*\#' # verbose, ignore errors and don't ask
alias swclock='sudo /usr/bin/ntpdate ntp1.inrim.it'

alias pQi='pacman-color -Qi'
alias pQs='pacman-color -Qs'
alias pQl='pacman-color -Ql'
alias pQo='pacman-color -Qo'
alias pQm='pacman-color -Qm'
#alias pRcns='sudo pacman -Rcns'
alias pRs='sudo pacman-color -Rs'
alias pS='sudo pacman-color -S'
alias pSasdep='sudo pacman-color -S --asdep'
alias pSs='pacman-color -Ss'
alias pSi='pacman-color -Si'
alias pSyu='sudo pacman-color -Syu'
alias pU='sudo pacman-color -U'
alias plookfor="pacman-color -Sl | cut -d' ' -f2 | grep "
psearch() {
    echo -e "$(pacman -Ss "$@" | sed \
     -e 's#^core/.*#\\033[1;31m&\\033[0;37m#g' \
     -e 's#^extra/.*#\\033[0;32m&\\033[0;37m#g' \
     -e 's#^community/.*#\\033[1;35m&\\033[0;37m#g' \
     -e 's#^.*/.* [0-9].*#\\033[0;36m&\\033[0;37m#g' ) \
     \033[0m"
}
#alias clnabs='rm -rf $HOME/abs/pkg/*; rm -rf $HOME/abs/src/*'

#f1# Provides useful information on globbing
H-Glob() {
    echo -e "
    /      directories
    .      plain files
    @      symbolic links
    =      sockets
    p      named pipes (FIFOs)
    *      executable plain files (0100)
    %      device files (character or block special)
    %b     block special files
    %c     character special files
    r      owner-readable files (0400)
    w      owner-writable files (0200)
    x      owner-executable files (0100)
    A      group-readable files (0040)
    I      group-writable files (0020)
    E      group-executable files (0010)
    R      world-readable files (0004)
    W      world-writable files (0002)
    X      world-executable files (0001)
    s      setuid files (04000)
    S      setgid files (02000)
    t      files with the sticky bit (01000)

  print *(m-1)          # Files modified up to a day ago
  print *(a1)           # Files accessed a day ago
  print *(@)            # Just symlinks
  print *(Lk+50)        # Files bigger than 50 kilobytes
  print *(Lk-50)        # Files smaller than 50 kilobytes
  print **/*.c          # All *.c files recursively starting in \$PWD
  print **/*.c~file.c   # Same as above, but excluding 'file.c'
  print (foo|bar).*     # Files starting with 'foo' or 'bar'
  print *~*.*           # All Files that do not contain a dot
  chmod 644 *(.^x)      # make all plain non-executable files publically readable
  print -l *(.c|.h)     # Lists *.c and *.h
  print **/*(g:users:)  # Recursively match all files that are owned by group 'users'
  echo /proc/*/cwd(:h:t:s/self//) # Analogous to >ps ax | awk '{print $1}'<"
}
alias help-zshglob=H-Glob

# shell functions {{{

#f1# Provide csh compatibility
setenv() { typeset -x "${1}${1:+=}${(@)argv[2,$#]}" }  # csh compatibility

#f1# Reload an autoloadable function
freload() { while (( $# )); do; unfunction $1; autoload -U $1; shift; done }
compdef _functions freload

# List symlinks in detail (more detailed version of 'readlink -f' and 'whence -s')
sll() {
    [[ -z "$1" ]] && printf 'Usage: %s <file(s)>\n' "$0" && return 1
    for file in "$@" ; do
        while [[ -h "$file" ]] ; do
            ls -l $file
            file=$(readlink "$file")
        done
    done
}

# Usage: extract <file>
# Smart archive extractor
extract() {
    emulate -L zsh
    if [[ -f $1 ]] ; then
        case $1 in
            *.tar.bz2)  bzip2 -v -d $1      ;;
            *.tar.gz)   tar -xvzf $1        ;;
            *.rar)      unrar $1            ;;
            *.deb)      ar -x $1            ;;
            *.bz2)      bzip2 -d $1         ;;
            *.lzh)      lha x $1            ;;
            *.gz)       gunzip -d $1        ;;
            *.tar)      tar -xvf $1         ;;
            *.tgz)      gunzip -d $1        ;;
            *.tbz2)     tar -jxvf $1        ;;
            *.zip)      unzip $1            ;;
            *.Z)        uncompress $1       ;;
            *)          echo "'$1' Error. Please go away" ;;
        esac
    else
        echo "'$1' is not a valid file"
    fi
}

# Usage: compress <file> (<type>)
# Smart archive creator
compress() {
    emulate -L zsh
    if [[ -n $2 ]] ; then
        case $2 in
            tgz | tar.gz)   tar -zcvf$1.$2 $1 ;;
            tbz2 | tar.bz2) tar -jcvf$1.$2 $1 ;;
            tar.Z)          tar -Zcvf$1.$2 $1 ;;
            tar)            tar -cvf$1.$2  $1 ;;
            gz | gzip)      gzip           $1 ;;
            bz2 | bzip2)    bzip2          $1 ;;
            *)
                echo "Error: $2 is not a valid compression type"
                ;;
        esac
    else
        smartcompress $1 tar.gz
    fi
}

# grep for running process, like: 'any vim'
any() {
    emulate -L zsh
    if [[ -z "$1" ]] ; then
        echo "any - grep for process(es) by keyword" >&2
        echo "Usage: any <keyword>" >&2 ; return 1
    else
        local STRING=$1
        local LENGTH=$(expr length $STRING)
        local FIRSCHAR=$(echo $(expr substr $STRING 1 1))
        local REST=$(echo $(expr substr $STRING 2 $LENGTH))
        ps xauwww| grep "[$FIRSCHAR]$REST"
    fi
}

# Disassemble source files using gcc and as
disassemble() {
    emulate -L zsh
    gcc -pipe -S -o - -O -g $* | as -aldh -o /dev/null
}

# print hex value of a number
hex() {
    emulate -L zsh
    [[ -n "$1" ]] && printf "%x\n" $1 || { print 'Usage: hex <number-to-convert>' ; return 1 }
}

sanitize() {
    chmod -R u=rwX,go=rX "$@"
    chown -R ${USER}.users "$@"
}

# make a backup of a file
bk() { cp -a "$1" "${1}_$(date --iso-8601=seconds)" }
calc() { echo "$*" | bc; }
dec2hex() { awk 'BEGIN { printf "%x\n",$1}'; }
f() { find . -iname "*$1*" }
hex2dec() { awk 'BEGIN { printf "%d\n",0x$1}'; }
# Unified diff to timestamped outputfile
mdiff() { diff -udrP "$1" "$2" > diff.`date "+%Y-%m-%d"`."$1" }
# Memory overview
memusage() { ps aux | awk '{if (NR > 1) print $5; if (NR > 2) print "+"} END { print "p" }' | dc }
# Find all files in \$PATH with setuid bit set
mkcd() { mkdir "$1" && cd "$1"; }
mkmine() { sudo chown -R ${USER} ${1:-.}; }
mktar() { tar czf "${1%%/}.tar.gz" "${1%%/}/"; }
rot13() { echo "$@" | tr a-zA-Z n-za-mN-ZA-M; }
rot47() { echo "$@" | tr '!-~' 'P-~!-O'; }
suidfind() { ls -latg $path | grep '^...s' }

# Unified diff
udiff() {
    emulate -L zsh
    diff -urd $* | egrep -v "^Only in |^Binary files "
}

# Search DMOZ
dmoz() {
    emulate -L zsh
    ${=BROWSER} http://search.dmoz.org/cgi-bin/search\?search=${1// /_}
}

# http://strcat.de/blog/index.php?/archives/335-Software-sauber-deinstallieren...html
# Log 'make install' output
mmake() {
    emulate -L zsh
    [[ ! -d ~/.errorlogs ]] && mkdir ~/.errorlogs
    make -n install > ~/.errorlogs/${PWD##*/}-makelog
}

# a small check to see which DIR is located on which server/partition.
# stolen and modified from Sven's zshrc.forall
# Report diskusage of a directory
dirspace() {
    emulate -L zsh
    if [[ -n "$1" ]] ; then
        for dir in "$@" ; do
            if [[ -d "$dir" ]] ; then
                ( cd $dir; echo "-<$dir>"; du -shx .; echo);
            else
                echo "warning: $dir does not exist" >&2
            fi
        done
    else
        for dir in $path; do
            if [[ -d "$dir" ]] ; then
                ( cd $dir; echo "-<$dir>"; du -shx .; echo);
            else
                echo "warning: $dir does not exist" >&2
            fi
        done
    fi
}

# % slow_print `cat /etc/passwd`
# Slowly print out parameters
slow_print() {
    for argument in "$@" ; do
        for ((i = 1; i <= ${#1} ;i++)) ; do
            print -n "${argument[i]}"
            sleep 0.08
        done
        print -n " "
    done
    print ""
}

# Show some status info
status() {
    print
    print "Date..: "$(date "+%Y-%m-%d %H:%M:%S")
    print "Shell.: Zsh $ZSH_VERSION (PID = $$, $SHLVL nests)"
    print "Term..: $TTY ($TERM), ${BAUD:+$BAUD bauds, }$COLUMNS x $LINES chars"
    print "Login.: $LOGNAME (UID = $EUID) on $HOST"
    print "System: $(cat /etc/[A-Za-z]*[_-][rv]e[lr]*)"
    print "Uptime:$(uptime)"
    print
}

# Create an ISO image. You are prompted for\\&\quad volume name, filename and directory
mkiso() {
    emulate -L zsh
    echo " * Volume name "
    read volume
    echo " * ISO Name (ie. tmp.iso)"
    read iso
    echo " * Directory or File"
    read files
    mkisofs -o ~/$iso -A $volume -allow-multidot -J -R -iso-level 3 -V $volume -R $files
}

sudo ntpdate ntp1.inrim.it ntp2.inrim.it
echo "\n"
fortune mine

Offline

#42 2010-04-25 18:39:31

demian
Member
From: Frankfurt, Germany
Registered: 2009-05-06
Posts: 709

Re: Zsh(rc) Tips Thread

JohannesSM64 wrote:

You can replace this:
[...]

Thanks, I've also looked into the whole widgets thing. It's really cool that you can wrap basically anything as hotkey.
Here's one for toggling the terminal size via alt + e:

## toggle vertical terminal size when pressing alt + e
  t() { # toggle vertical terminal size between 24 and 48 lines, gotta wrap this as hotkey
    if ((LINES < 48));then
      printf %b "\033[8;48;80t"
    else
      printf %b "\033[8;24;80t"
    fi
    #sleep .1
    #echo "\$LINES = $LINES"
  }
  zle -N toggle t
  bindkey '^[e' toggle

Greets,
demian

Last edited by demian (2010-04-25 18:39:50)


no place like /home
github

Offline

#43 2010-04-26 04:36:29

relgueta
Member
Registered: 2010-04-26
Posts: 31

Re: Zsh(rc) Tips Thread

buttons wrote:

how can show the message welcome, running?, is shown always or only when you logon?

Last edited by relgueta (2010-04-26 04:36:55)

Offline

#44 2010-04-27 14:13:07

lymphatik
Member
From: Somewhere else
Registered: 2009-03-07
Posts: 119

Re: Zsh(rc) Tips Thread

Here is my little zshrc commented as much as possible

However I am still unable to do completion without my cursor  ending at the end of the completion. Because it should stay where I started the completion by either using noalwaystoend or completeinword.

ALWAYS_TO_END
    If a completion is performed with the cursor within a word, and a full completion is inserted, the cursor is moved to the end of the word. That is, the cursor is moved to the end of the word if either a single match is inserted or menu completion is performed.
COMPLETE_IN_WORD
    If unset, the cursor is set to the end of the word if completion is started. Otherwise it stays there and completion is done from both ends.

from http://zsh.sourceforge.net/Doc/Release/zsh_15.html


#!/bin/zsh
#---
#- Author: "lymphatik".
#- Last updated: 2010-04-27.
#--
#- .zshrc: Sourced when a bash instance opens.
#- GREATLY inspired by gigamo's configs. http://github.com/gigamo/dotfiles
#---

#{{{ KEYS
bindkey -v #use vi keymap
bindkey "\e[A" history-beginning-search-backward #cursor up
bindkey "\e[B" history-beginning-search-forward  #cursor down
bindkey "\e[1~" beginning-of-line #home
bindkey "\e[4~" vi-end-of-line # end
bindkey "\e[8~" end-of-line
bindkey "\e[7~" vi-beginning-of-line
bindkey '\eOc' forward-word # ctrl cursor right
bindkey '\eOd' backward-word # ctrl cursor left
bindkey "^X" push-line-or-edit # push current command into a buffer, allows you to do another command then returns to previous command
bindkey ' ' magic-space

#}}}

#{{{ VARIABLES 
#color in man
export LESS_TERMCAP_mb=$'\E[01;31m'
export LESS_TERMCAP_md=$'\E[01;31m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[01;44;33m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[01;32m'
export MOZ_DISABLE_PANGO=1

export EDITOR=vim
typeset -U PATH #to prevent redundancy in path

#}}}

#{{{ LOGON
if [[ -z "$DISPLAY" ]] && [[ $(tty) = /dev/tty1 ]]; then
  startx
  logout
fi

#}}}

#{{{ ALIASSES
#- Standard aliasses
alias ..='cd ..'
alias ...='cd ../..'
alias home='cd ~'
alias x='startx'
#- Verbose everything to avoid stupid mistakes
alias backup='bash /home/lymphatik/.xmonad/script/backup'
alias cp='cp -vi'
alias efind='bash /home/lymphatik/.xmonad/script/efind'
alias grep='grep -i --color=auto'
alias la='ls -lFA'
alias less=$PAGER
alias ln='ln -v'
alias lsbig='ls -lSh *(.) | head' # List biggest
alias lsd='ls -lhd *(-/DN)' #dir only
alias lsf='ls -lhA *(-.DN)' #file only
alias ls='ls -h --group-directories-first --color=auto' #sort files by size
alias lsnew='ls -lrt *(.) | tail' # List newest
alias lsold='ls -lrt *(.) | head' # List oldest
alias lssmall='ls -lSh *(.) | head' # List smallest
alias mmv='noglob zmv -W'
alias mv='mv -vi'
alias ncmpc='ncmpcpp'
alias pacgraph='pacgraph -c'
alias pacman-cage='bash /home/lymphatik/.xmonad/script/pacman-cage'
alias pacman='sudo pacman'
alias pacman-uncage='bash /home/lymphatik/.xmonad/script/pacman-uncage'
alias pac='sudo clyde -S'
alias pcc='sudo pacman -Scc'
alias pc='sudo diffpac'
alias pi='clyde -Si'
alias ping='ping -c 5'
alias pqdt='sudo pacman -Qdt'
alias pr='sudo pacman -Rcs'
alias pss='clyde'
alias pu='sudo clyde -Syu --aur'
alias rm='rm -Iv' #the -I only for recursive and if >3 files
alias svi='sudo gvim -p' #to open multiple files in tab
alias vi='gvim -p' #to open multiple files in tab
alias wget='wget --timeout 10'
alias xbmc='amixer -q -c 0 set PCM 100; amixer -q -c 0 set Surround 100; amixer -q -c 0 set Center 100; amixer -q -c 0 set LFE 100;xbmc;amixer -q -c 0 set PCM 10; amixer -q -c 0 set Surround 10; amixer -q -c 0 set Center 10; amixer -q -c 0 set LFE 10'

#- TV aliases
alias arte='mplayer http://tv.freebox.fr/stream_arte'
alias direct8='mplayer http://tv.freebox.fr/stream_direct8'
alias fr2='mplayer http://tv.freebox.fr/stream_france2'
alias fr3='mplayer http://tv.freebox.fr/stream_france3'
alias fr4='mplayer http://tv.freebox.fr/stream_france4'
alias fr5='mplayer http://tv.freebox.fr/stream_france5'
alias grand_journal='canal "le_grand_journal"'
alias itele='mplayer "rtsp://mafreebox.freebox.fr/fbxtv_pub/stream?namespace=1&service=679&flavour=ld"'
alias jt='canal "le_jt_de_canal"'
alias nrj12='mplayer http://tv.freebox.fr/stream_nrj12'
alias nrjhits='mplayer http://tv.freebox.fr/stream_nrjhits'

#- Radio aliases
alias bbc='mplayer -playlist http://www.bbc.co.uk/radio2/realmedia/fmg2.ram'
alias nrj='mplayer mms://vipnrj.yacast.net/encodernrj'
alias rtl='mplayer http://streaming.radio.rtl.fr/rtl-1-44-96'

#- Global aliasses
alias -g G='| grep'
alias -g H='| head'
alias -g H='--help'
alias -g L='| less'
alias -g M='| more'
alias -g T='| tail'

#- Auto open certain files
alias -s {mpg,mpeg,avi,ogm,wmv,m4v,mp4,mov,mkv}='mplayer'
alias -s {mp3,ogg,wav,flac}='mplayer'
alias -s {html,php,com,net,org,gov,be}='firefox'
alias -s txt='gvim'
alias -s pdf='apvlv'
alias -s {rar,zip,7z,tar.bz2.gz}='aunpack'

# ls settings 
export LS_COLORS='no=00:fi=00:di=01;34:ln=01;36:pi=01;33:so=01;35:do=01;35:bd=00;33;01:cd=00;33;01:or=05;31;01:ex=01;37:*.tar=00;32:*.tgz=00;32:*.arj=00;32:*.taz=00;32:*.lzh=00;32:*.zip=00;32:*.z=01;32:*.Z=01;32:*.gz=01;32:*.bz2=01;32:*.jar=01;32:*.rar=01;32:*.ace=01;32:*.7z=01;32:*.jpg=00;36:*.jpeg=00;36:*.gif=00;36:*.bmp=00;36:*.pbm=00;36:*.pgm=00;36:*.ppm=00;36:*.tga=00;36:*.xbm=00;36:*.xpm=00;36:*.tif=00;36:*.tiff=00;36:*.png=00;36:*.svg=00;36:*.svgz=00;36:*.mng=00;36:*.pcx=00;36:*.nuv=00;36:*.flc=00;36:*.fli=00;36:*.flv=00;36:*.gl=00;36:*.dl=00;36:*.xcf=00;36:*.xwd=00;36:*.yuv=00;36:*.aac=00;33:*.au=00;33:*.flac=00;33:*.mid=00;33:*.midi=00;33:*.mka=00;33:*.mp3=00;33:*.mpc=00;33:*.ogg=00;33:*.ra=00;33:*.wav=00;33:*.mov=01;36:*.mpg=01;36:*.mpeg=01;36:*.m2v=01;36:*.mkv=01;36:*.ogm=01;36:*.mp4=01;36:*.m4v=01;36:*.mp4v=01;36:*.vob=01;36:*.qt=01;36:*.wmv=01;36:*.asf=01;36:*.rm=01;36:*.rmvb=01;36:*.avi=01;36';

# watch=(notme)               # watch login/logout with the command log

#}}}

#{{{ FUNCTIONS
canal()
{
    date=`date +%y%m%d --date ''0' days ago'`
    PAGE="http://www.canalplus.fr/rest/bootstrap.php?/bigplayer/search/$1"
    VIDEO=$( wget -q -O - $PAGE | grep -o -E 'rtmp[^<]*L.flv' | grep $date | grep $1 )
    echo "$VIDEO"
    i=0
    if [ ! -z "$VIDEO" ]
        then
        for link in $VIDEO
            do
                let "i=i+1"
                flvstreamer -r $link -o $1"$i".mkv
            done
        mplayer -fs -speed 1.6 $1[0-9].mkv
        rm $1[0-9].mkv
    else
        echo "Pas de vidéo trouvée pour ce jour"
    fi
}

merge() {
  if [ $# -lt 3 ]; then
    echo "usage: merge Movie Movie-CD1 Movie-CD2"
  else
     mencoder -ovc copy -oac copy -o "$1" "$2" "$3";
  fi
}

up.rm.m() {
  if [ $# -lt 2 ]; then
    echo "usage: up.rm.m Movie time"
  else
      mencoder -ovc copy -oac copy -ss 0 -endpos "$2" -o temp.avi "$1"
      rm "$1"
      mv temp.avi "$1"
  fi
}

up.rm.s() {
  if [ $# -lt 1 ]; then
    echo "usage: up.rm.s TVShow"
  else
      LEN=`mplayer -vo null -ao null -frames 0 -identify "$1" 2>/dev/null | grep "^ID_LENGTH" | sed -e 's/ID_LENGTH=//g'`
      temps=10
      temp=$(echo "$LEN-$temps" | bc)
      mencoder -ovc copy -oac copy -ss 0 -endpos $temp -o temp.avi "$1"
      rm "$1"
      mv temp.avi "$1"
  fi
}

up.tl() {
    find -iname "*.rar" -exec aunpack {} "*.avi" \;
# find -atime -1 -print0 | xargs -0 -I file $(up.rm.s file)
    tvrenamer.pl
    rm *.rar
}

#- create playlist
playlist() {
    IFS=$'\n'
    playfile="/home/lymphatik/playlist";
        case $1 in
            -tv) find /backup/TV -type f -newerma $playfile.tv >> $playfile.tv;;
            -an) find /backup/Anime -type f -newerma $playfile.anime >> $playfile.anime;;
           -mov) find /backup/Movies -type f -newerma $playfile.movie >> $playfile.movie;;
            -ptv) mplayer -fs -playlist $playfile.tv;;
            -pan) mplayer -fs -playlist $playfile.anime;;
            -pmov) mplayer -fs -playlist $playfile.movie;;
            *) echo "$1 $2 Learn how to read bash script";;
        esac
}


#- Search by paragraph
grepp() {
    if test -z "$1" || test -z "$2" ; then
        echo "USAGE: grepp searchterm filetosearch";
    else
        perl -00ne "print if /$1/i" < $2
    fi
}
#- Commit conf files easily
commit() {
    git commit -a -m "$*"
    git push origin master
}

#- Extract archive.
#extract() {
#    if [ -f "$1" ] ; then
#        case "$1" in
#            *.tar.bz2) tar xvjf "$1" ;;
#            *.tar.gz) tar xzvf "$1" ;;
#            *.tar.Z) tar xzvf "$1" ;;
#            *.bz2) bunzip2 "$1" ;;
#            *.rar) unrar x "$1" ;;
#            *.gz) gunzip "$1" ;;
#            *.jar) unzip "$1" ;;
#            *.tar) tar xvf "$1" ;;
#            *.tbz2) tar xvjf "$1" ;;
#            *.tgz) tar xvzf "$1" ;;
#            *.zip) unzip "$1" ;;
#            *.Z) uncompress "$1" ;;
#            *.7z) 7z x "$1" ;;
#            *) echo "'$1' Error. Please go away" ;;
#        esac
#    else
#        echo "'$1' is not a file"
#    fi
#}

#- Manage services
service() {
  if [ $# -lt 2 ]; then
    echo "usage: service [service] [stop|start|restart]"
  else
    sudo /etc/rc.d/$1 $2
  fi
}

#- Reload .zshrc.
src() {
    autoload -U zrecompile
    [[ -f ~/.zshrc ]] && zrecompile -p ~/.zshrc
    [[ -f ~/.zcompdump ]] && zrecompile -p ~/.zcompdump
    [[ -f ~/.zcompdump ]] && zrecompile -p ~/.zcompdump
    [[ -f ~/.zshrc.zwc.old ]] && rm -f ~/.zshrc.zwc.old
    [[ -f ~/.zcompdump.zwc.old ]] && rm -f ~/.zcompdump.zwc.old
    source ~/.zshrc
}

#- Create archive.
roll() {
    if [ -n "$1" ] ; then
        FILE=$1
        case $FILE in
            *.tar.bz2) shift && tar cjf $FILE $* ;;
            *.tar.gz) shift && tar czf $FILE $* ;;
            *.tgz) shift && tar czf $FILE $* ;;
            *.zip) shift && zip $FILE $* ;;
            *.rar) shift && rar $FILE $* ;;
        esac
    else
        echo "You must specify a filename."
    fi
}

#- Define a word - USAGE: define dog
define() {
    lynx -dump "http://www.google.com/search?hl=en&q=define%3A+${1}&btnG=Google+Search" | grep -m 3 -w "*"  | sed 's/;/ -/g' | cut -d- -f1 > /tmp/templookup.txt
    if [[ -s  /tmp/templookup.txt ]] ;then
        until ! read response
        do
            echo "${response}"
        done < /tmp/templookup.txt
    else
        echo "Sorry, I can't find the term \"${1} \""
    fi
    rm -f /tmp/templookup.txt > /dev/null
}

#- Determine a directory sizes
dirsize() {
    du -shx * .[a-zA-Z0-9_]* 2> /dev/null | \
    egrep '^ *[0-9.]*[MG]' | sort -n > /tmp/list
    egrep '^ *[0-9.]*M' /tmp/list
    egrep '^ *[0-9.]*G' /tmp/list
    rm -rf /tmp/list &> /dev/null
}

#- Swap two filenames around
swap() {
    if [ $# -ne 2 ]; then
        echo "Swap: 2 arguments needed"; return 1
    fi
    if [ ! -e $1 ]; then
        echo "Swap: $1 does not exist"; return 1
    fi
    if [ ! -e $2 ]; then
        echo "Swap: $2 does not exist"; return 1
    fi
    local TMPFILE=tmp.$$ ; mv $1 $TMPFILE ; mv $2 $1 ; mv $TMPFILE $2
}

goto() { [ -d "$1" ] && cd "$1" || cd "$(dirname "$1")"; }
#- Copy and follow
cpf() { cp "$@" && goto "$_"; }
#- Move and follow
mvf() { mv "$@" && goto "$_"; }

#}}}

#{{{ PROMPT

#change the title of urxvt based on the cmd
case $TERM in
    *xterm*|rxvt|rxvt-unicode|rxvt-256color|(dt|k|E)term)
        precmd () { print -Pn "\e]0;$TERM - [%n@%M]%# [%~]\a" }
        preexec () { print -Pn "\e]0;$TERM - [%n@%M]%# [%~] ($1)\a" }
    ;;
    screen)
        precmd () {
            print -Pn "\e]83;title \"$1\"\a"
            print -Pn "\e]0;$TERM - (%L) [%n@%M]%# [%~]\a"
        }
        preexec () {
            print -Pn "\e]83;title \"$1\"\a"
            print -Pn "\e]0;$TERM - (%L) [%n@%M]%# [%~] ($1)\a"
        }
    ;;
esac

#set prompt colors based on the users and chroot
setprompt () {
    autoload -U colors zsh/terminfo
    colors
    setopt prompt_subst

    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}]%}'
    done
    PR_NO_COLOR="%{$terminfo[sgr0]%}"
    PR_USER="%n"
    PR_DATE="%T"
    PR_DIR="%~"

    UC=$PR_CYAN             #- User's color
    [ $UID -eq "0" ] && UC=$PR_RED  #- Root's color

    if [ -e /chroot32 ]; then
        CHROOT=" ${PR_RED}(chroot32)${PR_NO_COLOR}"
    fi

    PROMPT="${UC}${PR_USER}$CHROOT ${PR_BLUE}${PR_DIR} ${UC}»${PR_NO_COLOR} "
    RPROMPT="${UC}${PR_NO_COLOR} ${PR_DATE}"
    PS2=" ${UC}»${PR_NO_COLOR} "
}

setprompt

#}}}

#{{{ COMPLETION SYSTEM
#- Expansion options.
zstyle ':completion:*' completer _expand _complete _prefix _correct _approximate
zstyle ':completion::prefix-1:*' completer _complete
zstyle ':completion:incremental:*' completer _complete _correct
zstyle ':completion:predict:*' completer _complete

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

#- Expand partial paths.
zstyle ':completion:*' expand 'yes'
zstyle ':completion:*' squeeze-slashes 'yes'

zstyle ':completion:*' use-cache on
zstyle ':completion:*' cache-path ~/.cache/zsh

#- Include non-hidden directories in globbed file completions
#- for certain commands.
zstyle ':completion::complete:*' '\'

#- Tag-order 'globbed-files directories' all-files.
zstyle ':completion::complete:*:tar:directories' file-patterns '*~.*(-/)'

# completion with globbing
zstyle ':completion:*' glob 'yes'

zstyle ':completion:*' insert-tab pending # tab, don't annoy me

#- Don't complete backup files as executables.
zstyle ':completion:*:complete:-command-::commands' ignored-patterns '*\~'
zstyle ':completion:*:-command-:*:'    verbose false

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

#- Separate matches into groups.
zstyle ':completion:*:matches' group 'yes'

#- Describe each match group.
zstyle ':completion:*:descriptions' format "%B---- %d%b"

#- Messages/warnings format.
zstyle ':completion:*:messages' format '%B%U---- %d%u%b'
zstyle ':completion:*:warnings' format '%B%U---- no match for: %d%u%b'

#- Describe options in full.
zstyle ':completion:*:options' description 'yes'
zstyle ':completion:*:options' auto-description '%d'

#- Complete manual by their section.
zstyle ':completion:*:manuals'    separate-sections true
zstyle ':completion:*:manuals.*'  insert-sections   true

#- activate color-completion
zstyle ':completion:*:default' list-colors ${(s.:.)LS_COLORS}

#- on processes completion complete all user processes
zstyle ':completion:*:processes' command 'ps -au$USER'

#- provide more processes in completion of programs like killall
zstyle ':completion:*:processes-names' command 'ps c -u ${USER} -o command | uniq'

#- completing process IDs with menu selection
zstyle ':completion:*:*:kill:*' menu yes select
zstyle ':completion:*:kill:*'   force-list always
zstyle ':completion:*:*:killall:*' menu yes select
zstyle ':completion:*:killall:*'   force-list always
zstyle ':completion:*:*:pkill:*' menu yes select
zstyle ':completion:*:pkill:*'   force-list always

#- ignore duplicate entries
zstyle ':completion:*:history-words' remove-all-dups yes
zstyle ':completion:*:history-words' stop yes

# activate menu
zstyle ':completion:*:correct:*' insert-unambiguous true # start menu completion only if it could find no unambiguous initial string
zstyle ':completion:*:man:*' menu yes select
zstyle ':completion:*:history-words' menu yes # activate menu
zstyle ':completion:*:*:cd:*:directory-stack' menu yes select # complete 'cd -<tab>' with menu
zstyle ':completion:*' menu select=5 yes

zstyle ':completion:*' format '%d:'
zstyle ':completion:*' group-name ''
zstyle ':completion:*' matcher-list 'r:|[._-]=* r:|=*'
zstyle ':completion:*' max-errors 3
zstyle ':completion:*' prompt 'Alternatives %e:'
zstyle ':completion:*' select-prompt %SScrolling active: current selection at %p%s
zstyle :compinstall filename "$HOME/.zshrc"

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

#}}}

#{{{ OPTIONS
#- History.
HISTSIZE=2000
SAVEHIST=2000
HISTFILE=~/.zshhistory

#- Load modules.
autoload -U compinit
compinit 2>/dev/null
autoload zmv        # For renaming.
autoload -U zcalc   # For math.
autoload -U zsh-mime-setup
zsh-mime-setup

compdef _pacman clyde=pacman

#- setopt (see http://zsh.sourceforge.net/Doc/Release/zsh_15.html)
setopt noalwaystoend          # When complete from middle, move cursor
setopt autocd               # automatically cd to paths
setopt automenu             # Automatically use menu completion after the second consecutive request for completion
setopt autopushd            # Automatically append dirs to the push/pop list
setopt BANG_HIST
setopt banghist             # Perform textual history expansion, csh-style, treating the character `!' specially.
setopt cdablevars           # Avoid the need for an explicit $
setopt completeinword       # Not just at the end
setopt correctall           # spelling correction
setopt extendedglob         # Weird & wacky pattern matching - yay zsh!
setopt EXTENDED_HISTORY 
setopt globdots             # Include dot file in globbing
setopt HIST_FIND_NO_DUPS
setopt hist_ignore_all_dups # when I run a command several times, only store one
setopt HIST_IGNORE_DUPS 
setopt hist_ignore_space    # don't store command which start by a space
setopt HIST_NO_STORE        # don't save 'history' cmd in history
setopt HIST_REDUCE_BLANKS 
setopt HIST_SAVE_NO_DUPS
setopt histverify           # When using ! cmds, confirm first
# setopt ignoreeof            # forces the user to type exit or logout, instead of just pressing ^D
setopt INC_APPEND_HISTORY 
setopt interactivecomments  # turns on interactive comments; comments begin with a #
setopt LONG_LIST_JOBS       # display PID when suspending processes as well
setopt monitor              # job control
setopt multios              # Perform implicit tees or cats when multiple redirections are attempted
setopt NO_AUTO_REMOVE_SLASH # When the last character resulting from a completion is a slash and the next character typed is a word delimiter, a slash, or a character that ends a command (such as a semicolon or an ampersand), remove the slash.
setopt nobeep               # who loves thos nasty beeps
setopt noclobber            # prevents you from accidentally overwriting an existing file. If you really do want to clobber a file, you can use the >! operator
setopt nohup                # and don't kill them, either
setopt listtypes            # Show types in completion
setopt nopromptcr           # Don't add \n which overwrites cmds with no \n
setopt NO_SH_WORD_SPLIT     # use zsh style word splitting
setopt notify               # notify immediately, not on next prompt
setopt printexitvalue       # alert me if something's failed
setopt pushdignoredups      # And don't duplicate them
setopt pushdminus 
setopt pushdsilent 
setopt pushdtohome
setopt SHARE_HISTORY
setopt vi                   # use bindkeys

#}}}

#{{{ WIDGET

# open ranger in the current directory by using Ctrl+f
integrate_ranger()
{
     ranger <$TTY
     cd "$(grep \^\' ~/.ranger/bookmarks | cut -b3-)"
     precmd
     zle redisplay
}
zle -N integrated-ranger integrate_ranger
bindkey '^E' integrated-ranger

# change the cursor color to red when in cmd mode vim style and grey when in insert mode
zle-keymap-select () {
if [ $KEYMAP = vicmd ]; then
echo -ne "\033]12;Red\007"
else
echo -ne "\033]12;Grey\007"
fi
}
zle -N zle-keymap-select
zle-line-init () {
zle -K viins
echo -ne "\033]12;Grey\007"
}
zle -N zle-line-init
bindkey -v

#}}}

Last edited by lymphatik (2010-04-27 14:39:07)

Offline

#45 2010-05-13 12:22:58

FaN_OnLy1
Member
From: Montpellier, France
Registered: 2008-09-22
Posts: 126

Re: Zsh(rc) Tips Thread

Some function i wrote to display the battery state in my right prompt, i guess it could have been wrote in a more elegant way, but it works.

in4y03.png
nqw7yp.png

#------------------- Battery Display Using ACPI -------------------

function showbat {
    BATP=$(acpi -b | awk '{print $4}' | sed -e s/%,//g);

    if [ "$BATP" = "100%" ]; then
        BATP="100" && BCOLOR="green";
    elif [ "$BATP" -ge "75" ]; then
        BCOLOR="green";
    elif [ "$BATP" -ge "25" ]; then
        BCOLOR="yellow";
    else
        BCOLOR="red";
    fi

    BATT=$(acpi -b | awk '{print $5}' | sed -e s/...$//g);
    BATAC=$(acpi -b | awk '{print $3}'| sed -e s/,//g);
    
    if [ "$BATAC" = "Charging" ] || [ "$BATAC" = "Full" ]; then
        echo "%{$fg_bold[$BCOLOR]%}$BATP%% ~[AC]%{$reset_color%}"
    else
        echo "%{$fg_bold[$BCOLOR]%}$BATP%% $BATT min%{$reset_color%}"
    fi
}

#------------------- Battery Display Using ACPI -------------------
RPROMPT='$(showbat)'

BATP var stores the battery percentage
BATT var stores the battery time, in hh:mm format (no need for seconds)
BATAC var stores the state of the battery (Charging or Discharging)
BCOLOR var stores the color i will display the battery stuff in
RPROMPT is zsh's right prompt

Now, if the battery is >= 75 , BCOLOR will be green, if it is =< 25, BCOLOR will be yellow, else it will be red

If the Battery is plugged to the AC, the prompt will display it like this : 97% ~[AC]
If it is unplugged : 97% 1:45

This, of course, needs the acpi package, wich is just about 44k and doesn't have any dependencies.

EDIT : Rewrote the script, i figured that the battery percentage and color were only updated when sourcing ~/.zshrc (opening a new shell), now it is fixed ans the function is implemented in a more elegant way, now you just have to put $(showbat) somewhere in your prompt and it will work with color and shiz. big_smile
EDIT2 : Fixed an issue when the battery was 100% fully charged on AC.

Last edited by FaN_OnLy1 (2010-05-16 22:36:19)

Offline

#46 2010-05-13 13:13:05

kazuo
Member
From: São Paulo/Brazil
Registered: 2008-03-18
Posts: 413
Website

Re: Zsh(rc) Tips Thread

Ok, I gonna post some parts of my zshrc that I think is useful.

First I use vi mode, and like to show the current mode. I have two solutions one when inside screen and other inside urxvt (the two are independent and works separated or together)

zshrc

# Key bindings {{{1
function show_mode() #{{{2
{
  case $TERM in
    screen*)
      # Show mode on hardstatus
      printf '\e_--%s--\e\' $1
    ;;
    rxvt*)
      # Show mode on overlay
      printf '\e]777;vishowmode:%s\007\e\' $1
    ;;
  esac
} #}}}2

function show_mode_delete() #{{{2
{
  case $TERM in
    screen*)
      printf '\e_\e\'
    ;;
    rxvt*)
      printf '\e]777;vishowmode:%s\007\e\' DELETE
    ;;
  esac
} #}}}2

function zle-keymap-select() #{{{2
{
  if [[ $KEYMAP == vicmd ]]; then
    show_mode NORMAL
  else
    show_mode INSERT
  fi
} #}}}2

case $TERM in
  rxvt*)
    # Clear overlay before opening a program
    add-zsh-hook preexec show_mode_delete
  ;;
esac

bindkey -v
show_mode INSERT

and the needed perl extension vishowmode

#! /usr/bib/perl
sub on_osc_seq_perl {
  if ($_[1] =~ /vishowmode:/) {
    my ($self) = @_;

    $self->{overlaymode} = $self->overlay (-1, -1, 10, 1, urxvt::DEFAULT_RSTYLE, 0);
    if ($_[1] =~ /NORMAL/) {
      $self->{overlaymode}->set (0, 0, "--NORMAL--");
    } elsif ($_[1] =~ /INSERT/) {
      $self->{overlaymode}->set (0, 0, "--INSERT--");
    } elsif ($_[1] =~ /DELETE/) {
      undef $self->{overlaymode}
    }
  }

  ()
}

ss:
10gz4i8.png

Another one, a small one, is I open vim, ssh in new screen windows but I test for a redirection so 'echo bla|vim -' works

# Test for terminal and open in a new window
function new_screen() {
  if [[ -t STDIN && -t STDOUT ]] { screen $* } else { $* }
}

case $TERM in
  screen*)
    alias vim='new_screen vim'
    alias vimdiff='new_screen vimdiff'
    alias ssh='new_screen ssh'
    alias irssi='new_screen irssi'
    alias weechat='new_screen weechat-curses'
  ;;
esac

Last edited by kazuo (2010-05-13 13:16:23)

Offline

#47 2010-05-13 17:16:45

Roline
Member
From: Netherlands
Registered: 2009-12-05
Posts: 207
Website

Re: Zsh(rc) Tips Thread

@kazuo: nice prompt! Would you care to share?


Bitbucket - DeviantART - Userstyles
*Currently Not Using Arch

Offline

#48 2010-05-13 19:39:48

kazuo
Member
From: São Paulo/Brazil
Registered: 2008-03-18
Posts: 413
Website

Re: Zsh(rc) Tips Thread

Roline wrote:

@kazuo: nice prompt! Would you care to share?

Its is basically adam2 from zsh distro. I modified it but adam2 is modified after so is better to use the the distro and edit it to you taste. The options to adam2 I used is '8bit blue yellow green'.

EDIT: Ok I updated. The only thing I need to do with the new adam2 is to correct the multibyte handling. This is the diff.

--- /usr/share/zsh/4.3.10/functions/Prompts/prompt_adam2_setup  2009-10-20 18:52:02.000000000 -0200
+++ prompt_adam2_setup 2010-05-13 16:48:57.639471409 -0300
@@ -85,8 +85,8 @@
 }
 
 prompt_adam2_choose_prompt () {
-  local prompt_line_1a_width=${#${(S%%)prompt_line_1a//(\%([KF1]|)\{*\}|\%[Bbkf])}}
-  local prompt_line_1b_width=${#${(S%%)prompt_line_1b//(\%([KF1]|)\{*\}|\%[Bbkf])}}
+  local prompt_line_1a_width=${(m)#${(S%%)prompt_line_1a//(\%([KF1]|)\{*\}|\%[Bbkf])}}
+  local prompt_line_1b_width=${(m)#${(S%%)prompt_line_1b//(\%([KF1]|)\{*\}|\%[Bbkf])}}
   
   local prompt_padding_size=$(( COLUMNS
                                   - prompt_line_1a_width

I remove the bold from the @ too, but this is trivial (remove the %B before the @ in prompt_user_host).

Last edited by kazuo (2010-05-13 19:50:46)

Offline

#49 2010-05-16 20:17:27

FaN_OnLy1
Member
From: Montpellier, France
Registered: 2008-09-22
Posts: 126

Re: Zsh(rc) Tips Thread

Also, let me point everyone to this : http://github.com/robbyrussell/oh-my-zsh

Sets up sane defaults for zsh and a clean implementation of a zshrc smile you juste have to set up a theme file or use a preinstalled one to customize your prompt, everything is set up in ~/.oh-my-zsh/ and the functions are in ~/.oh-my-zsh/lib

Offline

#50 2010-05-16 20:29:15

JohannesSM64
Member
From: Norway
Registered: 2009-10-11
Posts: 623
Website

Re: Zsh(rc) Tips Thread

Maybe this thread should be merged with this: http://bbs.archlinux.org/viewtopic.php?id=90777

Offline

Board footer

Powered by FluxBB