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