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