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