]> ruderich.org/simon Gitweb - config/dotfiles.git/blob - zsh/rc
zsh/rc: Use red # as prompt for root.
[config/dotfiles.git] / zsh / rc
1 # Zsh configuration file.
2
3 # Copyright (C) 2011-2013  Simon Ruderich
4 #
5 # This file is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This file is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this file.  If not, see <http://www.gnu.org/licenses/>.
17
18
19 source_debug '. ~/.zsh/rc'
20
21
22 # Warn when creating global variables from inside a function. Needs to be set
23 # before declaring a function.
24 setopt warn_create_global
25
26
27 # HELPER FUNCTIONS
28
29 # Return the name of the program which is called in the foreground with `fg`.
30 # $1 is the name of the program (optional). If it's not 'fg' or 'fg *' it's
31 # returned unchanged.
32 zshrc_resolve_fg_to_resumed_job_name() {
33     # $REPLY is used by convention for scalars ($reply for arrays) to return
34     # values from functions. unset it here to prevent problems when REPLY is
35     # bound to an integer or similar. Thanks to Mikachu in #zsh on Freenode
36     # (2012-09-27 17:14 CEST) for this hint.
37     unset REPLY
38
39     # Replace fg with the resumed job name.
40     if [[ $1 == fg ]]; then
41         REPLY="${jobtexts[%+]}"
42     elif [[ $1 == fg\ * ]]; then
43         REPLY="${jobtexts[${1#fg }]}"
44     # Normal program, return as is.
45     else
46         REPLY="$1"
47     fi
48 }
49
50
51 # MISCELLANEOUS SETTINGS
52
53 # Be paranoid, new files are readable/writable by me only, but not as root.
54 if [[ $UID -ne 0 ]]; then
55     umask 077
56 fi
57
58 # Disable beeps.
59 setopt nobeep
60
61 # Prevent overwriting existing files with '> filename', use '>| filename'
62 # (or >!) instead.
63 setopt noclobber
64
65 # Entering the name of a directory (if it's not a command) will automatically
66 # cd to that directory.
67 setopt autocd
68
69 # When entering a nonexistent command name automatically try to find a similar
70 # one.
71 setopt correct
72
73 # Enable zsh's extended glob abilities.
74 setopt extendedglob
75
76 # Don't exit if <C-D> is pressed. Prevents exiting the shell by accident (e.g.
77 # pressing <C-D> twice).
78 setopt ignoreeof
79
80
81 # KEY BINDINGS
82
83 # Not all bindings are done here, only those not specific to a given section.
84
85 # Use Vi(m) style key bindings.
86 bindkey -v
87
88 # Use jk to exit insert mode (jj is too slow).
89 bindkey 'jk' vi-cmd-mode
90
91 # I don't need the arrow keys, I use ^N and ^P for this (see below).
92 bindkey -r '^[OA' '^[OB' '^[OC' '^[OD' '^[[A' '^[[B' '^[[C' '^[[D'
93 # Also not in Vi mode.
94 bindkey -a -r '^[OA' '^[OB' '^[OC' '^[OD' '^[[A' '^[[B' '^[[C' '^[[D'
95
96
97 # FUNCTION SETTINGS
98
99 # Make sure every entry in $fpath is unique.
100 typeset -U fpath
101 # ~/.zsh/functions/completion is a symbolic link to the Completion directory
102 # of a Zsh Git checkout. Use it to get the newest completions if available.
103 if [[ -d ~/.zsh/functions/completion ]]; then
104     fpath=(~/.zsh/functions/completion/*/*(/) $fpath)
105 fi
106 # Set correct fpath to allow loading my functions (including completion
107 # functions).
108 fpath=(~/.zsh/functions $fpath)
109 # Autoload my functions (except completion functions and hidden files). Thanks
110 # to caphuso from the Zsh example files for this idea.
111 if [[ -d ~/.zsh/functions ]]; then
112     autoload -Uz ${fpath[1]}/^_*(^/:t)
113 fi
114
115 # Simulate hooks using _functions arrays for Zsh versions older than 4.3.4. At
116 # the moment only precmd(), preexec() and chpwd() are simulated.
117 if [[ $ZSH_VERSION != (4.3.<4->*|4.<4->*|<5->*) ]]; then
118     # Run all functions defined in the ${precmd,preexec,chpwd}_functions
119     # arrays.
120     function precmd() {
121         for function in $precmd_functions; do
122             $function "$@"
123         done
124     }
125     function preexec() {
126         for function in $preexec_functions; do
127             $function "$@"
128         done
129     }
130     function chpwd() {
131         for function in $chpwd_functions; do
132             $function "$@"
133         done
134     }
135 fi
136
137 # Load zmv (zsh move) which is a powerful file renamer.
138 autoload -Uz zmv
139
140
141 # HISTORY SETTINGS
142
143 # Use history and store it in ~/.zsh/history.
144 HISTSIZE=50000
145 SAVEHIST=50000
146 HISTFILE=~/.zsh/history
147 # Append to the history file instead of overwriting it and do it immediately
148 # when a command is executed.
149 setopt appendhistory
150 setopt incappendhistory
151 # If the same command is run multiple times store it only once in the history.
152 setopt histignoredups
153 # Don't add lines starting with a space to the history.
154 setopt histignorespace
155 # Vim like completions of previous executed commands (also enter Vi-mode). If
156 # called at the beginning it just recalls old commands (like cursor up), if
157 # called after typing something, only lines starting with the typed text are
158 # returned. Very useful to get old commands quickly - in addition to the
159 # history commands (!..). Thanks to Mikachu in #zsh on Freenode (2010-01-17
160 # 12:47 CET) for the information how to a use function with bindkey.
161 zle -N zshrc-vi-history-beginning-search-backward
162 zshrc-vi-history-beginning-search-backward() {
163     local not_at_beginning_of_line
164     if [[ $CURSOR -ne 0 ]]; then
165         not_at_beginning_of_line=yes
166     fi
167
168     zle history-beginning-search-backward
169
170     # Start Vi-mode and stay at the same position (Vi-mode moves one left,
171     # this counters it).
172     zle vi-cmd-mode
173     if [[ -n $not_at_beginning_of_line ]]; then
174         zle vi-forward-char
175     fi
176 }
177 bindkey '^P' zshrc-vi-history-beginning-search-backward
178 bindkey -a '^P' history-beginning-search-backward # binding for Vi-mode
179 # Here only Vi-mode is necessary as ^P enters Vi-mode and ^N only makes sense
180 # after calling ^P.
181 bindkey -a '^N' history-beginning-search-forward
182
183 # Automatically push cd-ed directories on the directory stack.
184 setopt autopushd
185 # Don't push duplicates on the directory stack.
186 setopt pushdignoredups
187 # Exchange the meaning of + and - when specifying a directory on the stack.
188 # This way cd -<Tab> lists the last used directory first, which is more
189 # natural because cd - goes to the last directory.
190 setopt pushdminus
191
192
193 # PROMPT SETTINGS
194
195 # Use colorized output, necessary for prompts and completions.
196 autoload -Uz colors && colors
197
198 # Necessary for $EPOCHSECONDS, the UNIX time.
199 zmodload zsh/datetime
200
201 # Some shortcuts for colors. The %{...%} tells zsh that the data in between
202 # doesn't need any space, necessary for correct prompt drawing.
203 local red="%{${fg[red]}%}"
204 local blue="%{${fg[blue]}%}"
205 local green="%{${fg[green]}%}"
206 local yellow="%{${fg[yellow]}%}"
207 local default="%{${fg[default]}%}"
208
209 # vcs_info was added in 4.3.9 but it works in earlier versions too. So load it
210 # if the necessary files are available in ~/.zsh/functions/vcs_info (often a
211 # symbolic link to current checkout of Zsh's sources).
212 if [[ $ZSH_VERSION == (4.3.<9->*|4.<4->*|<5->*) ||
213       -d ~/.zsh/functions/vcs_info ]]; then
214     # Update fpath to allow loading the vcs_info functions.
215     if [[ -d ~/.zsh/functions/vcs_info ]]; then
216        fpath=(~/.zsh/functions/vcs_info/
217               ~/.zsh/functions/vcs_info/Backends
218               $fpath)
219     fi
220
221     # Load vcs_info to display information about version control repositories.
222     autoload -Uz vcs_info
223     # Only look for certain VCS.
224     zstyle ':vcs_info:*' enable git
225     # Check the repository for changes so they can be used in %u/%c (see
226     # below). This comes with a speed penalty for bigger repositories.
227     zstyle ':vcs_info:*' check-for-changes yes
228
229     # Set style of vcs_info display. The current branch (green) and VCS (blue)
230     # is displayed. If there is an special action going on (merge, rebase)
231     # it's also displayed (red). Also display if there are unstaged or staged
232     # (%u/%c) changes.
233     if [[ $ZSH_VERSION == (4.3.<11->*|4.<4->*|<5->*) ||
234           -d ~/.zsh/functions/vcs_info ]]; then
235         zstyle ':vcs_info:*' formats \
236             "(${green}%b%u%c${default}:${blue}%s${default}%m)" \
237             "${green}%u%c${default}"
238         zstyle ':vcs_info:*' actionformats \
239             "(${green}%b%u%c${default}/${red}%a${default}:${blue}%s${default}%m)" \
240             "${green}%u%c${default}"
241     else
242         # In older versions %u and %c are not defined yet and are not
243         # correctly expanded.
244         zstyle ':vcs_info:*' formats \
245             "(${green}%b${default}:${blue}%s${default})"
246         zstyle ':vcs_info:*' actionformats \
247             "(${green}%b${default}/${red}%a${default}:${blue}%s${default})"
248     fi
249     # Set style for formats/actionformats when unstaged (%u) and staged (%c)
250     # changes are detected in the repository; check-for-changes must be set to
251     # true for this to work. Thanks to Bart Trojanowski
252     # (http://jukie.net/~bart/blog/pimping-out-zsh-prompt) for the idea
253     # (2010-03-11 00:20 CET).
254     zstyle ':vcs_info:*' unstagedstr '¹'
255     zstyle ':vcs_info:*' stagedstr   '²'
256
257     # Default to run vcs_info. If possible we prevent running it later for
258     # speed reasons. If set to a non empty value vcs_info is run.
259     zshrc_force_run_vcs_info=1
260
261     # Cache system inspired by Bart Trojanowski
262     # (http://jukie.net/~bart/blog/pimping-out-zsh-prompt).
263     zstyle ':vcs_info:*+pre-get-data:*' hooks pre-get-data
264     +vi-pre-get-data() {
265         # Only Git and Mercurial support and need caching. Abort if any other
266         # VCS is used.
267         [[ "$vcs" != git && "$vcs" != hg ]] && return
268
269         # If the shell just started up or we changed directories (or for other
270         # custom reasons) we must run vcs_info.
271         if [[ -n $zshrc_force_run_vcs_info ]]; then
272             zshrc_force_run_vcs_info=
273             return
274         fi
275
276         # Don't run vcs_info by default to speed up the shell.
277         ret=1
278         # If a git/hg command was run then run vcs_info as the status might
279         # need to be updated.
280         case "$(fc -ln $(($HISTCMD-1)))" in
281             git* | g\ *)
282                 ret=0
283                 ;;
284             hg*)
285                 ret=0
286                 ;;
287         esac
288     }
289
290     # Display number of WIP stashes (this excludes manually named commits
291     # which might be used for something else), thanks to
292     # http://eseth.org/2010/git-in-zsh.html (viewed on 2013-04-27) for the
293     # idea to display the stash count.
294     function +vi-git-stashes() {
295         if [[ -s ${hook_com[base]/.git/refs/stash} ]]; then
296             local -a stashes
297             # Thanks to Valodim in #zsh on Freenode (2013-07-01 14:14 CEST)
298             # for the solution to "grep" the output with (M) and :#(...).
299             stashes=( ${(M)${(f)"$(git stash list 2>/dev/null)"}:#(*WIP*)} )
300
301             if [[ ${#stashes} -gt 0 ]]; then
302                 hook_com[misc]+=" ${yellow}${#stashes}s${default}"
303             fi
304         fi
305     }
306
307     # Apply hooks to Git.
308     zstyle ':vcs_info:git*+set-message:*' hooks git-stashes
309
310     # Must run vcs_info when changing directories.
311     prompt_chpwd() {
312         zshrc_force_run_vcs_info=1
313     }
314     chpwd_functions+=(prompt_chpwd)
315
316     # Used by prompt code below to determine if vcs_info should be run.
317     zshrc_use_vcs_info=1
318 else
319     zshrc_use_vcs_info=
320 fi
321
322 typeset -a zshrc_longrun_data
323 zshrc_longrun_data=()
324 # Display runtime in seconds for long running programs (> 60 seconds) and send
325 # a bell to notify me.
326 zshrc_longrun_preexec() {
327     local program="$3"
328
329     # Handle fg.
330     local REPLY
331     zshrc_resolve_fg_to_resumed_job_name "$program"
332     program="$REPLY"
333
334     # Don't track the time for certain (possible) long running processes which
335     # need no automatic notification.
336     for ignore in elinks man mutt vim; do
337         case $program in
338             $ignore | $ignore\ *)
339                 zshrc_longrun_data=()
340                 return
341                 ;;
342         esac
343     done
344
345     zshrc_longrun_data=("$program" $EPOCHSECONDS)
346 }
347 zshrc_longrun_precmd() {
348     # No previous timestamp available or disabled for this command, ignore.
349     if [[ -z $zshrc_longrun_data ]]; then
350         return
351     fi
352
353     local difference=$(( EPOCHSECONDS - zshrc_longrun_data[2] ))
354     if [[ $difference -gt 60 ]]; then
355         echo
356         echo -n "${fg[yellow]}"
357         echo -n "~> ${(V)zshrc_longrun_data[1]} took $difference seconds."
358         echo -n "${fg[default]}"
359         echo    "\a" # send bell
360     fi
361
362     # Clear status. Prevents displaying old status information when pressing
363     # enter with an empty command line.
364     zshrc_longrun_data=()
365 }
366 preexec_functions+=(zshrc_longrun_preexec)
367 precmd_functions+=(zshrc_longrun_precmd)
368
369 # Set the prompt. A two line prompt is used. On the top left the current
370 # working directory is displayed, on the right vcs_info (if available) and the
371 # current time in hex. On the bottom left current user name and host is shown,
372 # the exit code of the last command if it wasn't 0, the number of running jobs
373 # if not 0.
374 #
375 # The prompt is in green and blue to make easily detectable, the error exit
376 # code in red and bold and the job count in yellow. Designed for dark
377 # terminals.
378 #
379 # Thanks to Adam's prompt for the basic idea of this prompt.
380 zshrc_prompt_precmd() {
381     # Regex to remove elements which take no space. Used to calculate the
382     # width of the top prompt. Thanks to Bart's and Adam's prompt code in
383     # Functions/Prompts/prompt_*_setup.
384     local zero='%([BSUbfksu]|([FB]|){*})'
385
386     # Call vcs_info before every prompt.
387     if [[ -n $zshrc_use_vcs_info ]]; then
388         vcs_info
389     else
390         vcs_info_msg_0_=
391         vcs_info_msg_1_=
392     fi
393
394     # Setup. Create variables holding the formatted content.
395
396     # Current directory in yellow, truncated if necessary (WIDTH is replaced
397     # below).
398     local directory="${yellow}%WIDTH<..<%~%<<${default}"
399     # Minimal information about the VCS, only displayed if there are
400     # unstaged/staged changes.
401     local vcs_staged="${vcs_info_msg_1_}"
402
403     # Information about the VCS in this directory.
404     local vcs="${vcs_info_msg_0_}"
405     # Current time (seconds since epoch) in Hex in bright blue.
406     local seconds="${blue}%B0x$(([##16] EPOCHSECONDS))%b${default}"
407
408     # User name (%n) in bright green.
409     local user="${green}%B%n%b${default}"
410     # Host name (%m) in bright green; underlined if running on a remote system
411     # through SSH.
412     local host="${green}%B%m%b${default}"
413     if [[ -n $SSH_CONNECTION ]]; then
414         host="%U${host}%u"
415     fi
416
417     # Number of background processes in yellow if not zero.
418     local background="%(1j.${yellow}%j${default}.)"
419     # Exit code in bright red in parentheses if not zero.
420     local exitcode="%(?..(${red}%B%?%b${default}%) )"
421     # Prompt symbol, % for normal users, # in red for root.
422     local symbol="%(!.${red}#${default}.%%)"
423
424     # Prefix characters in first and second line.
425     local top_prefix="${blue}%B.-%b${default}"
426     local bottom_prefix="${blue}%B'%b${default}"
427
428     # Combine them to create the prompt.
429
430     local top_left="${vcs_staged}"
431     local top_right="${vcs}(${seconds})"
432
433     local width_top_prefix=${#${(S%%)top_prefix//$~zero/}}
434     local width_top_left=${#${(S%%)top_left//$~zero/}}
435     local width_top_right=${#${(S%%)top_right//$~zero/}}
436
437     # Calculate the maximum width of ${top_left}. -2 are the braces of
438     # ${top_left}, -1 is one separator from ${top_separator} (we want at least
439     # one between left and right parts).
440     local top_left_width_max=$((
441         COLUMNS - $width_top_prefix
442                 - $width_top_left - 2
443                 - 1
444                 - $width_top_right
445     ))
446     # Truncate directory if necessary.
447     top_left="(${directory/WIDTH/${top_left_width_max}})${top_left}"
448     width_top_left=${#${(S%%)top_left//$~zero/}}
449
450     # Calculate the width of the top prompt to fill the middle with "-".
451     local width=$((
452         COLUMNS - width_top_prefix - width_top_left - width_top_right
453     ))
454     local top_separator="%B${blue}${(l:${width}::-:)}%b${default}"
455
456     PROMPT="${top_prefix}${top_left}${top_separator}${top_right}
457 ${bottom_prefix}${user}@${host} ${background}${symbol} ${exitcode}"
458 }
459 precmd_functions+=(zshrc_prompt_precmd)
460
461
462 # When GNU screen, tmux, xterm or rxvt is used set the name of the window to
463 # the currently running program.
464 #
465 # When a program is started preexec() sets the window's name to it; when it
466 # stops precmd() resets the window's name to 'zsh'. 'fg' is supported and sets
467 # the window's name to the resumed job.
468 #
469 # It works with GNU screen, tmux, xterm and rxvt.
470 #
471 # If a command is run with sudo or if the shell is running as root then a ! is
472 # added at the beginning of the command to make this clear. If a command is
473 # running on a different computer with ssh a @ is added at the beginning. If
474 # screen/tmux is running on the remote machine instead of @screen @:hostname
475 # (or @tmux ..; hostname replaced by the machine's hostname) is displayed.
476 # This only works if the .zshrc on the server also uses this command.
477 #
478 # screen* is necessary as `screen` uses screen.linux for example for a linux
479 # console.
480 if [[ $TERM == screen* || $TERM == xterm* || $TERM == rxvt* ]]; then
481     # Is set to a non empty value to reset the window name in the next
482     # precmd() call.
483     zshrc_window_reset=yes
484
485     zshrc_window_preexec() {
486         # Get the program name with its arguments.
487         local program_name=$1
488
489         # When sudo is used, use real program name instead, but with an
490         # exclamation mark at the beginning (handled below).
491         local program_sudo=
492         if [[ $program_name == sudo* ]]; then
493             program_name=${program_name#sudo }
494             program_sudo=yes
495         fi
496
497         # Handle fg.
498         local REPLY
499         zshrc_resolve_fg_to_resumed_job_name "$program_name"
500         program_name="$REPLY"
501
502         # Remove all arguments from the program name.
503         program_name=${program_name%% *}
504
505         # Ignore often used commands which are only running for a very short
506         # time. This prevents a "blinking" name when it's changed to "cd" for
507         # example and then some milliseconds later back to "zsh".
508         [[ $program_name == (cd*|d|ls|l|la|ll|clear|c) ]] && return
509
510         # Change my shortcuts so the real name of the program is displayed.
511         case $program_name in
512             e)
513                 program_name=elinks
514                 ;;
515             g)
516                 program_name=git
517                 ;;
518             m)
519                 program_name=mutt
520                 ;;
521             v)
522                 program_name=vim
523                 ;;
524         esac
525
526         # Add an exclamation mark at the beginning if running with sudo or if
527         # running zsh as root.
528         if [[ -n $program_sudo || $UID -eq 0 ]]; then
529             program_name=!$program_name
530         fi
531
532         # Add an at mark at the beginning if running through ssh on a
533         # different computer.
534         if [[ -n $SSH_CONNECTION ]]; then
535             program_name="@$program_name"
536
537             # If screen is running in SSH then display "@:hostname" as title
538             # in the term/outer screen.
539             if [[ $program_name == @screen || $program_name == @tmux ]]; then
540                 program_name="@:${HOST//.*/}"
541             # Use "@:!hostname" for root screens.
542             elif [[ $program_name == @!screen || $program_name == @!tmux ]]; then
543                 program_name="@:!${HOST//.*/}"
544             fi
545         fi
546
547         # Set the window name to the currently running program.
548         zshrc_window_title "$program_name"
549
550         # Tell precmd() to reset the window name when the program stops.
551         zshrc_window_reset=yes
552     }
553
554     zshrc_window_precmd() {
555         # Abort if no window name reset is necessary.
556         [[ -z $zshrc_window_reset ]] && return
557
558         # Reset the window name to 'zsh'.
559         local name=zsh
560         # If the function was called with an argument then reset the window
561         # name to '.zsh' (used by clear alias).
562         if [[ -n $1 ]]; then
563             name=.zsh
564         fi
565
566         # Prepend prefixes like in window_preexec().
567         if [[ $UID -eq 0 ]]; then
568             name="!$name"
569         fi
570         if [[ -n $SSH_CONNECTION ]]; then
571             name="@$name"
572         fi
573         zshrc_window_title $name
574
575         # Just reset the name, so no screen reset necessary for the moment.
576         zshrc_window_reset=
577     }
578
579     # Sets the window title. Works with GNU screen, tmux (which uses screen as
580     # TERM), xterm and rxvt. (V) escapes all non-printable characters, thanks
581     # to Mikachu in #zsh on Freenode (2010-08-07 17:09 CEST).
582     if [[ $TERM == screen* ]]; then
583         zshrc_window_title() {
584             print -n "\ek${(V)1}\e\\"
585         }
586     elif [[ $TERM == xterm* || $TERM == rxvt* ]]; then
587         zshrc_window_title() {
588             print -n "\e]2;${(V)1}\e\\"
589         }
590     else
591         # Fallback if another TERM is used.
592         zshrc_window_title() { }
593     fi
594
595     # Add the preexec() and precmd() hooks.
596     preexec_functions+=(zshrc_window_preexec)
597     precmd_functions+=(zshrc_window_precmd)
598 else
599     # Fallback if another TERM is used, necessary to run screen (see below in
600     # "RUN COMMANDS").
601     zshrc_window_preexec() { }
602 fi
603
604
605 # COMPLETION SETTINGS
606
607 # Load the complist module which provides additional features to completion
608 # lists (coloring, scrolling).
609 zmodload zsh/complist
610 # Use new completion system, store dumpfile in ~/.zsh/cache to prevent
611 # cluttering of ~/. $fpath must be set before calling this. Thanks to Adlai in
612 # #zsh on Freenode (2009-08-07 21:05 CEST) for reminding me of the $fpath
613 # problem.
614 autoload -Uz compinit && compinit -d ~/.zsh/cache/zcompdump
615
616 # Use cache to speed up some slow completions (dpkg, perl modules, etc.).
617 zstyle ':completion:*' use-cache yes
618 zstyle ':completion:*' cache-path ~/.zsh/cache
619
620 # Let the completion system handle all completions, including expanding of
621 # shell wildcards (which is handled by other shell mechanisms if the default
622 # expand-or-complete is used).
623 bindkey '^I' complete-word
624 # If there are multiple matches after pressing <Tab> always display them
625 # immediately without requiring another <Tab>. a<Tab> completes to aa and
626 # lists aaa, aab, aac as possible completions if the directory contains aaa,
627 # aab, aac, bbb instead of only completing to aa.
628 setopt nolistambiguous
629 # Support completions in the middle of a word, without this option zsh jumps
630 # to the end of the word before the completion process begins. Is required for
631 # the _prefix completer.
632 setopt completeinword
633
634 zstyle ':completion:::::' completer \
635     _expand _complete _prefix _ignored _approximate
636
637 # Match specification to be tried when completing items. Each group ('...') is
638 # tried after another if no matches were found, once matches are found no
639 # other groups are tried. Thanks to Mikachu in #zsh on Freenode (2012-08-28
640 # 18:48 CEST) for explanations.
641 #
642 # When matching also include the uppercase variant of typed characters
643 # ('m:{a-z}={A-Z}'); using '' before this group would try the unmodified match
644 # first, but I prefer to get all matches immediately (e.g. if Makefile and
645 # makefile exist in the current directory echo m<tab> matches both, with '' it
646 # would only match makefile because it found one match). This allows typing in
647 # lowercase most of the time and completion fixes the case, which is faster.
648 #
649 # Don't perform these fixes in _approximate to prevent it from changing the
650 # input too much. Thanks to the book "From Bash to Z Shell" page 249.
651 zstyle ':completion:*:(^approximate):*' matcher-list 'm:{a-z}={A-Z}'
652
653 # Allow one mistake per three characters. Thanks to the book "From Bash to Z
654 # Shell" page 248.
655 zstyle -e ':completion:*:approximate:*' max-errors \
656     'reply=( $(( ($#PREFIX + $#SUFFIX) / 3 )) )'
657
658 # Expand shell wildcards to all matching files after <Tab>. echo *<Tab>
659 # results in a b c if the directory contains the files a, b, c. Thanks to the
660 # book "From Bash to Z Shell" page 246.
661 zstyle ':completion:*:expand:*' tag-order all-expansions
662 # Keep prefixes unexpanded if possible: $HOME/<Tab> doesn't expand $HOME,
663 # while $HOME<Tab> does.
664 zstyle ':completion:*:expand:*' keep-prefix yes
665
666 # When completing multiple path components display all matching ambiguous
667 # components. For example /u/s/d/r/README<Tab> lists all matching READMEs
668 # instead of just the matching paths up to the r/ component. Can be slow if
669 # there are many matching files.
670 zstyle ':completion:*' list-suffixes yes
671
672 # Use ls-like colors for completions.
673 zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
674
675 # Make completion lists scrollable so "do you wish to see all n possibilities"
676 # is no longer displayed. Display current position in percent (%p).
677 zstyle ':completion:*:default' list-prompt '%p'
678 # Display group name (%d) (like 'external command', 'alias', etc.), in bold.
679 # Also display a message if _approximate found errors and no matches were
680 # found.
681 zstyle ':completion:*'             format '    %B%d%b:'
682 zstyle ':completion:*:corrections' format '    %B%d%b (errors: %e)'
683 zstyle ':completion:*:warnings'    format '    %Bno matches for %d%b'
684 # Display different types of matches separately.
685 zstyle ':completion:*' group-name ''
686
687 # Separate man pages by section.
688 zstyle ':completion:*' separate-sections yes
689
690 # Don't draw trailing / in bold (new in zsh 4.3.11). Thanks to Mikachu in #zsh
691 # on Freenode for the fix (2010-12-17 13:46 CET).
692 zle_highlight=(suffix:none)
693
694 # Ignore completion functions.
695 zstyle ':completion:*:functions' ignored-patterns '_*'
696 # Ignore parent directory.
697 zstyle ':completion:*:(cd|mv|cp):*' ignore-parents parent pwd
698 # Always complete file names only once in the current line. This makes it easy
699 # to complete multiple file names because I can just press tab to get all
700 # possible values. Otherwise I would have to skip the first value again and
701 # again. Thanks to Mikachu in #zsh on Freenode (2011-08-11 14:42 CEST) for the
702 # hint to use other. other is necessary so prefix<Tab> lists both prefix and
703 # prefixrest if the directory contains prefix and prefixrest.
704 zstyle ':completion:*:all-files' ignore-line other
705 # Except for mv and cp, because I often want to use to similar names, so I
706 # complete to the same and change it.
707 zstyle ':completion:*:(mv|cp):all-files' ignore-line no
708
709 # Don't complete ./config.* files, this makes running ./configure much
710 # simpler. Thanks to Nomexous in #zsh on Freenode (2010-03-16 01:54 CET)
711 zstyle ':completion:*:*:-command-:*' ignored-patterns './config.*'
712 # Don't complete unwanted files with Vim. Thanks to Nomexous in #zsh on
713 # Freenode (2010-06-06 04:54 CEST). See below for a way to complete them.
714 zstyle ':completion:*:*:vim:*:all-files' ignored-patterns \
715     '*.aux' '*.log' '*.pdf' \
716     '*.class'
717
718 # Provide a fallback completer which always completes files. Useful when Zsh's
719 # completion is too "smart". Thanks to Frank Terbeck <ft@bewatermyfriend.org>
720 # (http://www.zsh.org/mla/users/2009/msg01038.html).
721 zle -C complete-files complete-word _generic
722 zstyle ':completion:complete-files:*' completer _files
723 bindkey '^F' complete-files
724
725
726 # CUSTOM ALIASES AND FUNCTIONS
727
728 # If ^C is pressed while typing a command, add it to the history so it can be
729 # easily retrieved later and then abort like ^C normally does. This is useful
730 # when I want to abort an command to do something in between and then finish
731 # typing the command.
732 #
733 # Thanks to Vadim Zeitlin <vz-zsh@zeitlins.org> for a fix (--) so lines
734 # starting with - don't cause errors; and to Nadav Har'El
735 # <nyh@math.technion.ac.il> for a fix (-r) to handle whitespace/quotes
736 # correctly, both on the Zsh mailing list.
737 TRAPINT() {
738     # Don't store this line in history if histignorespace is enabled and the
739     # line starts with a space.
740     if [[ -o histignorespace && ${BUFFER[1]} = " " ]]; then
741         return $1
742     fi
743
744     # Store the current buffer in the history.
745     zle && print -s -r -- $BUFFER
746
747     # Return the default exit code so Zsh aborts the current command.
748     return $1
749 }
750
751 # Load aliases and similar functions also used by other shells.
752 if [[ -f ~/.shell/aliases ]]; then
753     . ~/.shell/aliases
754 fi
755
756 # Make sure aliases are expanded when using sudo.
757 alias sudo='sudo '
758
759 # Global aliases for often used redirections.
760 alias -g E='2>&1'
761 alias -g N='>/dev/null'
762 alias -g EN='2>/dev/null'
763 alias -g L='2>&1 | less'
764 alias -g LS='2>&1 | less -S' # -S prevents wrapping of long lines
765 alias -g D='2>&1 | colordiff | less'
766 # Global aliases for often used commands.
767 alias -g A='| awk'
768 alias -g G='| grep'
769 alias -g H='| head'
770 alias -g P='| perl'
771 alias -g S='| sort'
772 alias -g T='| tail'
773 alias -g U='| uniq'
774
775 # Make going up directories simple.
776 alias -g ...='../..'
777 alias -g ....='../../..'
778 alias -g .....='../../../..'
779
780 # If the window naming feature is used (see above) then use ".zsh" (leading
781 # dot) as title name after running clear so it's clear to me that the window
782 # is empty. I open so much windows that I don't know in which I have something
783 # important. This helps me to remember which windows are empty (I run clear
784 # after I finished my work in a window).
785 if [[ -n $zshrc_window_reset ]]; then
786     alias clear='clear; zshrc_window_reset=yes; zshrc_window_precmd reset'
787 fi
788
789
790 # CUSTOM COMMANDS
791
792 # Display all branches (except stash) in gitk but only 200 commits as this is
793 # much faster. Also put in the background and disown. Thanks to drizzd in #git
794 # on Freenode (2010-04-03 17:55 CEST).
795 (( $+commands[gitk] )) && gitk() {
796     command gitk --max-count=200 --branches --remotes --tags "$@" &
797     disown %command
798 }
799 # Same for tig (except the disown part as it's no GUI program).
800 (( $+commands[tig] )) && tig() {
801     command tig --max-count=200 --branches --remotes --tags "$@"
802 }
803
804 # Pipe output through less.
805 (( $+commands[tree] )) && tree() {
806     command tree -C "$@" | less
807 }
808
809 # Choose the "best" PDF viewer available: xpdf, then zathura (in the past
810 # zathura was preferred, but recent versions are completely broken: still no
811 # working search and no page-wise scrolling anymore). Also setup completion
812 # for `pdf`.
813 if (( $+commands[xpdf] )); then
814     pdf() {
815         command xpdf "$@" 2>/dev/null &
816         disown %command
817     }
818     compdef _xpdf pdf
819 elif (( $+commands[zathura] )); then
820     pdf() {
821         command zathura "$@" 2>/dev/null &
822         disown %command
823     }
824     # No completion for zathura yet.
825     compdef _xpdf pdf
826 fi
827
828 # GHCI doesn't use readline, force it if rlwrap is available.
829 (( $+commands[rlwrap] )) && ghci() {
830     command rlwrap \
831         --always-readline --complete-filenames -t dumb \
832         --histsize 5000 \
833         --file ~/.shell/rlwrap/ghci \
834         ghci "$@" 2>&1
835 }
836
837
838 # OS SPECIFIC SETTINGS
839
840 if [[ $OSTYPE == linux* ]]; then
841     # Settings when creating Debian packages.
842     export DEBEMAIL=simon@ruderich.org
843     export DEBFULLNAME='Simon Ruderich'
844 fi
845
846
847 # LOAD ADDITIONAL CONFIGURATION FILES
848
849 # Configuration option for rc.local to use GNU screen/tmux. By default GNU
850 # screen is used. Possible values: screen, tmux and empty (no value).
851 zshrc_use_multiplexer=screen
852
853 source_config ~/.zsh/rc.local
854
855
856 # RUN COMMANDS
857
858 # Make sure the multiplexer is available. Otherwise the exec terminates our
859 # session.
860 if [[ -n $zshrc_use_multiplexer ]]; then
861     if ! (( $+commands[$zshrc_use_multiplexer] )); then
862         echo "Multiplexer '$zshrc_use_multiplexer' not found." >&2
863         zshrc_use_multiplexer=
864     fi
865 fi
866
867 # If not already in screen or tmux, reattach to a running session or create a
868 # new one. This also starts screen/tmux on a remote server when connecting
869 # through ssh.
870 if [[ $TERM != dumb && $TERM != linux && -z $STY && -z $TMUX ]]; then
871     # Get running detached sessions.
872     if [[ $zshrc_use_multiplexer = screen ]]; then
873         session=$(screen -list | grep 'Detached' | awk '{ print $1; exit }')
874     elif [[ $zshrc_use_multiplexer = tmux ]]; then
875         session=$(tmux list-sessions 2>/dev/null \
876                   | sed '/(attached)$/ d; s/^\([0-9]\{1,\}\).*$/\1/; q')
877     fi
878
879     # As we exec later we have to set the title here.
880     if [[ $zshrc_use_multiplexer = screen ]]; then
881         zshrc_window_preexec screen
882     elif [[ $zshrc_use_multiplexer = tmux ]]; then
883         zshrc_window_preexec tmux
884     fi
885
886     # Create a new session if none is running.
887     if [[ -z $session ]]; then
888         if [[ $zshrc_use_multiplexer = screen ]]; then
889             exec screen
890         elif [[ $zshrc_use_multiplexer = tmux ]]; then
891             exec tmux
892         fi
893     # Reattach to a running session.
894     else
895         if [[ $zshrc_use_multiplexer = screen ]]; then
896             exec screen -r $session
897         elif [[ $zshrc_use_multiplexer = tmux ]]; then
898             exec tmux attach-session -t $session
899         fi
900     fi
901 fi
902
903 # Colorize stderr in red. Very useful when looking for errors. Thanks to
904 # http://gentoo-wiki.com/wiki/Zsh for the basic script and Mikachu in #zsh on
905 # Freenode (2010-03-07 04:03 CET) for some improvements (-r, printf). It's not
906 # yet perfect and doesn't work with su and git for example, but it can handle
907 # most interactive output quite well (even with no trailing new line) and in
908 # cases it doesn't work, the E alias can be used as workaround.
909 #
910 # Moved in the "run commands" section to prevent one unnecessary zsh process
911 # when starting GNU screen/tmux (see above).
912 exec 2>>(while read -r -k -u 0 line; do
913     printf '\e[91m%s\e[0m' "$line"
914     print -n $'\0'
915 done &)
916
917 # Display possible log messages from ~/.xinitrc (if `xmessage` wasn't
918 # installed). No race condition as xinitrc has finished before a shell is
919 # executed and only one shell is started on login.
920 if [[ -f ~/.xinitrc.errors ]]; then
921     echo "${fg_bold[red]}xinitrc failed!${fg_bold[default]}"
922     echo
923     cat ~/.xinitrc.errors
924     rm ~/.xinitrc.errors
925     echo
926 fi
927
928 # Run the following programs every 4 hours (and when zsh starts).
929 PERIOD=14400
930 periodic() {
931     # Display fortunes.
932     (( $+commands[fortune] )) && fortune -ac
933     # Display reminders.
934     (( $+commands[rem] )) && [[ -f ~/.reminders ]] && rem -h
935 }
936
937
938 # RESTART SETTINGS
939
940 zmodload -F zsh/stat b:zstat
941
942 # Remember startup time. Used to perform automatic restarts when ~/.zshrc is
943 # modified.
944 zshrc_startup_time=$EPOCHSECONDS
945
946 # Automatically restart Zsh if ~/.zshrc was modified.
947 zshrc_restart_precmd() {
948     local stat
949     if ! zstat -A stat +mtime ~/.zshrc; then
950         return
951     fi
952
953     # ~/.zshrc wasn't modified, nothing to do.
954     if [[ $stat -le $zshrc_startup_time ]]; then
955         return
956     fi
957
958     local startup
959     strftime -s startup '%Y-%m-%d %H:%M:%S' "$zshrc_startup_time"
960
961     echo -n "${fg[magenta]}"
962     echo -n "~/.zshrc modified since startup ($startup) ... "
963     echo -n "${fg[default]}"
964
965     if [[ -n $zshrc_disable_restart ]]; then
966         echo 'automatic restart disabled.'
967         return
968     fi
969
970     # Don't exec if we have background processes because execing will let us
971     # lose control over them.
972     if [[ ${#${(k)jobstates}} -ne 0 ]]; then
973         echo 'active background jobs!'
974         return
975     fi
976
977     # Try to start a new interactive shell. If it fails, something is wrong.
978     # Don't kill our current session by execing it.
979     zsh -i -c 'exit 42'
980     if [[ $? -ne 42 ]]; then
981         echo -n "${fg_bold[red]}"
982         echo 'failed to start new zsh!'
983         echo -n "${fg_bold[default]}"
984         return
985     fi
986
987     echo 'restarting zsh.'
988     echo
989
990     exec zsh
991 }
992 precmd_functions+=(zshrc_restart_precmd)
993
994
995 source_debug '. ~/.zsh/rc (done)'
996
997 # vim: ft=zsh