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