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