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