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