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