* /etc/zsh/zshrc:
[grml-etc-core.git] / etc / zsh / zshrc
1 # Filename:      zshrc
2 # Purpose:       config file for zsh (z shell)
3 # Authors:       grml-team (grml.org), (c) Michael Prokop <mika@grml.org>
4 # Bug-Reports:   see http://grml.org/bugs/
5 # License:       This file is licensed under the GPL v2.
6 # Latest change: Don Nov 30 16:15:06 CET 2006 [mika]
7 ################################################################################
8 # This file is sourced only for interactive shells. It
9 # should contain commands to set up aliases, functions,
10 # options, key bindings, etc.
11 #
12 # Global Order: zshenv, zprofile, zshrc, zlogin
13 ################################################################################
14
15 # {{{ check for version/system
16 # check for versions (compatibility reasons)
17   if autoload is-at-least && is-at-least 2>/dev/null ; then
18      is4() { is-at-least 4 }
19      is42() { is-at-least 4.2 }
20   else
21     is4(){
22       [[ $ZSH_VERSION == 4.* ]] && return 0
23       return 1
24     }
25     is42(){
26       [[ $ZSH_VERSION == 4.<2->* ]] && return 0
27       return 1
28     }
29   fi
30
31 # grml specific stuff
32   isgrml(){
33     [ -f /etc/grml_version ] && return 0
34     return 1
35   }
36
37   isgrmlcd(){
38     [ -f /etc/grml_cd ] && return 0
39     return 1
40   }
41
42   if isgrml ; then
43     isgrmlsmall() {
44     [[ ${${${(f)"$(</etc/grml_version)"}%% *}##*-} == 'small' ]] && return 0 ; return 1
45   }
46   else
47     isgrmlsmall() { return 1 }
48   fi
49
50 # check for user, if not running as root set $SUDO to sudo
51  (( EUID != 0 )) && SUDO='sudo' || SUDO=''
52
53 # change directory to home on first invocation of zsh
54 # important for rungetty -> autologin
55 # Thanks go to Bart Schaefer!
56   isgrml && checkhome() {
57   if [[ -z "$ALREADY_DID_CD_HOME" ]]; then
58      export ALREADY_DID_CD_HOME=$HOME
59      cd
60   fi
61   }
62 # }}}
63
64 # {{{ set some variables
65   export EDITOR=${EDITOR:-vim}
66   export MAIL=${MAIL:-/var/mail/$USER}
67   [[ -f ~/.terminfo/m/mostlike ]] && MYLESS='LESS=C TERMINFO=~/.terminfo TERM=mostlike less' || MYLESS='less'
68   [[ -x /usr/bin/dircolors ]] && eval `dircolors -b`
69
70 # Search path for the cd comman
71 #  cdpath=(.. ~)
72
73 # Support our own site-functions
74   [ -d /etc/zsh/site-functions ] && FPATH=/etc/zsh/site-functions:$FPATH
75
76 # automatically remove duplicates from these arrays
77   typeset -U path cdpath fpath manpath
78 # }}}
79
80 # {{{ keybindings
81  if [[ "$TERM" != emacs ]]; then
82   [[ -z "$terminfo[kdch1]" ]] || bindkey -M emacs "$terminfo[kdch1]" delete-char
83   [[ -z "$terminfo[khome]" ]] || bindkey -M emacs "$terminfo[khome]" beginning-of-line
84   [[ -z "$terminfo[kend]"  ]] || bindkey -M emacs "$terminfo[kend]"  end-of-line
85   [[ -z "$terminfo[kdch1]" ]] || bindkey -M vicmd "$terminfo[kdch1]" vi-delete-char
86   [[ -z "$terminfo[khome]" ]] || bindkey -M vicmd "$terminfo[khome]" vi-beginning-of-line
87   [[ -z "$terminfo[kend]"  ]] || bindkey -M vicmd "$terminfo[kend]"  vi-end-of-line
88   [[ -z "$terminfo[cuu1]"  ]] || bindkey -M viins "$terminfo[cuu1]"  vi-up-line-or-history
89   [[ -z "$terminfo[cuf1]"  ]] || bindkey -M viins "$terminfo[cuf1]"  vi-forward-char
90   [[ -z "$terminfo[kcuu1]" ]] || bindkey -M viins "$terminfo[kcuu1]" vi-up-line-or-history
91   [[ -z "$terminfo[kcud1]" ]] || bindkey -M viins "$terminfo[kcud1]" vi-down-line-or-history
92   [[ -z "$terminfo[kcuf1]" ]] || bindkey -M viins "$terminfo[kcuf1]" vi-forward-char
93   [[ -z "$terminfo[kcub1]" ]] || bindkey -M viins "$terminfo[kcub1]" vi-backward-char
94   # ncurses stuff:
95   [[ "$terminfo[kcuu1]" == "\eO"* ]] && bindkey -M viins "${terminfo[kcuu1]/O/[}" vi-up-line-or-history
96   [[ "$terminfo[kcud1]" == "\eO"* ]] && bindkey -M viins "${terminfo[kcud1]/O/[}" vi-down-line-or-history
97   [[ "$terminfo[kcuf1]" == "\eO"* ]] && bindkey -M viins "${terminfo[kcuf1]/O/[}" vi-forward-char
98   [[ "$terminfo[kcub1]" == "\eO"* ]] && bindkey -M viins "${terminfo[kcub1]/O/[}" vi-backward-char
99   [[ "$terminfo[khome]" == "\eO"* ]] && bindkey -M viins "${terminfo[khome]/O/[}" beginning-of-line
100   [[ "$terminfo[kend]"  == "\eO"* ]] && bindkey -M viins "${terminfo[kend]/O/[}"  end-of-line
101   [[ "$terminfo[khome]" == "\eO"* ]] && bindkey -M emacs "${terminfo[khome]/O/[}" beginning-of-line
102   [[ "$terminfo[kend]"  == "\eO"* ]] && bindkey -M emacs "${terminfo[kend]/O/[}"  end-of-line
103 fi
104
105 ## keybindings (run 'bindkeys' for details, more details via man zshzle)
106 # use emacs style per default:
107   bindkey -e
108 # use vi style:
109 # bindkey -v
110
111 #if [[ "$TERM" == screen ]]; then
112   bindkey '\e[1~' beginning-of-line       # home
113   bindkey '\e[4~' end-of-line             # end
114   bindkey "^[[A"  up-line-or-search       # cursor up
115   bindkey "^[[B"  down-line-or-search     # <ESC>-
116   bindkey '^x'    history-beginning-search-backward # alternative ways of searching the shell history
117 # bindkey -s '^L' "|less\n"             # ctrl-L pipes to less
118 # bindkey -s '^B' " &\n"                # ctrl-B runs it in the background
119 # if terminal type is set to 'rxvt':
120   bindkey '\e[7~' beginning-of-line       # home
121   bindkey '\e[8~' end-of-line             # end
122 #fi
123
124 #  bindkey '\eq' push-line-or-edit
125 # }}}
126
127 # power completion - abbreviation expansion {{{
128 # power completion / abbreviation expansion / buffer expansion
129 # see http://zshwiki.org/home/examples/zleiab for details
130 # less risky than the global aliases but powerful as well
131 # just type the abbreviation key and afterwards ',.' to expand it
132   declare -A abk
133   setopt extendedglob
134   setopt interactivecomments
135   abk=(
136    # key  # value
137    'C'    '| wc -l'
138    '...' '../..'
139    '....' '../../..'
140    'BG' '& exit'
141    'C' '|wc -l'
142    'G' '|& grep --color=auto'
143    'H' '|head'
144    'Hl' ' --help |& less -r'
145    'L' '|less'
146    'LL' '|& less -r'
147    'M' '|most'
148    'N' '&>/dev/null'
149    'R' '| tr A-z N-za-m'
150    'SL' '| sort | less'
151    'S' '| sort -u'
152    'T' '|tail'
153    'V' '|& vim -'
154    'hide' "echo -en '\033]50;nil2\007'"
155    'tiny' 'echo -en "\033]50;-misc-fixed-medium-r-normal-*-*-80-*-*-c-*-iso8859-15\007"'
156    'small' 'echo -en "\033]50;6x10\007"'
157    'medium' 'echo -en "\033]50;-misc-fixed-medium-r-normal--13-120-75-75-c-80-iso8859-15\007"'
158    'default' 'echo -e "\033]50;-misc-fixed-medium-r-normal-*-*-140-*-*-c-*-iso8859-15\007"'
159    'large' 'echo -en "\033]50;-misc-fixed-medium-r-normal-*-*-150-*-*-c-*-iso8859-15\007"'
160    'huge' 'echo -en "\033]50;-misc-fixed-medium-r-normal-*-*-210-*-*-c-*-iso8859-15\007"'
161    'smartfont' 'echo -en "\033]50;-artwiz-smoothansi-*-*-*-*-*-*-*-*-*-*-*-*\007"'
162    'semifont' 'echo -en "\033]50;-misc-fixed-medium-r-semicondensed-*-*-120-*-*-*-*-iso8859-15\007"'
163    'da' 'du -sch'
164    'j' 'jobs -l'
165    'u' 'translate -i'
166    'co' "./configure && make && sudo make install"
167    'CH' "./configure --help"
168    'conkeror' 'firefox -chrome chrome://conkeror/content'
169    'dir' 'ls -lSrah'
170    'lad' $'ls -d .*(/)\n# only show dot-directories'
171    'lsa' $'ls -a .*(.)\n# only show dot-files'
172    'lss' $'ls -l *(s,S,t)\n# only files with setgid/setuid/sticky flag'
173    'lsl' $'ls -l *(@[1,10])\n# only symlinks'
174    'lsx' $'ls -l *(*[1,10])\n# only executables'
175    'lsw' $'ls -ld *(R,W,X.^ND/)\n# world-{readable,writable,executable} files'
176    'lsbig' $'ls -flh *(.OL[1,10])\n# display the biggest files'
177    'lsd' $'ls -d *(/)\n# only show directories'
178    'lse' $'ls -d *(/^F)\n# only show empty directories'
179    'lsnew' $'ls -rl *(D.om[1,10])\n# display the newest files'
180    'lsold' $'ls -rtlh *(D.om[-11,-1])\n # display the oldest files'
181    'lssmall' $'ls -Srl *(.oL[1,10])\n# display the smallest files'
182    'rw-' 'chmod 600'
183    '600' 'chmod u+rw-x,g-rwx,o-rwx'
184    'rwx' 'chmod u+rwx'
185    '700' 'chmod u+rwx,g-rwx,o-rwx'
186    'r--' 'chmod u+r-wx,g-rwx,o-rwx'
187    '644' $'chmod u+rw-x,g+r-wx,o+r-wx\n # 4=r,2=w,1=x'
188    '755' 'chmod u+rwx,g+r-w+x,o+r-w+x'
189    'md' 'mkdir -p '
190    'cmplayer' 'mplayer -vo -fs -zoom fbdev'
191    'fbmplayer' 'mplayer -vo -fs -zoom fbdev'
192    'fblinks' 'links2 -driver fb'
193    'insecssh' 'ssh -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile=/dev/null"'
194    'fori' 'for i ({..}) { }'
195    'cx' 'chmod +x'
196    'e'  'print -l'
197    'se' 'setopt interactivecomments'
198    'va' 'valac --vapidir=../vapi/ --pkg=gtk+-2.0 gtktest.vala'
199    'fb2' '=mplayer -vo fbdev -fs -zoom 1>/dev/null -xy 2'
200    'fb3' '=mplayer -vo fbdev -fs  -zoom 1>/dev/null -xy 3'
201    'ci' 'centericq'
202    'D'  'export DISPLAY=:0.0'
203    'mp' 'mplayer -vo xv -fs -zoom'
204   )
205
206   globalias () {
207         local MATCH
208         matched_chars='[.-|_a-zA-Z0-9]#'
209         LBUFFER=${LBUFFER%%(#m)[.-|_a-zA-Z0-9]#}
210         LBUFFER+=${abk[$MATCH]:-$MATCH}
211   }
212
213   zle -N globalias
214   bindkey ",." globalias
215 # }}}
216
217 # {{{ autoloading
218   autoload -U zmv    # who needs mmv or rename?
219   autoload history-search-end
220
221   # we don't want to quote/espace URLs on our own...
222   # avoid 'url-quote-magic: function definition file not found' on some older boxes
223   if [ -f "/usr/share/zsh/$ZSH_VERSION/functions/Zle/url-quote-magic" ] && \
224      autoload -U url-quote-magic && zle -N self-insert url-quote-magic ; then
225      zle -N self-insert url-quote-magic
226   else
227      print 'Notice: no url-quote-magic available :('
228   fi
229
230   alias run-help >&/dev/null && unalias run-help
231   autoload run-help # use via 'esc-h'
232
233 # completion system
234   if autoload -U compinit && [ -f "/usr/share/zsh/$ZSH_VERSION/functions/Completion/compinit" ] && compinit 2>/dev/null ; then
235     compinit
236    else
237      print 'Notice: no compinit available :('
238      function zstyle { }
239      function compdef { }
240   fi
241
242   is4 && autoload -U zed                  # use ZLE editor to edit a file or function
243
244   is4 && for mod in complist deltochar mathfunc ; do
245              zmodload -i zsh/${mod}
246          done
247
248 # autoload zsh modules when they are referenced
249   is4 && for opt mod in a  stat    \
250                         a  zpty    \
251                         a  zprof   \
252                         ap mapfile ; do
253              zmodload -${opt} zsh/${mod} ${mod}
254          done ; unset opt mod
255
256   is4 && autoload -U insert-files && \
257   zle -N insert-files && \
258   bindkey "^Xf" insert-files # C-x-f
259
260   bindkey ' '   magic-space    # also do history expansion on space
261   bindkey '\ei' menu-complete  # menu completion via esc-i
262
263 # press esc-e for editing command line in $EDITOR or $VISUAL
264   is4 && autoload -U edit-command-line && \
265   zle -N edit-command-line && \
266   bindkey '\ee' edit-command-line
267
268 # menu selection: pick item but stay in the menu (press esc-return)
269   is4 && bindkey -M menuselect '\e^M' accept-and-menu-complete
270
271 # press "ctrl-e d" to insert the actual date in the form yyyy-mm-dd
272   _bkdate() { BUFFER="$BUFFER$(date '+%F')"; CURSOR=$#BUFFER; }
273   bindkey '\C-ed' _bkdate
274   zle -N _bkdate
275
276 # press esc-m for inserting last typed word again (thanks to caphuso!)
277   insert-last-typed-word() { zle insert-last-word -- 0 -1 }; \
278   zle -N insert-last-typed-word; bindkey "\em" insert-last-typed-word
279
280 # set command prediction from history, see 'man 1 zshcontrib'
281 #  is4 && autoload -U predict-on && \
282 #  zle -N predict-on         && \
283 #  zle -N predict-off        && \
284 #  bindkey "^X^Z" predict-on && \
285 #  bindkey "^Z" predict-off
286
287 # put job into foreground via ctrl-z:
288   bindkey -s '^z' "fg\n"
289
290 # press ctrl-q to quote line:
291 #  mquote () {
292 #        zle beginning-of-line
293 #        zle forward-word
294 #        # RBUFFER="'$RBUFFER'"
295 #        RBUFFER=${(q)RBUFFER}
296 #        zle end-of-line
297 #  }
298 #  zle -N mquote && bindkey '^q' mquote
299
300 # run command line as user root via sudo:
301   _sudo-command-line() {
302     [[ $BUFFER != sudo\ * ]] && LBUFFER="sudo $LBUFFER"
303   }
304   zle -N sudo-command-line _sudo-command-line
305   bindkey "^Os" sudo-command-line
306 # }}}
307
308 # {{{ set some important options
309   umask 022
310
311 # history:
312   setopt append_history       # append history list to the history file (important for multiple parallel zsh sessions!)
313   is4 && setopt SHARE_HISTORY # import new commands from the history file also in other zsh-session
314   setopt extended_history     # save each command's beginning timestamp and the duration to the history file
315   is4 && setopt histignorealldups # If  a  new  command  line being added to the history
316                               # list duplicates an older one, the older command is removed from the list
317   setopt histignorespace      # remove command lines from the history list when
318                               # the first character on the line is a space
319 #  setopt histallowclobber    # add `|' to output redirections in the history
320 #  setopt NO_clobber          # warning if file exists ('cat /dev/null > ~/.zshrc')
321   setopt auto_cd              # if a command is issued that can't be executed as a normal command,
322                               # and the command is the name of a directory, perform the cd command to that directory
323   setopt extended_glob        # in order to use #, ~ and ^ for filename generation
324                               # grep word *~(*.gz|*.bz|*.bz2|*.zip|*.Z) ->
325                               # -> searches for word not in compressed files
326                               # don't forget to quote '^', '~' and '#'!
327   setopt notify               # report the status of backgrounds jobs immediately
328   setopt hash_list_all        # Whenever a command completion is attempted, make sure \
329                               # the entire command path is hashed first.
330   setopt completeinword       # not just at the end
331 # setopt nocheckjobs          # don't warn me about bg processes when exiting
332   setopt nohup                # and don't kill them, either
333 # setopt printexitvalue       # alert me if something failed
334 # setopt dvorak               # with spelling correction, assume dvorak kb
335   setopt auto_pushd           # make cd push the old directory onto the directory stack.
336   setopt nonomatch            # try to avoid the 'zsh: no matches found...'
337   setopt nobeep               # avoid "beep"ing
338
339   MAILCHECK=30       # mailchecks
340   REPORTTIME=5       # report about cpu-/system-/user-time of command if running longer than 5 secondes
341   watch=(notme root) # watch for everyone but me and root
342
343 # define word separators (for stuff like backward-word, forward-word, backward-kill-word,..)
344 #  WORDCHARS='*?_-.[]~=/&;!#$%^(){}<>' # the default
345 #  WORDCHARS=.
346 #  WORDCHARS='*?_[]~=&;!#$%^(){}'
347 #  WORDCHARS='${WORDCHARS:s@/@}'
348
349 # only slash should be considered as a word separator:
350   slash-backward-kill-word() {
351     local WORDCHARS="${WORDCHARS:s@/@}"
352     # zle backward-word
353     zle backward-kill-word
354   }
355   zle -N slash-backward-kill-word
356   bindkey '\ev' slash-backward-kill-word # press esc-v to delete a word until its last '/' (not the same as ctrl-w!)
357 # }}}
358
359 # {{{ history
360   export ZSHDIR=$HOME/.zsh
361   HISTFILE=$HOME/.zsh_history
362   isgrmlcd && HISTSIZE=500  || HISTSIZE=5000
363   isgrmlcd && SAVEHIST=1000 || SAVEHIST=10000 # useful for setopt append_history
364 # }}}
365
366 # {{{ display battery status on right side of prompt via running 'BATTERY=1 zsh'
367   if [ -n "$BATTERY" ] ; then
368      if [ -x =acpi ] ; then
369         PERCENT="${(C)${(s| |)$(acpi 2>/dev/null)}[4]}"
370         [ -z "$PERCENT" ] && PERCENT='acpi not present'
371         if [ "${PERCENT%%%}" -lt 20 ] ; then
372            PERCENT="warning: ${PERCENT}%"
373         fi
374      fi
375   fi
376 # }}}
377
378 # {{{ set prompt
379   if [ -f "/usr/share/zsh/$ZSH_VERSION/functions/Prompts/promptinit" ] && autoload promptinit && promptinit 2>/dev/null ; then
380      promptinit # people should be able to use their favourite prompt
381   else
382      print 'Notice: no promptinit available :('
383   fi
384
385 # precmd() => a function which is executed just before each prompt
386 # use 'NOPRECMD=1' to disable the precmd + preexec commands
387
388   # precmd () { setopt promptsubst; [[ -o interactive ]] && jobs -l;
389
390   is4 && ! [[ -n "$NOPRECMD" ]] && precmd () {
391       (( NOPRECMD > 0 )) && return 0
392       # just use DONTSETRPROMPT=1 to be able to overwrite RPROMPT
393       if [[ -z ${DONTSETRPROMPT} ]] ; then
394         if [ -n "$BATTERY" ] ; then
395           # RPROMPT="%(?..:()% ${PERCENT}${SCREENTITLE}"
396           RPROMPT="${PERCENT}${SCREENTITLE}"
397         else
398           # RPROMPT="%(?..:()% ${SCREENTITLE}"
399           RPROMPT="${SCREENTITLE}"
400         fi
401       fi
402       # adjust title of xterm
403       # see http://www.faqs.org/docs/Linux-mini/Xterm-Title.html
404       case $TERM in (xterm*|rxvt)
405         print -Pn "\e]0;%n@%m: %~\a"
406         ;;
407       esac
408   }
409
410 # chpwd () => a function which is executed whenever the directory is changed
411
412 # preexec() => a function running before every command
413   is4 && ! [[ -n "$NOPRECMD" ]] && preexec () {
414       (( NOPRECMD > 0 )) && return 0
415   # set hostname if not running on host with name 'grml'
416       local HOSTNAME=$(hostname)
417       if [[ "$HOSTNAME" != grml ]] ; then
418          NAME="@$HOSTNAME"
419       fi
420   # get the name of the program currently running and hostname of local machine
421   # set screen window title if running in a screen
422       if [[ "$TERM" == screen* ]]; then
423           # local CMD=${1[(wr)^(*=*|sudo|ssh|-*)]}       # dont't use hostname
424           local CMD="${1[(wr)^(*=*|sudo|ssh|-*)]}$NAME" # use hostname
425           echo -ne "\ek$CMD\e\\"
426       fi
427   # set the screen title to "zsh" when sitting at the command prompt:
428       if [[ "$TERM" == screen* ]]; then
429            SCREENTITLE=$'%{\ekzsh\e\\%}'
430       else
431            SCREENTITLE=''
432       fi
433   # adjust title of xterm
434       case $TERM in (xterm*|rxvt)
435         print -Pn "\e]0;%n@%m: $1\a"
436         ;;
437       esac
438   }
439
440 # set colors
441   if autoload colors && colors 2>/dev/null ; then
442      BLUE="%{${fg[blue]}%}"
443      RED="%{${fg_bold[red]}%}"
444      GREEN="%{${fg[green]}%}"
445      CYAN="%{${fg[cyan]}%}"
446      WHITE="%{${fg[white]}%}"
447      NO_COLOUR="%{${reset_color}%}"
448   else
449      BLUE="%{\e[1;34m%}"
450      RED="%{\e[1;31m%}"
451      GREEN="%{\e[1;32m%}"
452      CYAN="%{\e[1;36m%}"
453      WHITE="%{\e[1;37m%}"
454      NO_COLOUR="%{\e[0m%}"
455   fi
456
457   EXITCODE="%(?..%?%1v )"
458   PS2='`%_> '       # secondary prompt, printed when the shell needs more information to complete a command.
459   PS3='?# '         # selection prompt used within a select loop.
460   PS4='+%N:%i:%_> ' # the execution trace prompt (setopt xtrace). default: '+%N:%i>'
461
462   # set variable debian_chroot if running in a chroot with /etc/debian_chroot
463   if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
464     debian_chroot=$(cat /etc/debian_chroot)
465   fi
466
467   # don't use colors on dumb terminals (like emacs):
468   if [[ "$TERM" == dumb ]] ; then
469     PROMPT="${EXITCODE}${debian_chroot:+($debian_chroot)}%n@%m %40<...<%B%~%b%<< %# "
470   else
471     # only if $GRMLPROMPT is set (e.g. via 'GRMLPROMPT=1 zsh') use the extended prompt
472     # set variable identifying the chroot you work in (used in the prompt below)
473     if [[ -n "$GRMLPROMPT" ]]; then
474       PROMPT="${RED}${EXITCODE}${CYAN}[%j running job(s)] ${GREEN}{history#%!} ${RED}%(3L.+.) ${BLUE}%* %D
475 ${BLUE}%n${NO_COLOUR}@%m %40<...<%B%~%b%<< %# "
476     else
477       if (( EUID != 0 )); then
478         PROMPT="${RED}${EXITCODE}${WHITE}${debian_chroot:+($debian_chroot)}${BLUE}%n${NO_COLOUR}@%m %40<...<%B%~%b%<< %# " # primary prompt string
479       else
480         PROMPT="${BLUE}${EXITCODE}${WHITE}${debian_chroot:+($debian_chroot)}${RED}%n${NO_COLOUR}@%m %40<...<%B%~%b%<< %# " # primary prompt string
481       fi
482     fi
483   fi
484
485   # if we are inside a grml-chroot set a specific prompt theme
486   if [ -n "$GRML_CHROOT" ] ; then
487      PROMPT="%{$fg[red]%}(CHROOT) %{$fg_bold[red]%}%n%{$fg_no_bold[white]%}@%m %40<...<%B%~%b%<< %\# "
488   fi
489 # }}}
490
491 # {{{ 'hash' some often used directories
492   hash -d deb=/var/cache/apt/archives
493   hash -d doc=/usr/share/doc
494   hash -d linux=/lib/modules/$(command uname -r)/build/
495   hash -d log=/var/log
496   hash -d slog=/var/log/syslog
497   hash -d src=/usr/src
498   hash -d templ=/usr/share/doc/grml-templates
499   hash -d tt=/usr/share/doc/texttools-doc
500   hash -d www=/var/www
501 # }}}
502
503 # {{{ some aliases
504   if [ $UID = 0 ] ; then
505      [ -r /etc/grml/screenrc ] && alias screen='/usr/bin/screen -c /etc/grml/screenrc'
506   elif [ -r $HOME/.screenrc ] ; then
507      alias screen="/usr/bin/screen -c $HOME/.screenrc"
508   else
509      [ -r /etc/grml/screenrc_grml ] && alias screen='/usr/bin/screen -c /etc/grml/screenrc_grml'
510   fi
511
512   if ls --help 2>/dev/null |grep -- --color= >/dev/null && [ "$TERM" != dumb ] ; then
513      alias ls='ls -b -CF --color=auto' # do we have GNU ls with color-support?
514      alias la='ls -la --color=auto'
515      alias ll='ls -l --color=auto'
516      alias lh='ls -hAl --color=auto'
517      alias l='ls -lF --color=auto'
518   else
519      alias ls='ls -b -CF'
520      alias la='ls -la'
521      alias ll='ls -l'
522      alias lh='ls -hAl'
523      alias l='ls -lF'
524   fi
525
526   alias cp='nocorrect cp'         # no spelling correction on cp
527   alias mkdir='nocorrect mkdir'   # no spelling correction on mkdir
528   alias mv='nocorrect mv'         # no spelling correction on mv
529   alias rm='nocorrect rm'         # no spelling correction on rm
530
531   alias rd='rmdir'
532   alias md='mkdir'
533
534   alias swspeak="setopt singlelinezle ; unsetopt prompt_cr ; export PS1='%m%# ' ; speechd-up" # set up software synth.
535
536 # truecrypt; use e.g. via 'truec /dev/ice' /mnt/ice' or 'truec -i'
537   if [ -x /usr/sbin/truecrypt ] ; then
538      alias truec='truecrypt --mount-options "rw,sync,dirsync,users,uid=1000,gid=users,umask=077" '
539   fi
540
541   zsh-help(){print "$bg[white]$fg[black]
542 zsh-help - hints for use of zsh on grml
543 =======================================$reset_color
544
545 Main configuration of zsh happens in /etc/zsh/zshrc (global)
546 and /etc/skel/.zshrc which is copied to \$HOME/.zshrc once.
547 The files are part of the package grml-etc-core, if you want to
548 use them on a non-grml-system just get the tar.gz from
549 http://grml.org/repos/ or get the files from the mercurial
550 repository:
551
552   http://hg.grml.org/grml-etc-core/raw-file/tip/etc/skel/.zshrc
553   http://hg.grml.org/grml-etc-core/raw-file/tip/etc/zsh/zshrc
554
555 If you want to stay in sync with zsh configuration of grml
556 run 'ln -sf /etc/skel/.zshrc \$HOME/.zshrc' and configure
557 your own stuff in \$HOME/.zshrc.local. System wide configuration
558 without touching configuration files of grml can take place
559 in /etc/zsh/zshrc.local.
560
561 If you want to use the configuration of user grml also when
562 running as user root just run 'zshskel' which will source
563 the file /etc/skel/.zshrc.
564
565 For information regarding zsh start at http://grml.org/zsh/
566
567 Take a look at grml's zsh refcard:
568 % xpdf =(zcat /usr/share/doc/grml-docs/zsh/grml-zsh-refcard.pdf.gz)
569
570 Check out the main zsh refcard:
571 % $BROWSER http://www.bash2zsh.com/zsh_refcard/refcard.pdf
572
573 And of course visit the zsh-lovers:
574 % man zsh-lovers
575
576 You can adjust some options through environment variables when
577 invoking zsh without having to edit configuration files.
578 Basically meant for bash users who are not used to the power of
579 the zsh yet. :)
580
581   \"NOCOR=1    zsh\" => deactivate automatic correction
582   \"NOMENU=1   zsh\" => do not use menu completion (note: use strg-d for completion instead!)
583   \"NOPRECMD=1 zsh\" => disable the precmd + preexec commands (set GNU screen title)
584   \"BATTERY=1  zsh\" => activate battery status (via acpi) on right side of prompt
585 $bg[white]$fg[black]
586 Please report wishes + bugs to the grml-team: http://grml.org/bugs/
587 Enjoy your grml system with the zsh!$reset_color"
588 }
589
590 # debian stuff
591   if [ -r /etc/debian_version ] ; then
592     alias acs='apt-cache search'
593     alias acsh='apt-cache show'
594     alias acp='apt-cache policy'
595     alias adg="$SUDO apt-get dist-upgrade"
596     alias agi="$SUDO apt-get install"
597     alias ag="$SUDO apt-get upgrade"
598     alias au="$SUDO apt-get update"
599     alias dbp='dpkg-buildpackage'
600     alias ge='grep-excuses'
601
602     # debian upgrade
603     upgrade () {
604       if [ -z "$1" ] ; then
605           $SUDO apt-get update
606           $SUDO apt-get -u upgrade
607       else
608           ssh $1 $SUDO apt-get update
609           # ask before the upgrade
610           local dummy
611           ssh $1 $SUDO apt-get --no-act upgrade
612           echo -n 'Process the upgrade?'
613           read -q dummy
614           if [[ $dummy == "y" ]] ; then
615               ssh $1 $SUDO apt-get -u upgrade --yes
616           fi
617       fi
618     }
619
620     isgrmlcd && alias su="sudo su"          # change to user root
621     alias tlog="tail -f /var/log/syslog"    # take a look at the syslog
622     alias zshskel="source /etc/skel/.zshrc" # source skeleton zshrc
623   fi
624
625 # if cdrecord is a symlink (to wodim) or isn't present at all warn:
626   if [ -L /usr/bin/cdrecord -o ! -x =cdrecord ] ; then
627      if [ -x =wodim ] ; then
628         alias cdrecord="echo 'cdrecord is not provided under its original name by Debian anymore.
629 See #377109 in the BTS of Debian for more details.
630
631 Please use the wodim binary instead' ; return 1"
632      fi
633   fi
634
635 # }}}
636
637 # {{{ Use hard limits, except for a smaller stack and no core dumps
638   unlimit
639   limit stack 8192
640   isgrmlcd && limit core 0 # important for a live-cd-system
641   limit -s
642 # }}}
643
644 # {{{ completion stuff
645
646 # Where to look for autoloaded function definitions
647   if [ -d /etc/zsh/completion.d ] ; then
648     local comp=/etc/zsh/completion.d
649     for func in $comp/*(N-.:t); . ${comp}/${func}
650   fi
651
652 # called later (via is4 && grmlcomp)
653 # notice: use 'zstyle' for getting current settings
654 #         press ^Xh (control-x h) for getting tags in context; ^X? (control-x ?) to run complete_debug with trace output
655 grmlcomp() {
656 ## completion system
657   zstyle ':completion:*:approximate:'    max-errors 'reply=( $((($#PREFIX+$#SUFFIX)/3 )) numeric )' # allow one error for every three characters typed in approximate completer
658   zstyle ':completion:*:complete:-command-::commands' ignored-patterns '*\~' # don't complete backup files as executables
659   zstyle ':completion:*:correct:*'       insert-unambiguous true             # start menu completion only if it could find no unambiguous initial string
660   zstyle ':completion:*:corrections'     format $'%{\e[0;31m%}%d (errors: %e)%{\e[0m%}' #
661   zstyle ':completion:*:correct:*'       original true                       #
662   zstyle ':completion:*:default'         list-colors ${(s.:.)LS_COLORS}      # activate color-completion(!)
663   zstyle ':completion:*:descriptions'    format $'%{\e[0;31m%}completing %B%d%b%{\e[0m%}'  # format on completion
664   zstyle ':completion:*:*:cd:*:directory-stack' menu yes select              # complete 'cd -<tab>' with menu
665   zstyle ':completion:*:expand:*'        tag-order all-expansions            # insert all expansions for expand completer
666   zstyle ':completion:*:history-words'   list false                          #
667   zstyle ':completion:*:history-words'   menu yes                            # activate menu
668   zstyle ':completion:*:history-words'   remove-all-dups yes                 # ignore duplicate entries
669   zstyle ':completion:*:history-words'   stop yes                            #
670   zstyle ':completion:*:*:linda:*'       file-patterns '*.deb'               # complete debian packages for command 'linda'
671   zstyle ':completion:*:*:lintian:*'     file-patterns '*.deb'               # complete debian packages for command 'lintian'
672   zstyle ':completion:*'                 matcher-list 'm:{a-z}={A-Z}'        # match uppercase from lowercase
673   zstyle ':completion:*:matches'         group 'yes'                         # separate matches into groups
674   zstyle ':completion:*'                 group-name ''
675   if [[ -z "$NOMENU" ]] ; then
676     zstyle ':completion:*'               menu select=5                       # if there are more than 5 options allow selecting from a menu
677   else
678     setopt no_auto_menu # don't use any menus at all
679   fi
680   zstyle ':completion:*:messages'        format '%d'                         #
681   zstyle ':completion:*:options'         auto-description '%d'               #
682   zstyle ':completion:*:options'         description 'yes'                   # describe options in full
683   zstyle ':completion:*:processes'       command 'ps -au$USER'               # on processes completion complete all user processes
684   zstyle ':completion:*:*:-subscript-:*' tag-order indexes parameters        # offer indexes before parameters in subscripts
685   zstyle ':completion:*'                 verbose true                        # provide verbose completion information
686   zstyle ':completion:*:warnings'        format $'%{\e[0;31m%}No matches for:%{\e[0m%} %d' # set format for warnings
687   zstyle ':completion:*:*:zcompile:*'    ignored-patterns '(*~|*.zwc)'       # define files to ignore for zcompile
688   zstyle ':completion:correct:'          prompt 'correct to: %e'             #
689   zstyle ':completion::(^approximate*):*:functions' ignored-patterns '_*'    # Ignore completion functions for commands you don't have:
690
691 # complete manual by their section
692   zstyle ':completion:*:manuals'    separate-sections true
693   zstyle ':completion:*:manuals.*'  insert-sections   true
694   zstyle ':completion:*:man:*'      menu yes select
695
696 ## correction
697 # run rehash on completion so new installed program are found automatically:
698   _force_rehash() {
699       (( CURRENT == 1 )) && rehash
700          return 1 # Because we didn't really complete anything
701     }
702 # some people don't like the automatic correction - so run 'NOCOR=1 zsh' to deactivate it
703   if [[ -n "$NOCOR" ]] ; then
704     zstyle ':completion:*' completer _oldlist _expand _force_rehash _complete
705     setopt nocorrect # do not try to correct the spelling if possible
706   else
707 #    zstyle ':completion:*' completer _oldlist _expand _force_rehash _complete _correct _approximate
708     setopt correct  # try to correct the spelling if possible
709     zstyle -e ':completion:*' completer '
710         if [[ $_last_try != "$HISTNO$BUFFER$CURSOR" ]]; then
711           _last_try="$HISTNO$BUFFER$CURSOR"
712           reply=(_complete _match _prefix)
713         else
714           if [[ $words[1] = (rm|mv) ]]; then
715             reply=(_complete)
716           else
717             reply=(_oldlist _expand _force_rehash _complete _correct _approximate)
718           fi
719         fi'
720   fi
721 # zstyle ':completion:*' completer _complete _correct _approximate
722 # zstyle ':completion:*' expand prefix suffix
723
724 # automatic rehash? Credits go to Frank Terbeck
725 # function my_accept () {
726 #   local buf
727 #   [[ -z ${BUFFER} ]] && zle accept-line && return
728 #   buf=( ${(z)BUFFER}  )
729 #   [[ -z ${commands[${buf[1]}]} ]] && rehash
730 #   zle accept-line
731 # }
732 # zle -N my_accept
733 # bindkey "^M" my_accept
734
735 # command for process lists, the local web server details and host completion
736   hosts=(`hostname` grml.org)
737   zstyle '*' hosts $hosts
738   zstyle ':completion:*:urls' local 'www' '/var/www/' 'public_html'
739
740 # caching
741   [ -d $ZSHDIR/cache ] && zstyle ':completion:*' use-cache yes && \
742                           zstyle ':completion::complete:*' cache-path $ZSHDIR/cache/
743
744 # use ~/.ssh/known_hosts for completion [does not work with hashing of new ssh versions anymore]
745   if [ -f "$HOME/.ssh/known_hosts" ] ; then
746     hosts=(${${${${(f)"$(<$HOME/.ssh/known_hosts)"}:#[\|]*}%%\ *}%%,*})
747     zstyle ':completion:*:hosts' hosts $hosts
748   fi
749
750 # use generic completion system for programs not yet defined:
751   compdef _gnu_generic tail head feh cp mv gpg df stow uname ipacsum fetchipac
752
753 # see upgrade function in this file
754   compdef _hosts upgrade
755 }
756 # }}}
757
758 # {{{ grmlstuff
759 grmlstuff() {
760 # people should use 'grml-x'!
761   function startx() {
762     if [ -e /etc/X11/xorg.conf ] ; then
763        [ -x /usr/bin/startx ] && /usr/bin/startx || /usr/X11R6/bin/startx
764     else
765       echo "Please use the script \"grml-x\" for starting the X Window System
766 because there does not exist /etc/X11/xorg.conf yet.
767 If you want to use startx anyway please call \"/usr/bin/startx\"."
768       return -1
769     fi
770   }
771
772   function xinit() {
773     if [ -e /etc/X11/xorg.conf ] ; then
774        [ -x /usr/bin/xinit ] && /usr/bin/xinit || /usr/X11R6/bin/xinit
775     else
776       echo "Please use the script \"grml-x\" for starting the X Window System.
777 because there does not exist /etc/X11/xorg.conf yet.
778 If you want to use xinit anyway please call \"/usr/bin/xinit\"."
779       return -1
780     fi
781   }
782
783   if [ -x /usr/sbin/915resolution ] ; then
784      alias 855resolution='echo -e "Please use 915resolution as resolution modify tool for Intel graphic chipset."; return -1'
785   fi
786
787   alias grml-version='cat /etc/grml_version'
788
789   if [ -x /usr/sbin/rebuildfstab ] ; then
790      alias grml-rebuildfstab='rebuildfstab -v -r -config'
791   fi
792 }
793 # }}}
794
795 # {{{ now run the functions
796   isgrml && checkhome
797   is4    && isgrml    && grmlstuff
798   is4    && grmlcomp
799 # }}}
800
801 # {{{ keephack
802   [ -r /etc/zsh/keephack ] && is4 && source /etc/zsh/keephack
803 # }}}
804
805 # {{{ wonderful idea of using "e" glob qualifier by Peter Stephenson
806 # You use it as follows:
807 # $ NTREF=/reference/file
808 # $ ls -l *(e:nt:)
809 # This lists all the files in the current directory newer than the reference file.
810 # You can also specify the reference file inline; note quotes:
811 # $ ls -l *(e:'nt ~/.zshenv':)
812   is4 && nt() {
813     if [[ -n $1 ]]; then
814       local NTREF=${~1}
815     fi
816     [[ $REPLY -nt $NTREF ]]
817   }
818 # }}}
819
820 # shell functions {{{
821   setenv()  { typeset -x "${1}${1:+=}${(@)argv[2,$#]}" }  # csh compatibility
822   freload() { while (( $# )); do; unfunction $1; autoload -U $1; shift; done }
823   manzsh()  {  /usr/bin/man zshall |  vim -c "se ft=man| se hlsearch" +/"$1" - ; }
824 #  manzsh()  { /usr/bin/man zshall |  most +/"$1" ; }
825 #  manzsh()  { man zshall | $MYLESS -p $1 ; }
826
827 # use "dchange <package-name>" to view Debian's changelog of the package:
828   dchange() {
829     if [ -r /usr/share/doc/${1}/changelog.Debian.gz ] ; then
830        most /usr/share/doc/${1}/changelog.Debian.gz
831     else
832        if [ -r /usr/share/doc/${1}/changelog.gz ] ; then
833           most /usr/share/doc/${1}/changelog.gz
834        else
835           echo "No changelog for package $1 found, sorry."
836           return 1
837        fi
838     fi
839   }
840   _dchange() { _files -W /usr/share/doc -/ }
841   compdef _dchange dchange
842
843 # use "uchange <package-name>" to view upstream's changelog of the package:
844   uchange() {
845     if [ -r /usr/share/doc/${1}/changelog.gz ] ; then
846        most /usr/share/doc/${1}/changelog.gz
847     else
848        echo "No changelog for package $1 found, sorry."
849        return 1
850     fi
851   }
852   _uchange() { _files -W /usr/share/doc -/ }
853   compdef _uchange uchange
854
855 # edit alias via zle:
856   edalias() {
857     [ -z "$1" ] && { echo "Usage: edalias <alias_to_edit>" ; return 1 } || vared aliases'[$1]' ;
858   }
859   compdef _aliases edalias
860
861 # edit function via zle:
862   edfun() {
863     [ -z "$1" ] && { echo "Usage: edfun <function_to_edit>" ; return 1 } || zed -f "$1" ;
864   }
865   compdef _functions edfun
866
867 # use it e.g. via 'Restart apache2'
868  if [ -d /etc/init.d ] ; then
869   for i in Start Restart Stop Force-Reload Reload ; do
870     eval "$i() { $SUDO /etc/init.d/\$1 ${i:l} \$2 ; }"
871   done
872   # now the completion for this:
873   compctl -g "$(echo /etc/init.d/*(:t))" Start Restart Stop Force-Reload Reload
874  fi
875
876 # provide useful information on globbing
877   H-Glob() {
878   echo -e "
879       /      directories
880       .      plain files
881       @      symbolic links
882       =      sockets
883       p      named pipes (FIFOs)
884       *      executable plain files (0100)
885       %      device files (character or block special)
886       %b     block special files
887       %c     character special files
888       r      owner-readable files (0400)
889       w      owner-writable files (0200)
890       x      owner-executable files (0100)
891       A      group-readable files (0040)
892       I      group-writable files (0020)
893       E      group-executable files (0010)
894       R      world-readable files (0004)
895       W      world-writable files (0002)
896       X      world-executable files (0001)
897       s      setuid files (04000)
898       S      setgid files (02000)
899       t      files with the sticky bit (01000)
900
901    print *(m-1)          # Files modified up to a day ago
902    print *(a1)           # Files accessed a day ago
903    print *(@)            # Just symlinks
904    print *(Lk+50)        # Files bigger than 50 kilobytes
905    print *(Lk-50)        # Files smaller than 50 kilobytes
906    print **/*.c          # All *.c files recursively starting in \$PWD
907    print **/*.c~file.c   # Same as above, but excluding 'file.c'
908    print (foo|bar).*     # Files starting with 'foo' or 'bar'
909    print *~*.*           # All Files that do not contain a dot
910    chmod 644 *(.^x)      # make all plain non-executable files publically readable
911    print -l *(.c|.h)     # Lists *.c and *.h
912    print **/*(g:users:)  # Recursively match all files that are owned by group 'users'
913    echo /proc/*/cwd(:h:t:s/self//) # Analogous to >ps ax | awk '{print $1}'<"
914   }
915   alias help-zshglob=H-Glob
916
917   type -p fma &>/dev/null && alias ?='fma zshall'
918
919 # }}}
920
921 # {{{ make sure our environment is clean regarding colors
922   for color in BLUE RED GREEN CYAN WHITE ; unset $color
923 # }}}
924
925 # source another config file if present {{{
926   if [ -r /etc/zsh/zshrc.local ]; then
927    source /etc/zsh/zshrc.local
928   fi
929 # }}}
930
931 # "persistent history" {{{
932 # just write important commands you always need to ~/.important_commands
933   if [ -r ~/.important_commands ] ; then
934      fc -R ~/.important_commands
935   fi
936 # }}}
937
938 ## END OF FILE #################################################################
939 # vim:foldmethod=marker