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