]> ruderich.org/simon Gitweb - config/dotfiles.git/blob - zsh/rc
zsh/rc: Set PROMPT in a precmd() hook.
[config/dotfiles.git] / zsh / rc
1 # Zsh configuration file.
2
3
4 source_debug "sourcing ~/.zsh/rc"
5
6 # MISCELLANEOUS SETTINGS
7
8 # Be paranoid, new files are readable/writable by me only.
9 umask 077
10
11 # Disable beeps.
12 setopt nobeep
13
14 # Prevent overwriting existing files with '> filename', use '>| filename'
15 # (or >!) instead.
16 setopt noclobber
17
18 # Entering the name of a directory (if it's not a command) will automatically
19 # cd to that directory.
20 setopt autocd
21
22 # When entering a nonexistent command name automatically try to find a similar
23 # one.
24 setopt correct
25
26 # Enable zsh's extended glob abilities.
27 setopt extendedglob
28
29 # Don't exit if <C-d> is pressed.
30 setopt ignoreeof
31
32
33 # KEY BINDINGS
34
35 # Not all bindings are done here, only those not specific to a given section.
36
37 # Use Vi(m) style key bindings.
38 bindkey -v
39
40 # Also use jj to exit insert mode.
41 bindkey 'jj' vi-cmd-mode
42
43 # I don't need the arrow keys, I use ^N and ^P for this (see below).
44 bindkey -r '^[OA' '^[OB' '^[OC' '^[OD' '^[[A' '^[[B' '^[[C' '^[[D'
45 # Also not in Vi mode.
46 bindkey -a -r '^[OA' '^[OB' '^[OC' '^[OD' '^[[A' '^[[B' '^[[C' '^[[D'
47
48
49 # FUNCTION SETTINGS
50
51 # Make sure every entry in $fpath is unique.
52 typeset -U fpath
53 # ~/.zsh/functions/completion is a symbolic link to the Completion directory
54 # of a Zsh CVS checkout. Use it to get the newest completions if available.
55 if [[ -d ~/.zsh/functions/completion ]]; then
56     fpath=(~/.zsh/functions/completion/*/*(/) $fpath)
57 fi
58 # Set correct fpath to allow loading my functions (including completion
59 # functions).
60 fpath=(~/.zsh/functions $fpath)
61 # Autoload my functions (except completion functions and hidden files). Thanks
62 # to caphuso from the Zsh example files for this idea.
63 if [[ -d ~/.zsh/functions ]]; then
64     autoload ${fpath[1]}/^_*(^/:t)
65 fi
66
67 # Simulate hooks using _functions arrays for Zsh versions older than 4.3.4. At
68 # the moment only precmd(), preexec() and chpwd() are simulated.
69 #
70 # At least 4.3.4 (not sure about later versions) has an error in add-zsh-hook
71 # so the compatibility version is used there too.
72 if [[ $ZSH_VERSION != (4.3.<5->|4.<4->*|<5->*) ]]; then
73     # Provide add-zsh-hook which was added in 4.3.4.
74     fpath=(~/.zsh/functions/compatibility $fpath)
75
76     # Run all functions defined in the ${precmd,preexec,chpwd}_functions
77     # arrays.
78     function precmd() {
79         for function in $precmd_functions; do
80             $function $@
81         done
82     }
83     function preexec() {
84         for function in $preexec_functions; do
85             $function $@
86         done
87     }
88     function chpwd() {
89         for function in $chpwd_functions; do
90             $function $@
91         done
92     }
93 fi
94
95 # Autoload add-zsh-hook to add/remove zsh hook functions easily.
96 autoload -Uz add-zsh-hook
97
98 # Load zmv (zsh move) which is powerful to rename files.
99 autoload zmv
100
101
102 # HISTORY SETTINGS
103
104 # Use history and store it in ~/.zsh/history.
105 HISTSIZE=50000
106 SAVEHIST=50000
107 HISTFILE=~/.zsh/history
108 # Append to the history file instead of overwriting it and do it immediately
109 # when a command is executed.
110 setopt appendhistory
111 setopt incappendhistory
112 # If the same command is run multiple times store it only once in the history.
113 setopt histignoredups
114 # Vim like completions of previous executed commands (also enter Vi-mode). If
115 # called at the beginning it just recalls old commands (like cursor up), if
116 # called after typing something, only lines starting with the typed are
117 # returned. Very useful to get old commands quickly. Thanks to Mikachu in #zsh
118 # on Freenode (2010-01-17 12:47) for the information how to a use function
119 # with bindkey.
120 zle -N my-vi-history-beginning-search-backward
121 my-vi-history-beginning-search-backward() {
122     local not_at_beginning_of_line
123     if [[ $CURSOR -ne 0 ]]; then
124         not_at_beginning_of_line=yes
125     fi
126
127     zle history-beginning-search-backward
128
129     # Start Vi-mode and stay at the same position (Vi-mode moves one left,
130     # this counters it).
131     zle vi-cmd-mode
132     if [[ -n $not_at_beginning_of_line ]]; then
133         zle vi-forward-char
134     fi
135 }
136 bindkey '^P' my-vi-history-beginning-search-backward
137 bindkey -a '^P' history-beginning-search-backward # binding for Vi-mode
138 # Here only Vi-mode is necessary as ^P enters Vi-mode and ^N only makes sense
139 # after calling ^P.
140 bindkey -a '^N' history-beginning-search-forward
141
142
143 # PROMPT SETTINGS
144
145 # Use colorized output, necessary for prompts and completions.
146 autoload -U colors && colors
147
148 # Some shortcuts for colors. The %{...%} tells zsh that the data in between
149 # doesn't need any space, necessary for correct prompt draw.
150 local red="%{${fg[red]}%}"
151 local blue="%{${fg[blue]}%}"
152 local green="%{${fg[green]}%}"
153 local yellow="%{${fg[yellow]}%}"
154 local default="%{${fg[default]}%}"
155
156 # vcs_info was added in 4.3.9 but it works in earlier versions too. So load it
157 # if the necessary files are available in ~/.zsh/functions/vcs_info (often a
158 # symbolic link to current checkout of Zsh's sources).
159 if [[ $ZSH_VERSION == (4.3.<9->|4.<4->*|<5->*) ||
160       -d ~/.zsh/functions/vcs_info ]]; then
161     # Update fpath to allow loading the vcs_info functions.
162     if [[ -d ~/.zsh/functions/vcs_info ]]; then
163        fpath=(~/.zsh/functions/vcs_info/
164               ~/.zsh/functions/vcs_info/Backends
165               $fpath)
166     fi
167
168     # Allow substitutions and expansions in the prompt, necessary for
169     # vcs_info.
170     setopt promptsubst
171     # Load vcs_info to display information about version control repositories.
172     autoload -Uz vcs_info
173     # Only look for git and mercurial repositories; the only I use.
174     zstyle ':vcs_info:*' enable git hg
175     # Check the repository for changes so they can be used in %u/%c (see
176     # below). This comes with a speed penalty for bigger repositories.
177     zstyle ':vcs_info:*' check-for-changes true
178
179     # Set style of vcs_info display. The current branch (green) and VCS (blue)
180     # is displayed. If there is an special action going on (merge, rebase)
181     # it's also displayed (red). Also display if there are unstaged or staged
182     # (%u/%c) changes.
183     if [[ $ZSH_VERSION == (4.3.<11->|4.<4->*|<5->*) ||
184           -d ~/.zsh/functions/vcs_info ]]; then
185         zstyle ':vcs_info:*' formats \
186             "($green%b%u%c$default:$blue%s$default)"
187         zstyle ':vcs_info:*' actionformats \
188             "($green%b%u%c$default/$red%a$default:$blue%s$default)"
189     else
190         # In older versions %u and %c are not defined yet and are not
191         # correctly expanded.
192         zstyle ':vcs_info:*' formats \
193             "($green%b$default:$blue%s$default)"
194         zstyle ':vcs_info:*' actionformats \
195             "($green%b$default/$red%a$default:$blue%s$default)"
196     fi
197     # Set style for formats/actionformats when unstaged (%u) and staged (%c)
198     # changes are detected in the repository; check-for-changes must be set to
199     # true for this to work. Thanks to Bart Trojanowski
200     # (http://jukie.net/~bart/blog/pimping-out-zsh-prompt) for the idea
201     # (2010-03-11 00:20).
202     zstyle ':vcs_info:*' unstagedstr '¹'
203     zstyle ':vcs_info:*' stagedstr   '²'
204
205     # Default to running vcs_info. If possible we prevent running it later for
206     # speed reasons. If set to a non empty value vcs_info is run.
207     FORCE_RUN_VCS_INFO=1
208
209     # Cache system inspired by Bart Trojanowski
210     # (http://jukie.net/~bart/blog/pimping-out-zsh-prompt).
211     #zstyle ':vcs_info:*+pre-get-data:*' hooks pre-get-data
212     +vi-pre-get-data() {
213         # Only Git and Mercurial support and need caching. Abort if any other
214         # VCS is used.
215         [[ "$vcs" != git && "$vcs" != hg ]] && return
216
217         # If the shell just started up or we changed directories (or for other
218         # custom reasons) we must run vcs_info.
219         if [[ -n $FORCE_RUN_VCS_INFO ]]; then
220             FORCE_RUN_VCS_INFO=
221             return
222         fi
223
224         # Don't run vcs_info by default to speed up the shell.
225         ret=1
226         # If a git/hg command was run then run vcs_info as the status might
227         # need to be updated.
228         case "$(fc -ln $(($HISTCMD-1)))" in
229             git* | g\ *)
230                 ret=0
231                 ;;
232             hg*)
233                 ret=0
234                 ;;
235         esac
236     }
237
238     # Must run vcs_info when changing directories.
239     prompt_chpwd() {
240         FORCE_RUN_VCS_INFO=1
241     }
242     add-zsh-hook chpwd prompt_chpwd
243
244
245     # Display the VCS information in the right prompt.
246     if [[ $ZSH_VERSION == (4.3.<9->|4.<4->*|<5->*) ]]; then
247         RPROMPT='${vcs_info_msg_0_}'
248     # There is a bug in Zsh below 4.3.9 which displays a wrong symbol when
249     # ${vcs_info_msg_0_} is empty. Provide a workaround for those versions,
250     # thanks to Frank Terbeck <ft@bewatermyfriend.org> for it.
251     else
252         RPROMPT='${vcs_info_msg_0_:- }'
253     fi
254
255     RUN_VCS_INFO=1
256 else
257     RUN_VCS_INFO=
258 fi
259
260 # Set the default prompt. The current host and working directory is displayed,
261 # the exit code of the last command if it wasn't 0, the number of running jobs
262 # if not 0.
263 #
264 # The prompt is in green and blue to make easily detectable, the error exit
265 # code in red and bold and the job count in yellow.
266 prompt_precmd() {
267     # Call vcs_info before every prompt.
268     if [[ -n $RUN_VCS_INFO ]]; then
269         vcs_info
270     fi
271
272     PROMPT="$green%B%m%b$default:$blue%B%~%b$default \
273 %(1j.$yellow%j$default.)%# \
274 %(?..($red%B%?%b$default%) )"
275 }
276 add-zsh-hook precmd prompt_precmd
277
278
279 # When screen, xterm or rxvt is used set the name of the window to the
280 # currently running program.
281 #
282 # When a program is started preexec() sets the window's name to it; when it
283 # stops precmd() resets the window's name to 'zsh'.
284 #
285 # It works with screen, xterm and rxvt.
286 #
287 # If a command is run with sudo or if the shell is running as root then a ! is
288 # added at the beginning of the command to make this clear. If a command is
289 # running on a different computer with ssh a @ is added at the beginning. If
290 # screen is running on the remote machine instead of @screen @:hostname
291 # (hostname replaced by the machine's hostname) is displayed. This only works
292 # if the .zshrc on the server also uses this command.
293 #
294 # screen* is necessary as `screen` uses screen.linux for example for a linux
295 # console.
296 if [[ $TERM == screen* || $TERM == xterm* || $TERM == rxvt* ]]; then
297     # Is set to a non empty value to reset the window name in the next
298     # precmd() call.
299     window_reset=yes
300     # Is set to a non empty value when the shell is running as root.
301     if [[ $(id -u) -eq 0 ]]; then
302         window_root=yes
303     fi
304
305     window_preexec() {
306         # Get the program name with its arguments.
307         local program_name=$1
308
309         # When sudo is used use real program name instead, but with an
310         # exclamation mark at the beginning (handled below).
311         local program_sudo=
312         if [[ $program_name == sudo* ]]; then
313             program_name=${program_name#sudo }
314             program_sudo=yes
315         fi
316         # Remove all arguments from the program name.
317         program_name=${program_name%% *}
318
319         # Ignore often used commands which are only running for a very short
320         # time. This prevents a "blinking" name when it's changed to "cd" for
321         # example and then some milliseconds later back to "zsh".
322         [[ $program_name == (cd*|ls|la|ll|clear|c) ]] && return
323
324         # Change my shortcuts so the real name of the program is displayed.
325         case $program_name in
326             e)
327                 program_name=elinks
328                 ;;
329             g)
330                 program_name=git
331                 ;;
332             m)
333                 program_name=mutt
334                 ;;
335             v)
336                 program_name=vim
337                 ;;
338         esac
339
340         # Add an exclamation mark at the beginning if running with sudo or if
341         # running zsh as root.
342         if [[ -n $program_sudo || -n $window_root ]]; then
343             program_name=!$program_name
344         fi
345
346         # Add an at mark at the beginning if running through ssh on a
347         # different computer.
348         if [[ -n $SSH_CONNECTION ]]; then
349             program_name="@$program_name"
350
351             # If screen is running in SSH then display "@:hostname" as title
352             # in the term/outer screen.
353             if [[ $program_name == @screen ]]; then
354                 program_name="@:${$(hostname)//.*/}"
355             fi
356         fi
357
358         # Set the window name to the currently running program.
359         window_title "$program_name"
360
361         # Tell precmd() to reset the window name when the program stops.
362         window_reset=yes
363     }
364
365     window_precmd() {
366         # Abort if no window name reset is necessary.
367         [[ -z $window_reset ]] && return
368
369         # Reset the window name to 'zsh'.
370         local name=zsh
371         # If the function was called with an argument then reset the window
372         # name to '.zsh' (used by clear alias).
373         if [[ -n $1 ]]; then
374             name=.zsh
375         fi
376
377         # Prepend prefixes like in window_preexec().
378         if [[ -n $window_root ]]; then
379             name="!$name"
380         fi
381         if [[ -n $SSH_CONNECTION ]]; then
382             name="@$name"
383         fi
384         window_title $name
385
386         # Just reset the name, so no screen reset necessary for the moment.
387         window_reset=
388     }
389
390     # Sets the window title. Works with screen, xterm and rxvt.
391     if [[ $TERM == screen* ]]; then
392         window_title() {
393             print -n "\ek$1\e\\"
394         }
395     elif [[ $TERM == xterm* || $TERM == rxvt* ]]; then
396         window_title() {
397             print -n "\e]2;$1\e\\"
398         }
399     else
400         # Fallback if another TERM is used.
401         window_title() { }
402     fi
403
404     # Add the preexec() and precmd() hooks.
405     add-zsh-hook preexec window_preexec
406     add-zsh-hook precmd window_precmd
407 fi
408
409
410 # COMPLETION SETTINGS
411
412 # Load the complist module which provides additions to completion lists
413 # (coloring, scrollable).
414 zmodload zsh/complist
415 # Use new completion system, store dumpfile in ~/.zsh/cache to prevent
416 # cluttering of ~/. $fpath must be set before calling this. Thanks to Adlai in
417 # #zsh on Freenode (2009-08-07 21:05) for reminding me of the $fpath problem.
418 autoload -U compinit && compinit -d ~/.zsh/cache/zcompdump
419
420 # Use cache to speed up completions.
421 zstyle ':completion:*' use-cache on
422 zstyle ':completion:*' cache-path ~/.zsh/cache
423
424 # Complete arguments and fix spelling mistakes when possible.
425 zstyle ':completion:*' completer _complete _match _correct _approximate
426
427 # Make sure the list of possible completions is displayed after pressing <TAB>
428 # the first time.
429 setopt nolistambiguous
430 # Allow completions in the middle of a text, i.e. "/usr/bin/<TAB>whatever"
431 # completes like "/usr/bin/<TAB>". Useful when adding new options to commands.
432 bindkey '^I' expand-or-complete-prefix
433 # Try uppercase if the currently typed string doesn't match. This allows
434 # typing in lowercase most of the time and completion fixes the case.
435 zstyle ':completion:*' matcher-list '' 'm:{a-z}={A-Z}'
436
437 # Use ls like colors for completions.
438 zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
439
440 # Make completion lists scrollable so "do you wish to see all n possibilities"
441 # is no longer displayed.
442 zstyle ':completion:*' list-prompt '%p'
443 # Display group name (like 'external command', 'alias', etc.) when there are
444 # multiple matches in bold.
445 zstyle ':completion:*' format '    %B%d%b:'
446 # Display different types of matches separately.
447 zstyle ':completion:*' group-name ''
448
449 # Ignore completion functions.
450 zstyle ':completion:*:functions' ignored-patterns '_*'
451 # Ignore parent directory.
452 zstyle ':completion:*:(cd|mv|cp):*' ignore-parents parent pwd
453 # Always complete one value (file name) only once in the current line. This
454 # makes it easy to complete multiple values because I can just press tab to
455 # get all possible values. Otherwise I would have to skip the first value
456 # again and again.
457 zstyle ':completion:*' ignore-line yes
458 # Except for mv and cp, because I often want to use to similar names, so I
459 # complete to the same and change it.
460 zstyle ':completion:*:(mv|cp):*' ignore-line no
461
462
463 # CUSTOM ALIASES AND FUNCTIONS
464
465 # If ^C is pressed while typing a command, add it to the history so it can be
466 # easily retrieved later and then abort like ^C normally does. This is useful
467 # when I want to abort an command to do something in between and then finish
468 # typing the command.
469 #
470 # Thanks to Vadim Zeitlin <vz-zsh@zeitlins.org> for a fix (--) so lines
471 # starting with - don't cause errors; and to Nadav Har'El
472 # <nyh@math.technion.ac.il> for a fix (-r) to handle whitespace/quotes
473 # correctly, both on the Zsh mailing list.
474 TRAPINT() {
475     # Store the current buffer in the history.
476     zle && print -s -r -- $BUFFER
477
478     # Return the default exit code so Zsh aborts the current command.
479     return $1
480 }
481
482 # Colorize stderr. Very useful when looking for errors. Thanks to
483 # http://gentoo-wiki.com/wiki/Zsh for the basic script and Mikachu in #zsh on
484 # Freenode (2010-03-07 04:03) for some improvements (-r, printf). It's not yet
485 # perfect and doesn't work with su and git for example, but it can handle most
486 # interactive output quite well (even with no trailing new line) and in those
487 # cases the E alias can be used as workaround.
488 exec 2>>(while read -r -k -u 0 line; do
489     printf '\e[91m%s\e[0m' "$line";
490     print -n $'\0';
491 done &)
492
493 # Load aliases and similar functions also used by other shells.
494 if [[ -f ~/.shell/aliases ]]; then
495     . ~/.shell/aliases
496 fi
497
498 # Make sure aliases are expanded when using sudo.
499 alias sudo='sudo '
500
501 # Global aliases for often used commands in the command line.
502 alias -g E='2>&1'
503 alias -g L='E | less'
504 alias -g D='E | colordiff L'
505 alias -g G='| grep'
506 alias -g S='| sort'
507 alias -g U='| uniq'
508 alias -g H='| head'
509 alias -g T='| tail'
510
511 # Make going up directories simple.
512 alias -g ...='../..'
513 alias -g ....='../../..'
514 alias -g .....='../../../..'
515
516 # If the window naming feature is used (see above) then use ".zsh" (leading
517 # dot) as title name after running clear so it's clear to me that the window
518 # is empty. I open so much windows that I don't know in which I have something
519 # important. This helps me to remember which windows are empty (I run clear
520 # after I finished my work in a window).
521 if [[ -n $window_reset ]]; then
522     alias clear='clear; window_reset=yes; window_precmd reset'
523 fi
524
525 # Display all branches (except stash) in gitk but only 200 commits as this is
526 # much faster. Also put in the background and disown. Thanks to sitaram in
527 # #git on Freenode (2009-04-20 15:51).
528 gitk() {
529     command gitk \
530         --max-count=200 \
531         $(git rev-parse --symbolic-full-name --remotes --branches) \
532         $@ &
533     disown %command
534 }
535 # Same for tig (except the disown part as it's no GUI program).
536 tig() {
537     command tig \
538         --max-count=200 \
539         $(git rev-parse --symbolic-full-name --remotes --branches) \
540         $@
541 }
542
543
544 # OS SPECIFIC SETTINGS
545
546 local uname=$(uname)
547
548 if [[ $uname == Linux ]]; then
549     # Settings when creating Debian packages.
550     DEBEMAIL=simon@ruderich.org
551     export DEBEMAIL
552     DEBFULLNAME='Simon Ruderich'
553     export DEBFULLNAME
554
555 elif [[ $uname == Darwin ]]; then # Mac OS X
556     # Store the current clipboard in CLIPBOARD before every command so it can
557     # be used in commands.
558     os_darwin_preexec() {
559         export CLIPBOARD="$(pbpaste)"
560     }
561     # Add the function as preexec hook.
562     add-zsh-hook preexec os_darwin_preexec
563
564     # Initialize CLIPBOARD so it's available for completion directly after
565     # startup.
566     CLIPBOARD=""
567     export CLIPBOARD
568
569     # Fetch current URL in clipboard with wget.
570     alias wnc='wget --no-proxy $CLIPBOARD'
571 fi
572
573
574 # LOAD ADDITIONAL CONFIGURATION FILES
575
576 # Load rc file for current hostname (first part before a dot) or rc.local.
577 source_config ~/.zsh host rc ${$(hostname)//.*/}
578
579
580 # RUN COMMANDS
581
582 # If not already in screen reattach to a running session or create a new one.
583 # This also starts screen one a remote server when connecting through ssh.
584 if [[ $TERM != dumb && -z $STY ]]; then
585     # Get running detached sessions.
586     session=$(screen -list | grep 'Detached' | awk '{ print $1; exit }')
587
588     # As we exec later we have to set the title here.
589     window_preexec "screen"
590
591     # Create a new session if none is running.
592     if [[ -z $session ]]; then
593         exec screen
594     # Reattach to a running session.
595     else
596         exec screen -r $session
597     fi
598 fi
599
600
601 source_debug "finished sourcing ~/.zsh/rc"
602
603 # vim: ft=zsh