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