* /etc/zsh/zshrc: added isgrmlsmall() and set $EDITOR
[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: Mit Okt 25 23:44:27 CEST 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 ; 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   isgrmlsmall() {
43     [[ ${${${(f)"$(</etc/grml_version)"}%% *}##*-} == 'small' ]] && return 0 ; return 1
44   }
45
46 # check for user, if not running as root set $SUDO to sudo
47  (( EUID != 0 )) && SUDO='sudo' || SUDO=''
48
49 # change directory to home on first invocation of zsh
50 # important for rungetty -> autologin
51 # Thanks go to Bart Schaefer!
52   isgrml && checkhome() {
53   if [[ -z "$ALREADY_DID_CD_HOME" ]]; then
54      export ALREADY_DID_CD_HOME=$HOME
55      cd
56   fi
57   }
58 # }}}
59
60 # {{{ set some variables
61   isgrmlsmall && export EDITOR=${EDITOR:-vi} || export EDITOR=${EDITOR:-vim}
62   export MAIL=${MAIL:-/var/mail/$USER}
63   [[ -f ~/.terminfo/m/mostlike ]] && MYLESS='LESS=C TERMINFO=~/.terminfo TERM=mostlike less' || MYLESS='less'
64   [[ -x /usr/bin/dircolors ]] && eval `dircolors -b`
65
66 # Search path for the cd comman
67 #  cdpath=(.. ~)
68
69 # Support our own site-functions
70   [ -d /etc/zsh/site-functions ] && export FPATH=/etc/zsh/site-functions:$FPATH
71
72 # automatically remove duplicates from these arrays
73   typeset -U path cdpath fpath manpath
74 # }}}
75
76 # {{{ keybindings
77  if [[ "$TERM" != emacs ]]; then
78   [[ -z "$terminfo[kdch1]" ]] || bindkey -M emacs "$terminfo[kdch1]" delete-char
79   [[ -z "$terminfo[khome]" ]] || bindkey -M emacs "$terminfo[khome]" beginning-of-line
80   [[ -z "$terminfo[kend]"  ]] || bindkey -M emacs "$terminfo[kend]"  end-of-line
81   [[ -z "$terminfo[kdch1]" ]] || bindkey -M vicmd "$terminfo[kdch1]" vi-delete-char
82   [[ -z "$terminfo[khome]" ]] || bindkey -M vicmd "$terminfo[khome]" vi-beginning-of-line
83   [[ -z "$terminfo[kend]"  ]] || bindkey -M vicmd "$terminfo[kend]"  vi-end-of-line
84   [[ -z "$terminfo[cuu1]"  ]] || bindkey -M viins "$terminfo[cuu1]"  vi-up-line-or-history
85   [[ -z "$terminfo[cuf1]"  ]] || bindkey -M viins "$terminfo[cuf1]"  vi-forward-char
86   [[ -z "$terminfo[kcuu1]" ]] || bindkey -M viins "$terminfo[kcuu1]" vi-up-line-or-history
87   [[ -z "$terminfo[kcud1]" ]] || bindkey -M viins "$terminfo[kcud1]" vi-down-line-or-history
88   [[ -z "$terminfo[kcuf1]" ]] || bindkey -M viins "$terminfo[kcuf1]" vi-forward-char
89   [[ -z "$terminfo[kcub1]" ]] || bindkey -M viins "$terminfo[kcub1]" vi-backward-char
90   # ncurses stuff:
91   [[ "$terminfo[kcuu1]" == "\eO"* ]] && bindkey -M viins "${terminfo[kcuu1]/O/[}" vi-up-line-or-history
92   [[ "$terminfo[kcud1]" == "\eO"* ]] && bindkey -M viins "${terminfo[kcud1]/O/[}" vi-down-line-or-history
93   [[ "$terminfo[kcuf1]" == "\eO"* ]] && bindkey -M viins "${terminfo[kcuf1]/O/[}" vi-forward-char
94   [[ "$terminfo[kcub1]" == "\eO"* ]] && bindkey -M viins "${terminfo[kcub1]/O/[}" vi-backward-char
95   [[ "$terminfo[khome]" == "\eO"* ]] && bindkey -M viins "${terminfo[khome]/O/[}" beginning-of-line
96   [[ "$terminfo[kend]"  == "\eO"* ]] && bindkey -M viins "${terminfo[kend]/O/[}"  end-of-line
97   [[ "$terminfo[khome]" == "\eO"* ]] && bindkey -M emacs "${terminfo[khome]/O/[}" beginning-of-line
98   [[ "$terminfo[kend]"  == "\eO"* ]] && bindkey -M emacs "${terminfo[kend]/O/[}"  end-of-line
99 fi
100
101 ## keybindings (run 'bindkeys' for details, more details via man zshzle)
102 # use emacs style per default
103   bindkey -e
104 # use vi style:
105 # bindkey -v
106
107 #if [[ "$TERM" == screen ]]; then
108   bindkey '\e[1~' beginning-of-line       # home
109   bindkey '\e[4~' end-of-line             # end
110   bindkey "^[[A"  up-line-or-search       # cursor up
111   bindkey "^[[B"  down-line-or-search     # <ESC>-
112   bindkey '^x'    history-beginning-search-backward # alternative ways of searching the shell history
113 # bindkey -s '^L' "|less\n"             # ctrl-L pipes to less
114 # bindkey -s '^B' " &\n"                # ctrl-B runs it in the background
115 # if terminal type is set to 'rxvt':
116   bindkey '\e[7~' beginning-of-line       # home
117   bindkey '\e[8~' end-of-line             # end
118 #fi
119
120 #  bindkey '\eq' push-line-or-edit
121 # }}}
122
123 # {{{ autoloading
124   autoload -U zmv    # who needs mmv or rename?
125   autoload history-search-end
126
127   # we don't want to quote/espace URLs on our own...
128   # avoid 'url-quote-magic: function definition file not found' on some older boxes
129   if [ -f "/usr/share/zsh/$ZSH_VERSION/functions/Zle/url-quote-magic" ] ; then
130      autoload -U url-quote-magic && zle -N self-insert url-quote-magic
131   else
132      print 'Notice: no url-quote-magic available :('
133   fi
134
135   alias run-help >&/dev/null && unalias run-help
136   autoload run-help # use via 'esc-h'
137
138 # completion system
139   is42 && if autoload -U compinit && [ -f "/usr/share/zsh/$ZSH_VERSION/functions/Completion/compinit" ] ; then
140     compinit
141    else
142      print 'Notice: no compinit available :('
143      function zstyle { }
144      function compdef { }
145   fi
146   is4 && autoload -U zed                  # use ZLE editor to edit a file or function
147
148   is4 && \
149   for mod in complist deltochar mathfunc ; do
150     zmodload -i zsh/${mod}
151   done
152 # autoload zsh modules when they are referenced
153   is4 && \
154   for opt mod in a  stat    \
155                  a  zpty    \
156                  a  zprof   \
157                  ap mapfile ; do
158     zmodload -${opt} zsh/${mod} ${mod}
159   done
160   unset opt mod
161
162   is4 && autoload -U insert-files && \
163   zle -N insert-files && \
164   bindkey "^Xf" insert-files # C-x-f
165
166   bindkey ' '   magic-space    # also do history expansion on space
167   bindkey '\ei' menu-complete  # menu completion via esc-i
168
169 # press esc-e for editing command line in $EDITOR or $VISUAL
170   is4 && autoload -U edit-command-line && \
171   zle -N edit-command-line && \
172   bindkey '\ee' edit-command-line
173
174 ## menu selection: pick item but stay in the menu (press esc-return)
175   is4 && bindkey -M menuselect '\e^M' accept-and-menu-complete
176
177 # press "ctrl-e d" to insert the actual date in the form yyyy-mm-dd
178   _bkdate() { BUFFER="$BUFFER$(date '+%F')"; CURSOR=$#BUFFER; }
179   bindkey '\C-ed' _bkdate
180   zle -N _bkdate
181
182 # press esc-m for inserting last typed word again (thanks to caphuso!)
183   insert-last-typed-word() { zle insert-last-word -- 0 -1 }; \
184   zle -N insert-last-typed-word; bindkey "\em" insert-last-typed-word
185
186 # set command prediction from history, see 'man 1 zshcontrib'
187 #  is4 && autoload -U predict-on && \
188 #  zle -N predict-on         && \
189 #  zle -N predict-off        && \
190 #  bindkey "^X^Z" predict-on && \
191 #  bindkey "^Z" predict-off
192
193 # put job into foreground via ctrl-z:
194   bindkey -s '^z' "fg\n"
195
196 # press ctrl-q to quote line:
197 #  mquote () {
198 #        zle beginning-of-line
199 #        zle forward-word
200 #        # RBUFFER="'$RBUFFER'"
201 #        RBUFFER=${(q)RBUFFER}
202 #        zle end-of-line
203 #  }
204 #  zle -N mquote && bindkey '^q' mquote
205
206 # run command line as user root via sudo:
207   _sudo-command-line() {
208     [[ $BUFFER != sudo\ * ]] && LBUFFER="sudo $LBUFFER"
209   }
210   zle -N sudo-command-line _sudo-command-line
211   bindkey "^Os" sudo-command-line
212 # }}}
213
214 # {{{ set some important options
215   umask 022
216
217 # history:
218   setopt append_history       # append history list to the history file (important for multiple parallel zsh sessions!)
219   is4 && setopt SHARE_HISTORY # import new commands from the history file also in other zsh-session
220   setopt extended_history     # save each command's beginning timestamp and the duration to the history file
221   is4 && setopt histignorealldups # If  a  new  command  line being added to the history
222                               # list duplicates an older one, the older command is removed from the list
223   setopt histignorespace      # remove command lines from the history list when
224                               # the first character on the line is a space
225 #  setopt histallowclobber    # add `|' to output redirections in the history
226 #  setopt NO_clobber          # warning if file exists ('cat /dev/null > ~/.zshrc')
227   setopt auto_cd              # if a command is issued that can't be executed as a normal command,
228                               # and the command is the name of a directory, perform the cd command to that directory
229   setopt extended_glob        # in order to use #, ~ and ^ for filename generation
230                               # grep word *~(*.gz|*.bz|*.bz2|*.zip|*.Z) ->
231                               # -> searches for word not in compressed files
232                               # don't forget to quote '^', '~' and '#'!
233   setopt notify               # report the status of backgrounds jobs immediately
234   setopt hash_list_all        # Whenever a command completion is attempted, make sure \
235                               # the entire command path is hashed first.
236   setopt completeinword       # not just at the end
237 # setopt nocheckjobs          # don't warn me about bg processes when exiting
238   setopt nohup                # and don't kill them, either
239 # setopt printexitvalue       # alert me if something failed
240 # setopt dvorak               # with spelling correction, assume dvorak kb
241   setopt auto_pushd           # make cd push the old directory onto the directory stack.
242   setopt nonomatch            # try to avoid the 'zsh: no matches found...'
243   setopt nobeep               # avoid "beep"ing
244
245   MAILCHECK=30       # mailchecks
246   REPORTTIME=5       # report about cpu-/system-/user-time of command if running longer than 5 secondes
247   watch=(notme root) # watch for everyone but me and root
248
249 # define word separators (for stuff like backward-word, forward-word, backward-kill-word,..)
250 #  WORDCHARS='*?_-.[]~=/&;!#$%^(){}<>' # the default
251 #  WORDCHARS=.
252 #  WORDCHARS='*?_[]~=&;!#$%^(){}'
253 #  WORDCHARS='${WORDCHARS:s@/@}'
254
255 # only slash should be considered as a word separator:
256   slash-backward-kill-word() {
257     local WORDCHARS="${WORDCHARS:s@/@}"
258     # zle backward-word
259     zle backward-kill-word
260   }
261   zle -N slash-backward-kill-word
262   bindkey '\ev' slash-backward-kill-word # press esc-v to delete a word until its last '/' (not the same as ctrl-w!)
263 # }}}
264
265 # {{{ history
266   export ZSHDIR=$HOME/.zsh
267   HISTFILE=$HOME/.zsh_history
268   isgrmlcd && HISTSIZE=500  || HISTSIZE=5000
269   isgrmlcd && SAVEHIST=1000 || SAVEHIST=10000 # useful for setopt append_history
270 # }}}
271
272 # {{{ display battery status on right side of prompt via running 'BATTERY=1 zsh'
273   if [ -n "$BATTERY" ] ; then
274      if [ -x =acpi ] ; then
275         PERCENT="${(C)${(s| |)$(acpi 2>/dev/null)}[4]}"
276         [ -z "$PERCENT" ] && PERCENT='acpi not present'
277         if [ "${PERCENT%%%}" -lt 20 ] ; then
278            PERCENT="warning: ${PERCENT}%"
279         fi
280      fi
281   fi
282 # }}}
283
284 # {{{ set prompt
285   if [ -f "/usr/share/zsh/$ZSH_VERSION/functions/Prompts/promptinit" ] ; then
286      autoload promptinit && promptinit # people should be able to use their favourite prompt
287   else
288      print 'Notice: no prompiinit available :('
289   fi
290   # precmd() => a function which is executed just before each prompt
291   # precmd () { setopt promptsubst; [[ -o interactive ]] && jobs -l;
292   # run 'NOPRECMD=1 zsh' to disable the precmd + preexec commands
293   is4 && ! [[ -n "$NOPRECMD" ]] && precmd () {
294       if [ -n "$BATTERY" ] ; then
295         RPROMPT="%(?..:()% ${PERCENT}${SCREENTITLE}"
296       else
297         RPROMPT="%(?..:()% ${SCREENTITLE}"
298       fi
299       # adjust title of xterm
300       # see http://www.faqs.org/docs/Linux-mini/Xterm-Title.html
301       case $TERM in (xterm*|rxvt)
302         print -Pn "\e]0;%n@%m: %~\a"
303         ;;
304       esac
305   }
306
307   # chpwd () => a function which is executed whenever the directory is changed
308
309   # preexec() => a function running before every command
310   is4 && ! [[ -n "$NOPRECMD" ]] && preexec () {
311   # set screen window title if running in a screen
312   # get the name of the program currently running and hostname of local machine
313       local HOSTNAME=$(hostname)
314       if [[ "$HOSTNAME" != grml ]] ; then
315          NAME="@$HOSTNAME"
316       fi
317       if [[ "$TERM" == screen* ]]; then
318 #          local CMD=${1[(wr)^(*=*|sudo|ssh|-*)]}       # dont't use hostname
319           local CMD="${1[(wr)^(*=*|sudo|ssh|-*)]}$NAME" # use hostname
320           echo -ne "\ek$CMD\e\\"
321       fi
322   # set the screen title to "zsh" when sitting at the command prompt:
323       if [[ "$TERM" == screen* ]]; then
324            SCREENTITLE=$'%{\ekzsh\e\\%}'
325       else
326            SCREENTITLE=''
327       fi
328   # adjust title of xterm
329       case $TERM in (xterm*|rxvt)
330         print -Pn "\e]0;%n@%m: $1\a"
331         ;;
332       esac
333   }
334
335 # set colors
336   if autoload colors && colors ; then
337      BLUE="%{${fg[blue]}%}"
338      RED="%{${fg_bold[red]}%}"
339      GREEN="%{${fg[green]}%}"
340      CYAN="%{${fg[cyan]}%}"
341      WHITE="%{${fg[white]}%}"
342      NO_COLOUR="%{${reset_color}%}"
343   else
344      BLUE="%{\e[1;34m%}"
345      RED="%{\e[1;31m%}"
346      GREEN="%{\e[1;32m%}"
347      CYAN="%{\e[1;36m%}"
348      WHITE="%{\e[1;37m%}"
349      NO_COLOUR="%{\e[0m%}"
350   fi
351
352   EXITCODE="%(?..%?%1v )"
353   PS2='`%_> '       # secondary prompt, printed when the shell needs more information to complete a command.
354   PS3='?# '         # selection prompt used within a select loop.
355   PS4='+%N:%i:%_> ' # the execution trace prompt (setopt xtrace). default: '+%N:%i>'
356
357 # set variable debian_chroot if running in a chroot with /etc/debian_chroot
358   if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
359     debian_chroot=$(cat /etc/debian_chroot)
360   fi
361
362 # don't use colors on dumb terminals (like emacs):
363   if [[ "$TERM" == dumb ]] ; then
364     PROMPT="${EXITCODE}${debian_chroot:+($debian_chroot)}%n@%m %40<...<%B%~%b%<< %# "
365   else
366     # only if $GRMLPROMPT is set (e.g. via 'GRMLPROMPT=1 zsh') use the extended prompt
367     # set variable identifying the chroot you work in (used in the prompt below)
368     if [[ -n "$GRMLPROMPT" ]]; then
369       PROMPT="${RED}${EXITCODE}${CYAN}[%j running job(s)] ${GREEN}{history#%!} ${RED}%(3L.+.) ${BLUE}%* %D
370 ${BLUE}%n${NO_COLOUR}@%m %40<...<%B%~%b%<< %# "
371     else
372       if (( EUID != 0 )); then
373         PROMPT="${RED}${EXITCODE}${WHITE}${debian_chroot:+($debian_chroot)}${BLUE}%n${NO_COLOUR}@%m %40<...<%B%~%b%<< %# " # primary prompt string
374       else
375         PROMPT="${BLUE}${EXITCODE}${WHITE}${debian_chroot:+($debian_chroot)}${RED}%n${NO_COLOUR}@%m %40<...<%B%~%b%<< %# " # primary prompt string
376       fi
377     fi
378   fi
379
380 # if we are inside a grml-chroot set a specific prompt theme
381   if [ -n "$GRML_CHROOT" ] ; then
382      PROMPT="%{$fg[red]%}(CHROOT) %{$fg_bold[red]%}%n%{$fg_no_bold[white]%}@%m %40<...<%B%~%b%<< %\# "
383   fi
384 # }}}
385
386 # {{{ 'hash' some often used directories
387   hash -d deb=/var/cache/apt/archives
388   hash -d doc=/usr/share/doc
389   hash -d linux=/lib/modules/$(command uname -r)/build/
390   hash -d log=/var/log
391   hash -d slog=/var/log/syslog
392   hash -d src=/usr/src
393   hash -d templ=/usr/share/doc/grml-templates
394   hash -d tt=/usr/share/doc/texttools-doc
395   hash -d www=/var/www
396 # }}}
397
398 # {{{ some aliases
399   if [ $UID = 0 ] ; then
400      [ -r /etc/grml/screenrc ] && alias screen='/usr/bin/screen -c /etc/grml/screenrc'
401   elif [ -r $HOME/.screenrc ] ; then
402      alias screen="/usr/bin/screen -c $HOME/.screenrc"
403   else
404      [ -r /etc/grml/screenrc_grml ] && alias screen='/usr/bin/screen -c /etc/grml/screenrc_grml'
405   fi
406
407   if ls --help 2>/dev/null |grep -- --color= >/dev/null && [ "$TERM" != dumb ] ; then
408      alias ls='ls -b -CF --color=auto' # do we have GNU ls with color-support?
409      alias la='ls -la --color=auto'
410      alias ll='ls -l --color=auto'
411      alias lh='ls -hAl --color=auto'
412      alias l='ls -lF --color=auto'
413   else
414      alias ls='ls -b -CF'
415      alias la='ls -la'
416      alias ll='ls -l'
417      alias lh='ls -hAl'
418      alias l='ls -lF'
419   fi
420
421   alias cp='nocorrect cp'         # no spelling correction on cp
422   alias mkdir='nocorrect mkdir'   # no spelling correction on mkdir
423   alias mv='nocorrect mv'         # no spelling correction on mv
424   alias rm='nocorrect rm'         # no spelling correction on rm
425
426   alias rd='rmdir'
427   alias md='mkdir'
428
429   alias swspeak="setopt singlelinezle ; unsetopt prompt_cr ; export PS1='%m%# ' ; speechd-up" # set up software synth.
430
431 # truecrypt; use e.g. via 'truec /dev/ice' /mnt/ice' or 'truec -i'
432   if [ -x /usr/sbin/truecrypt ] ; then
433      alias truec='truecrypt --mount-options "rw,sync,dirsync,users,uid=1000,gid=users,umask=077" '
434   fi
435
436   zsh-help(){print "$bg[white]$fg[black]
437 zsh-help - hints for use of zsh on grml
438 =======================================$reset_color
439
440 Main configuration of zsh happens in /etc/zsh/zshrc (global)
441 and /etc/skel/.zshrc which is copied to \$HOME/.zshrc once.
442 The files are part of the package grml-etc, if you want to
443 use them on a non-grml-system just get the tar.gz from
444 http://grml.org/repos/
445
446 If you want to stay in sync with zsh configuration of grml
447 run 'ln -sf /etc/skel/.zshrc \$HOME/.zshrc' and configure
448 your own stuff in \$HOME/.zshrc.local. System wide configuration
449 without touching configuration files of grml can take place
450 in /etc/zsh/zshrc.local.
451
452 If you want to use the configuration of user grml also when
453 running as user root just run 'zshskel' which will source
454 the file /etc/skel/.zshrc.
455
456 For information regarding zsh start at http://grml.org/zsh/
457
458 Take a look at grml's zsh refcard:
459 % xpdf =(zcat /usr/share/doc/grml-docs/zsh/grml-zsh-refcard.pdf.gz)
460
461 Check out the main zsh refcard:
462 % $BROWSER http://www.bash2zsh.com/zsh_refcard/refcard.pdf
463
464 And of course visit the zsh-lovers:
465 % man zsh-lovers
466
467 You can adjust some options through environment variables when
468 invoking zsh without having to edit configuration files.
469 Basically meant for bash users who are not used to the power of
470 the zsh yet. :)
471
472   \"NOCOR=1    zsh\" => deactivate automatic correction
473   \"NOMENU=1   zsh\" => do not use menu completion (note: use strg-d for completion instead!)
474   \"NOPRECMD=1 zsh\" => disable the precmd + preexec commands (set GNU screen title)
475   \"BATTERY=1  zsh\" => activate battery status (via acpi) on right side of prompt
476 $bg[white]$fg[black]
477 Please report wishes + bugs to the grml-team: http://grml.org/bugs/
478 Enjoy your grml system with the zsh!$reset_color"
479 }
480
481 # debian stuff
482   if [ -r /etc/debian_version ] ; then
483     alias acs="apt-cache search"
484     alias acsh="apt-cache show"
485     alias adg="$SUDO apt-get dist-upgrade"
486     alias agi="$SUDO apt-get install"
487     alias ag="$SUDO apt-get upgrade"
488     alias au="$SUDO apt-get update"
489     alias dbp="dpkg-buildpackage"
490     alias ge="grep-excuses"
491
492     isgrmlcd && alias su="sudo su"          # change to user root
493     alias tlog="tail -f /var/log/syslog"    # take a look at the syslog
494     alias zshskel="source /etc/skel/.zshrc" # source skeleton zshrc
495   fi
496
497 # if cdrecord is a symlink (to wodim) or isn't present at all warn:
498   if [ -L /usr/bin/cdrecord -o ! -x =cdrecord ] ; then
499      if [ -x =wodim ] ; then
500         alias cdrecord="echo 'cdrecord is not provided under its original name by Debian anymore.
501 See #377109 in the BTS of Debian for more details.
502
503 Please use the wodim binary instead' ; return 1"
504      fi
505   fi
506
507 # }}}
508
509 # {{{ Use hard limits, except for a smaller stack and no core dumps
510   unlimit
511   limit stack 8192
512   limit core 0      # important for a live-cd-system
513   limit -s
514 # }}}
515
516 # {{{ completion stuff
517
518 # Where to look for autoloaded function definitions
519   if [ -d /etc/zsh/completion.d ] ; then
520     local comp=/etc/zsh/completion.d
521     for func in $comp/*(N-.:t); . ${comp}/${func}
522   fi
523
524 # called later (via is4 && grmlcomp)
525 # notice: use 'zstyle' for getting current settings
526 #         press ^Xh (control-x h) for getting tags in context; ^X? (control-x ?) to run complete_debug with trace output
527 grmlcomp() {
528 ## completion system
529   zstyle ':completion:*:approximate:'    max-errors 'reply=( $((($#PREFIX+$#SUFFIX)/3 )) numeric )' # allow one error for every three characters typed in approximate completer
530   zstyle ':completion:*:complete:-command-::commands' ignored-patterns '*\~' # don't complete backup files as executables
531   zstyle ':completion:*:correct:*'       insert-unambiguous true             # start menu completion only if it could find no unambiguous initial string
532   zstyle ':completion:*:corrections'     format $'%{\e[0;31m%}%d (errors: %e)%{\e[0m%}' #
533   zstyle ':completion:*:correct:*'       original true                       #
534   zstyle ':completion:*:default'         list-colors ${(s.:.)LS_COLORS}      # activate color-completion(!)
535   zstyle ':completion:*:descriptions'    format $'%{\e[0;31m%}completing %B%d%b%{\e[0m%}'  # format on completion
536   zstyle ':completion:*:*:cd:*:directory-stack' menu yes select              # complete 'cd -<tab>' with menu
537   zstyle ':completion:*:expand:*'        tag-order all-expansions            # insert all expansions for expand completer
538   zstyle ':completion:*:history-words'   list false                          #
539   zstyle ':completion:*:history-words'   menu yes                            # activate menu
540   zstyle ':completion:*:history-words'   remove-all-dups yes                 # ignore duplicate entries
541   zstyle ':completion:*:history-words'   stop yes                            #
542   zstyle ':completion:*:*:linda:*'       file-patterns '*.deb'               # complete debian packages for command 'linda'
543   zstyle ':completion:*:*:lintian:*'     file-patterns '*.deb'               # complete debian packages for command 'lintian'
544   zstyle ':completion:*'                 matcher-list 'm:{a-z}={A-Z}'        # match uppercase from lowercase
545   zstyle ':completion:*:matches'         group 'yes'                         # separate matches into groups
546   zstyle ':completion:*'                 group-name ''
547   if [[ -z "$NOMENU" ]] ; then
548     zstyle ':completion:*'               menu select=5                       # if there are more than 5 options allow selecting from a menu
549   else
550     setopt no_auto_menu # don't use any menus at all
551   fi
552   zstyle ':completion:*:messages'        format '%d'                         #
553   zstyle ':completion:*:options'         auto-description '%d'               #
554   zstyle ':completion:*:options'         description 'yes'                   # describe options in full
555   zstyle ':completion:*:processes'       command 'ps -au$USER'               # on processes completion complete all user processes
556   zstyle ':completion:*:*:-subscript-:*' tag-order indexes parameters        # offer indexes before parameters in subscripts
557   zstyle ':completion:*'                 verbose true                        # provide verbose completion information
558   zstyle ':completion:*:warnings'        format $'%{\e[0;31m%}No matches for:%{\e[0m%} %d' # set format for warnings
559   zstyle ':completion:*:*:zcompile:*'    ignored-patterns '(*~|*.zwc)'       # define files to ignore for zcompile
560   zstyle ':completion:correct:'          prompt 'correct to: %e'             #
561   zstyle ':completion::(^approximate*):*:functions' ignored-patterns '_*'    # Ignore completion functions for commands you don't have:
562
563 # complete manual by their section
564   zstyle ':completion:*:manuals'    separate-sections true
565   zstyle ':completion:*:manuals.*'  insert-sections   true
566   zstyle ':completion:*:man:*'      menu yes select
567
568 ## correction
569 # run rehash on completion so new installed program are found automatically:
570   _force_rehash() {
571       (( CURRENT == 1 )) && rehash
572          return 1 # Because we didn't really complete anything
573     }
574 # some people don't like the automatic correction - so run 'NOCOR=1 zsh' to deactivate it
575   if [[ -n "$NOCOR" ]] ; then
576     zstyle ':completion:*' completer _oldlist _expand _force_rehash _complete
577     setopt nocorrect # do not try to correct the spelling if possible
578   else
579 #    zstyle ':completion:*' completer _oldlist _expand _force_rehash _complete _correct _approximate
580     setopt correct  # try to correct the spelling if possible
581     zstyle -e ':completion:*' completer '
582         if [[ $_last_try != "$HISTNO$BUFFER$CURSOR" ]]; then
583           _last_try="$HISTNO$BUFFER$CURSOR"
584           reply=(_complete _match _prefix)
585         else
586           if [[ $words[1] = (rm|mv) ]]; then
587             reply=(_complete)
588           else
589             reply=(_oldlist _expand _force_rehash _complete _correct _approximate)
590           fi
591         fi'
592   fi
593 # zstyle ':completion:*' completer _complete _correct _approximate
594 # zstyle ':completion:*' expand prefix suffix
595
596 # automatic rehash? Credits go to Frank Terbeck
597 # function my_accept () {
598 #   local buf
599 #   [[ -z ${BUFFER} ]] && zle accept-line && return
600 #   buf=( ${(z)BUFFER}  )
601 #   [[ -z ${commands[${buf[1]}]} ]] && rehash
602 #   zle accept-line
603 # }
604 # zle -N my_accept
605 # bindkey "^M" my_accept
606
607 # command for process lists, the local web server details and host completion
608   hosts=(`hostname` grml.org)
609   zstyle '*' hosts $hosts
610   zstyle ':completion:*:urls' local 'www' '/var/www/' 'public_html'
611
612 # caching
613   [ -d $ZSHDIR/cache ] && zstyle ':completion:*' use-cache yes && \
614                           zstyle ':completion::complete:*' cache-path $ZSHDIR/cache/
615
616 # use ~/.ssh/known_hosts for completion [does not work with hashing of new ssh versions anymore]
617   if [ -f "$HOME/.ssh/known_hosts" ] ; then
618     hosts=(${${${${(f)"$(<$HOME/.ssh/known_hosts)"}:#[\|]*}%%\ *}%%,*})
619     zstyle ':completion:*:hosts' hosts $hosts
620   fi
621
622 # use generic completion system for programs not yet defined:
623   compdef _gnu_generic tail head feh cp mv gpg df stow uname ipacsum fetchipac
624
625 # see upgrade function in this file
626   compdef _hosts upgrade
627 }
628 # }}}
629
630 # {{{ grmlstuff
631 grmlstuff() {
632 # people should use 'grml-x'!
633   function startx() {
634     if [ -e /etc/X11/xorg.conf ] ; then
635        [ -x /usr/bin/startx ] && /usr/bin/startx || /usr/X11R6/bin/startx
636     else
637       echo "Please use the script \"grml-x\" for starting the X Window System
638 because there does not exist /etc/X11/xorg.conf yet.
639 If you want to use startx anyway please call \"/usr/bin/startx\"."
640       return -1
641     fi
642   }
643
644   function xinit() {
645     if [ -e /etc/X11/xorg.conf ] ; then
646        [ -x /usr/bin/xinit ] && /usr/bin/xinit || /usr/X11R6/bin/xinit
647     else
648       echo "Please use the script \"grml-x\" for starting the X Window System.
649 because there does not exist /etc/X11/xorg.conf yet.
650 If you want to use xinit anyway please call \"/usr/bin/xinit\"."
651       return -1
652     fi
653   }
654
655   if [ -x /usr/sbin/915resolution ] ; then
656      alias 855resolution='echo -e "Please use 915resolution as resolution modify tool for Intel graphic chipset."; return -1'
657   fi
658
659   alias grml-version='cat /etc/grml_version'
660
661   if [ -x /usr/sbin/rebuildfstab ] ; then
662      local fstabuser=$(getent passwd 1000 | cut -d: -f1)
663      alias grml-rebuildfstab="rebuildfstab -v -r -u $fstabuser -g $fstabuser"
664   fi
665 }
666 # }}}
667
668 # {{{ now run the functions
669   isgrml && checkhome
670   is4    && isgrml    && grmlstuff
671   is4    && grmlcomp
672 # }}}
673
674 # {{{ keephack
675   [ -r /etc/zsh/keephack ] && is4 && source /etc/zsh/keephack
676 # }}}
677
678 # {{{ wonderful idea of using "e" glob qualifier by Peter Stephenson
679 # You use it as follows:
680 # $ NTREF=/reference/file
681 # $ ls -l *(e:nt:)
682 # This lists all the files in the current directory newer than the reference file.
683 # You can also specify the reference file inline; note quotes:
684 # $ ls -l *(e:'nt ~/.zshenv':)
685   is4 && nt() {
686     if [[ -n $1 ]]; then
687       local NTREF=${~1}
688     fi
689     [[ $REPLY -nt $NTREF ]]
690   }
691 # }}}
692
693 # shell functions {{{
694   setenv()  { typeset -x "${1}${1:+=}${(@)argv[2,$#]}" }  # csh compatibility
695   freload() { while (( $# )); do; unfunction $1; autoload -U $1; shift; done }
696   manzsh()  {  /usr/bin/man zshall |  vim -c "se ft=man| se hlsearch" +/"$1" - ; }
697 #  manzsh()  { man zshall | $MYLESS -p $1 ; }
698 #  manzsh() {  /usr/bin/man zshall |  most +/"$1" ; }
699
700 # use "dchange <package-name>" to view Debian's changelog of the package:
701   dchange() {
702     if [ -r /usr/share/doc/${1}/changelog.Debian.gz ] ; then
703        most /usr/share/doc/${1}/changelog.Debian.gz
704     else
705        if [ -r /usr/share/doc/${1}/changelog.gz ] ; then
706           most /usr/share/doc/${1}/changelog.gz
707        else
708           echo "No changelog for package $1 found, sorry."
709           return 1
710        fi
711     fi
712   }
713   _dchange() { _files -W /usr/share/doc -/ }
714   compdef _dchange dchange
715
716 # use "uchange <package-name>" to view upstream's changelog of the package:
717   uchange() {
718     if [ -r /usr/share/doc/${1}/changelog.gz ] ; then
719        most /usr/share/doc/${1}/changelog.gz
720     else
721        echo "No changelog for package $1 found, sorry."
722        return 1
723     fi
724   }
725   _uchange() { _files -W /usr/share/doc -/ }
726   compdef _uchange uchange
727
728 # edit alias via zle:
729   edalias() {
730     [ -z "$1" ] && { echo "Usage: edalias <alias_to_edit>" ; return 1 } || vared aliases'[$1]' ;
731   }
732   compdef _aliases edalias
733
734 # edit function via zle:
735   edfun() {
736     [ -z "$1" ] && { echo "Usage: edfun <function_to_edit>" ; return 1 } || zed -f "$1" ;
737   }
738   compdef _functions edfun
739
740 # use it e.g. via 'Restart apache2'
741  if [ -d /etc/init.d ] ; then
742   for i in Start Restart Stop Reload ; do
743     eval "$i() { $SUDO /etc/init.d/\$1 ${i:l} \$2 ; }"
744   done
745 # now the completion for this:
746   compctl -g "$(echo /etc/init.d/*(:t))" Start Restart Stop Reload
747  fi
748 # }}}
749
750 # make sure our environment is clean regarding colors
751   for color in BLUE RED GREEN CYAN WHITE ; unset $color
752
753 # source another config file if present {{{
754   if [ -r /etc/zsh/zshrc.local ]; then
755    source /etc/zsh/zshrc.local
756   fi
757 # }}}
758
759 # "persistent history" {{{
760 # just write important commands you always need to ~/.important_commands
761   if [ -r ~/.important_commands ] ; then
762      fc -R ~/.important_commands
763   fi
764 # }}}
765
766 ## END OF FILE #################################################################
767 # vim:foldmethod=marker