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