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