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