1 # Zsh configuration file.
4 source_debug ". ~/.zsh/rc"
6 # MISCELLANEOUS SETTINGS
8 # Be paranoid, new files are readable/writable by me only.
14 # Prevent overwriting existing files with '> filename', use '>| filename'
18 # Entering the name of a directory (if it's not a command) will automatically
19 # cd to that directory.
22 # When entering a nonexistent command name automatically try to find a similar
26 # Enable zsh's extended glob abilities.
29 # Don't exit if <C-d> is pressed.
35 # Not all bindings are done here, only those not specific to a given section.
37 # Use Vi(m) style key bindings.
40 # Use jj and jk to exit insert mode.
41 bindkey 'jj' vi-cmd-mode
42 bindkey 'jk' vi-cmd-mode
44 # I don't need the arrow keys, I use ^N and ^P for this (see below).
45 bindkey -r '^[OA' '^[OB' '^[OC' '^[OD' '^[[A' '^[[B' '^[[C' '^[[D'
46 # Also not in Vi mode.
47 bindkey -a -r '^[OA' '^[OB' '^[OC' '^[OD' '^[[A' '^[[B' '^[[C' '^[[D'
52 # Make sure every entry in $fpath is unique.
54 # ~/.zsh/functions/completion is a symbolic link to the Completion directory
55 # of a Zsh CVS checkout. Use it to get the newest completions if available.
56 if [[ -d ~/.zsh/functions/completion ]]; then
57 fpath=(~/.zsh/functions/completion/*/*(/) $fpath)
59 # Set correct fpath to allow loading my functions (including completion
61 fpath=(~/.zsh/functions $fpath)
62 # Autoload my functions (except completion functions and hidden files). Thanks
63 # to caphuso from the Zsh example files for this idea.
64 if [[ -d ~/.zsh/functions ]]; then
65 autoload -Uz ${fpath[1]}/^_*(^/:t)
68 # Simulate hooks using _functions arrays for Zsh versions older than 4.3.4. At
69 # the moment only precmd(), preexec() and chpwd() are simulated.
71 # At least 4.3.4 (not sure about later versions) has an error in add-zsh-hook
72 # so the compatibility version is used there too.
73 if [[ $ZSH_VERSION != (4.3.<5->|4.<4->*|<5->*) ]]; then
74 # Provide add-zsh-hook which was added in 4.3.4.
75 fpath=(~/.zsh/functions/compatibility $fpath)
77 # Run all functions defined in the ${precmd,preexec,chpwd}_functions
80 for function in $precmd_functions; do
85 for function in $preexec_functions; do
90 for function in $chpwd_functions; do
96 # Autoload add-zsh-hook to add/remove zsh hook functions easily.
97 autoload -Uz add-zsh-hook
99 # Load zmv (zsh move) which is a powerful file renamer.
105 # Use history and store it in ~/.zsh/history.
108 HISTFILE=~/.zsh/history
109 # Append to the history file instead of overwriting it and do it immediately
110 # when a command is executed.
112 setopt incappendhistory
113 # If the same command is run multiple times store it only once in the history.
114 setopt histignoredups
115 # Vim like completions of previous executed commands (also enter Vi-mode). If
116 # called at the beginning it just recalls old commands (like cursor up), if
117 # called after typing something, only lines starting with the typed text are
118 # returned. Very useful to get old commands quickly - in addition to the
119 # history commands (!..). Thanks to Mikachu in #zsh on Freenode (2010-01-17
120 # 12:47 CET) for the information how to a use function with bindkey.
121 zle -N my-vi-history-beginning-search-backward
122 my-vi-history-beginning-search-backward() {
123 local not_at_beginning_of_line
124 if [[ $CURSOR -ne 0 ]]; then
125 not_at_beginning_of_line=yes
128 zle history-beginning-search-backward
130 # Start Vi-mode and stay at the same position (Vi-mode moves one left,
133 if [[ -n $not_at_beginning_of_line ]]; then
137 bindkey '^P' my-vi-history-beginning-search-backward
138 bindkey -a '^P' history-beginning-search-backward # binding for Vi-mode
139 # Here only Vi-mode is necessary as ^P enters Vi-mode and ^N only makes sense
141 bindkey -a '^N' history-beginning-search-forward
143 # Automatically push cd-ed directories on the directory stack.
145 # Don't push duplicates on the directory stack.
146 setopt pushdignoredups
147 # Exchange the meaning of + and - when specifying a directory on the stack.
148 # This way cd -<Tab> lists the last used directory first, which is more
149 # natural because cd - goes to the last directory.
155 # Use colorized output, necessary for prompts and completions.
156 autoload -Uz colors && colors
158 # Necessary for $EPOCHSECONDS, the UNIX time.
159 zmodload zsh/datetime
161 # Some shortcuts for colors. The %{...%} tells zsh that the data in between
162 # doesn't need any space, necessary for correct prompt drawing.
163 local red="%{${fg[red]}%}"
164 local blue="%{${fg[blue]}%}"
165 local green="%{${fg[green]}%}"
166 local yellow="%{${fg[yellow]}%}"
167 local default="%{${fg[default]}%}"
169 # vcs_info was added in 4.3.9 but it works in earlier versions too. So load it
170 # if the necessary files are available in ~/.zsh/functions/vcs_info (often a
171 # symbolic link to current checkout of Zsh's sources).
172 if [[ $ZSH_VERSION == (4.3.<9->|4.<4->*|<5->*) ||
173 -d ~/.zsh/functions/vcs_info ]]; then
174 # Update fpath to allow loading the vcs_info functions.
175 if [[ -d ~/.zsh/functions/vcs_info ]]; then
176 fpath=(~/.zsh/functions/vcs_info/
177 ~/.zsh/functions/vcs_info/Backends
181 # Load vcs_info to display information about version control repositories.
182 autoload -Uz vcs_info
183 # Only look for git and mercurial repositories; the only I use.
184 zstyle ':vcs_info:*' enable git hg
185 # Check the repository for changes so they can be used in %u/%c (see
186 # below). This comes with a speed penalty for bigger repositories.
187 zstyle ':vcs_info:*' check-for-changes yes
189 # Set style of vcs_info display. The current branch (green) and VCS (blue)
190 # is displayed. If there is an special action going on (merge, rebase)
191 # it's also displayed (red). Also display if there are unstaged or staged
193 if [[ $ZSH_VERSION == (4.3.<11->|4.<4->*|<5->*) ||
194 -d ~/.zsh/functions/vcs_info ]]; then
195 zstyle ':vcs_info:*' formats \
196 "($green%b%u%c$default:$blue%s$default)"
197 zstyle ':vcs_info:*' actionformats \
198 "($green%b%u%c$default/$red%a$default:$blue%s$default)"
200 # In older versions %u and %c are not defined yet and are not
201 # correctly expanded.
202 zstyle ':vcs_info:*' formats \
203 "($green%b$default:$blue%s$default)"
204 zstyle ':vcs_info:*' actionformats \
205 "($green%b$default/$red%a$default:$blue%s$default)"
207 # Set style for formats/actionformats when unstaged (%u) and staged (%c)
208 # changes are detected in the repository; check-for-changes must be set to
209 # true for this to work. Thanks to Bart Trojanowski
210 # (http://jukie.net/~bart/blog/pimping-out-zsh-prompt) for the idea
211 # (2010-03-11 00:20 CET).
212 zstyle ':vcs_info:*' unstagedstr '¹'
213 zstyle ':vcs_info:*' stagedstr '²'
215 # Default to run vcs_info. If possible we prevent running it later for
216 # speed reasons. If set to a non empty value vcs_info is run.
219 # Cache system inspired by Bart Trojanowski
220 # (http://jukie.net/~bart/blog/pimping-out-zsh-prompt).
221 zstyle ':vcs_info:*+pre-get-data:*' hooks pre-get-data
223 # Only Git and Mercurial support and need caching. Abort if any other
225 [[ "$vcs" != git && "$vcs" != hg ]] && return
227 # If the shell just started up or we changed directories (or for other
228 # custom reasons) we must run vcs_info.
229 if [[ -n $FORCE_RUN_VCS_INFO ]]; then
234 # Don't run vcs_info by default to speed up the shell.
236 # If a git/hg command was run then run vcs_info as the status might
237 # need to be updated.
238 case "$(fc -ln $(($HISTCMD-1)))" in
248 # Must run vcs_info when changing directories.
252 add-zsh-hook chpwd prompt_chpwd
254 # Used by prompt code below to determine if vcs_info should be run.
260 # Set the prompt. A two line prompt is used. On the top left the current
261 # working directory is displayed, on the right vcs_info (if available) and the
262 # current time in hex. On the bottom left current user name and host is shown,
263 # the exit code of the last command if it wasn't 0, the number of running jobs
266 # The prompt is in green and blue to make easily detectable, the error exit
267 # code in red and bold and the job count in yellow.
269 # Thanks to Adam's prompt for the basic idea of this prompt.
271 # Regex to remove elements which take no space. Used to calculate the
272 # width of the top prompt. Thanks to Bart's and Adam's prompt code in
273 # Functions/Prompts/prompt_*_setup.
274 local zero='%([BSUbfksu]|([FB]|){*})'
276 # Call vcs_info before every prompt.
277 if [[ -n $RUN_VCS_INFO ]]; then
283 local width width_left width_right
284 local top_left top_right
286 # Display the current time in HEX in bright blue and vcs_info (if used) on
287 # the right in the top prompt.
288 top_right="$vcs_info_msg_0_($blue%B0x$(([##16] EPOCHSECONDS))%b$default)"
289 width_right=${#${(S%%)top_right//$~zero/}}
290 # Remove it if it would get too long.
291 if [[ $(( COLUMNS - 4 - 1 - width_right )) -lt 0 ]]; then
296 # Display current directory on the left in the top prompt. Truncate the
297 # directory if necessary.
298 width=$(( COLUMNS - 4 - 1 - width_right ))
299 top_left=".-$default%b($yellow%$width<..<%~%<<$default)%B$blue"
301 # Calculate the width of the top prompt to fill the middle with "-".
302 width_left=${#${(S%%)top_left//$~zero/}}
303 width_right=${#${(S%%)top_right//$~zero/}}
304 width=$(( COLUMNS - width_left - width_right ))
306 PROMPT="$blue%B$top_left${(l:$width::-:)}%b$default$top_right
308 $green%B%n%b$default@$green%B%m%b$default %(1j.$yellow%j$default.)%# \
309 %(?..($red%B%?%b$default%) )"
311 add-zsh-hook precmd prompt_precmd
314 # When screen, xterm or rxvt is used set the name of the window to the
315 # currently running program.
317 # When a program is started preexec() sets the window's name to it; when it
318 # stops precmd() resets the window's name to 'zsh'.
320 # It works with screen, xterm and rxvt.
322 # If a command is run with sudo or if the shell is running as root then a ! is
323 # added at the beginning of the command to make this clear. If a command is
324 # running on a different computer with ssh a @ is added at the beginning. If
325 # screen is running on the remote machine instead of @screen @:hostname
326 # (hostname replaced by the machine's hostname) is displayed. This only works
327 # if the .zshrc on the server also uses this command.
329 # screen* is necessary as `screen` uses screen.linux for example for a linux
331 if [[ $TERM == screen* || $TERM == xterm* || $TERM == rxvt* ]]; then
332 # Is set to a non empty value to reset the window name in the next
335 # Is set to a non empty value when the shell is running as root.
336 if [[ $UID -eq 0 ]]; then
341 # Get the program name with its arguments.
342 local program_name=$1
344 # When sudo is used use real program name instead, but with an
345 # exclamation mark at the beginning (handled below).
347 if [[ $program_name == sudo* ]]; then
348 program_name=${program_name#sudo }
351 # Remove all arguments from the program name.
352 program_name=${program_name%% *}
354 # Ignore often used commands which are only running for a very short
355 # time. This prevents a "blinking" name when it's changed to "cd" for
356 # example and then some milliseconds later back to "zsh".
357 [[ $program_name == (cd*|d|ls|l|la|ll|clear|c) ]] && return
359 # Change my shortcuts so the real name of the program is displayed.
360 case $program_name in
375 # Add an exclamation mark at the beginning if running with sudo or if
376 # running zsh as root.
377 if [[ -n $program_sudo || -n $window_root ]]; then
378 program_name=!$program_name
381 # Add an at mark at the beginning if running through ssh on a
382 # different computer.
383 if [[ -n $SSH_CONNECTION ]]; then
384 program_name="@$program_name"
386 # If screen is running in SSH then display "@:hostname" as title
387 # in the term/outer screen.
388 if [[ $program_name == @screen ]]; then
389 program_name="@:${HOST//.*/}"
390 # Use "@:!hostname" for root screens.
391 elif [[ $program_name == @!screen ]]; then
392 program_name="@:!${HOST//.*/}"
396 # Set the window name to the currently running program.
397 window_title "$program_name"
399 # Tell precmd() to reset the window name when the program stops.
404 # Abort if no window name reset is necessary.
405 [[ -z $window_reset ]] && return
407 # Reset the window name to 'zsh'.
409 # If the function was called with an argument then reset the window
410 # name to '.zsh' (used by clear alias).
415 # Prepend prefixes like in window_preexec().
416 if [[ -n $window_root ]]; then
419 if [[ -n $SSH_CONNECTION ]]; then
424 # Just reset the name, so no screen reset necessary for the moment.
428 # Sets the window title. Works with screen, xterm and rxvt. (V) escapes
429 # all non-printable characters. Thanks to Mikachu in #zsh on Freenode
430 # (2010-08-07 17:09 CEST).
431 if [[ $TERM == screen* ]]; then
433 print -n "\ek${(V)1}\e\\"
435 elif [[ $TERM == xterm* || $TERM == rxvt* ]]; then
437 print -n "\e]2;${(V)1}\e\\"
440 # Fallback if another TERM is used.
444 # Add the preexec() and precmd() hooks.
445 add-zsh-hook preexec window_preexec
446 add-zsh-hook precmd window_precmd
448 # Fallback if another TERM is used, necessary to run screen (see below in
454 # COMPLETION SETTINGS
456 # Load the complist module which provides additional features to completion
457 # lists (coloring, scrolling).
458 zmodload zsh/complist
459 # Use new completion system, store dumpfile in ~/.zsh/cache to prevent
460 # cluttering of ~/. $fpath must be set before calling this. Thanks to Adlai in
461 # #zsh on Freenode (2009-08-07 21:05 CEST) for reminding me of the $fpath
463 autoload -Uz compinit && compinit -d ~/.zsh/cache/zcompdump
465 # Use cache to speed up some slow completions (dpkg, perl modules, etc.).
466 zstyle ':completion:*' use-cache yes
467 zstyle ':completion:*' cache-path ~/.zsh/cache
469 # Let the completion system handle all completions, including expanding of
470 # shell wildcards (which is handled by other shell mechanisms if the default
471 # expand-or-complete is used).
472 bindkey '^I' complete-word
473 # If there are multiple matches after pressing <Tab> always display them
474 # immediately without requiring another <Tab>. a<Tab> completes to aa and
475 # lists aaa, aab, aac as possible completions if the directory contains aaa,
476 # aab, aac, bbb instead of only completing to aa.
477 setopt nolistambiguous
478 # Support completions in the middle of a word, without this option zsh jumps
479 # to the end of the word before the completion process begins. Is required for
480 # the _prefix completer.
481 setopt completeinword
483 zstyle ':completion:::::' completer \
484 _expand _complete _prefix _ignored _approximate
486 # Try uppercase if the currently typed string doesn't match. This allows
487 # typing in lowercase most of the time and completion fixes the case. Don't
488 # perform these fixes in _approximate to prevent it from changing the input
489 # too much. Thanks to the book "From Bash to Z Shell" page 249.
490 zstyle ':completion:*:(^approximate):*' matcher-list 'm:{a-z}={A-Z}'
492 # Allow one mistake per three characters. Thanks to the book "From Bash to Z
494 zstyle -e ':completion:*:approximate:*' max-errors \
495 'reply=( $(( ($#PREFIX + $#SUFFIX) / 3 )) )'
497 # Expand shell wildcards to all matching files after <Tab>. echo *<Tab>
498 # results in a b c if the directory contains the files a, b, c. Thanks to the
499 # book "From Bash to Z Shell" page 246.
500 zstyle ':completion:*:expand:*' tag-order all-expansions
501 # Keep prefixes unexpanded if possible: $HOME/<Tab> doesn't expand $HOME,
502 # while $HOME<Tab> does.
503 zstyle ':completion:*:expand:*' keep-prefix yes
505 # When completing multiple path components display all matching ambiguous
506 # components. For example /u/s/d/r/README<Tab> lists all matching READMEs
507 # instead of just the matching paths up to the r/ component. Can be slow if
508 # there are many matching files.
509 zstyle ':completion:*' list-suffixes yes
511 # Use ls-like colors for completions.
512 zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
514 # Make completion lists scrollable so "do you wish to see all n possibilities"
515 # is no longer displayed. Display current position in percent (%p).
516 zstyle ':completion:*:default' list-prompt '%p'
517 # Display group name (%d) (like 'external command', 'alias', etc.), in bold.
518 # Also display a message if _approximate found errors and if no matches were
520 zstyle ':completion:*' format ' %B%d%b:'
521 zstyle ':completion:*:corrections' format ' %B%d%b (errors: %e)'
522 zstyle ':completion:*:warnings' format ' %Bno matches for %d%b'
523 # Display different types of matches separately.
524 zstyle ':completion:*' group-name ''
526 # Separate man pages by section.
527 zstyle ':completion:*' separate-sections yes
529 # Don't draw trailing / in bold (new in zsh 4.3.11). Thanks to Mikachu in #zsh
530 # on Freenode for the fix (2010-12-17 13:46 CET).
531 zle_highlight=(suffix:none)
533 # Ignore completion functions.
534 zstyle ':completion:*:functions' ignored-patterns '_*'
535 # Ignore parent directory.
536 zstyle ':completion:*:(cd|mv|cp):*' ignore-parents parent pwd
537 # Always complete file names only once in the current line. This makes it easy
538 # to complete multiple file names because I can just press tab to get all
539 # possible values. Otherwise I would have to skip the first value again and
540 # again. Thanks to Mikachu in #zsh on Freenode (2011-08-11 14:42 CEST) for the
541 # hint to use other. other is necessary so prefix<Tab> lists both prefix and
542 # prefixrest if the directory contains prefix and prefixrest.
543 zstyle ':completion:*:all-files' ignore-line other
544 # Except for mv and cp, because I often want to use to similar names, so I
545 # complete to the same and change it.
546 zstyle ':completion:*:(mv|cp):all-files' ignore-line no
548 # Don't complete ./config.* files, this makes running ./configure much
549 # simpler. Thanks to Nomexous in #zsh on Freenode (2010-03-16 01:54 CET)
550 zstyle ':completion:*:*:-command-:*' ignored-patterns './config.*'
551 # Don't complete unwanted files with Vim. Thanks to Nomexous in #zsh on
552 # Freenode (2010-06-06 04:54 CEST). See below for a way to complete them.
553 zstyle ':completion:*:*:vim:*:all-files' ignored-patterns \
554 '*.aux' '*.log' '*.pdf' \
557 # Provide a fallback completer which always completes files. Useful when Zsh's
558 # completion is too "smart". Thanks to Frank Terbeck <ft@bewatermyfriend.org>
559 # (http://www.zsh.org/mla/users/2009/msg01038.html).
560 zle -C complete-files complete-word _generic
561 zstyle ':completion:complete-files:*' completer _files
562 bindkey '^F' complete-files
565 # CUSTOM ALIASES AND FUNCTIONS
567 # If ^C is pressed while typing a command, add it to the history so it can be
568 # easily retrieved later and then abort like ^C normally does. This is useful
569 # when I want to abort an command to do something in between and then finish
570 # typing the command.
572 # Thanks to Vadim Zeitlin <vz-zsh@zeitlins.org> for a fix (--) so lines
573 # starting with - don't cause errors; and to Nadav Har'El
574 # <nyh@math.technion.ac.il> for a fix (-r) to handle whitespace/quotes
575 # correctly, both on the Zsh mailing list.
577 # Store the current buffer in the history.
578 zle && print -s -r -- $BUFFER
580 # Return the default exit code so Zsh aborts the current command.
584 # Load aliases and similar functions also used by other shells.
585 if [[ -f ~/.shell/aliases ]]; then
589 # Make sure aliases are expanded when using sudo.
592 # Global aliases for often used commands in the command line.
594 alias -g L='E | less'
595 alias -g D='E | colordiff L'
602 # Make going up directories simple.
604 alias -g ....='../../..'
605 alias -g .....='../../../..'
607 # If the window naming feature is used (see above) then use ".zsh" (leading
608 # dot) as title name after running clear so it's clear to me that the window
609 # is empty. I open so much windows that I don't know in which I have something
610 # important. This helps me to remember which windows are empty (I run clear
611 # after I finished my work in a window).
612 if [[ -n $window_reset ]]; then
613 alias clear='clear; window_reset=yes; window_precmd reset'
616 # Display all branches (except stash) in gitk but only 200 commits as this is
617 # much faster. Also put in the background and disown. Thanks to sitaram in
618 # #git on Freenode (2009-04-20 15:51).
622 $(git rev-parse --symbolic-full-name --remotes --branches) \
626 # Same for tig (except the disown part as it's no GUI program).
630 $(git rev-parse --symbolic-full-name --remotes --branches) \
634 # Pipe output through less.
636 command tree -C "$@" | less
639 # Automatically disown.
646 # OS SPECIFIC SETTINGS
648 if [[ $OSTYPE == linux* ]]; then
649 # Settings when creating Debian packages.
650 DEBEMAIL=simon@ruderich.org
652 DEBFULLNAME='Simon Ruderich'
657 # LOAD ADDITIONAL CONFIGURATION FILES
659 source_config ~/.zsh/rc.local
664 # If not already in screen reattach to a running session or create a new one.
665 # This also starts screen on a remote server when connecting through ssh.
666 if [[ $TERM != dumb && $TERM != linux && -z $STY ]]; then
667 # Get running detached sessions.
668 session=$(screen -list | grep 'Detached' | awk '{ print $1; exit }')
670 # As we exec later we have to set the title here.
671 window_preexec "screen"
673 # Create a new session if none is running.
674 if [[ -z $session ]]; then
676 # Reattach to a running session.
678 exec screen -r $session
682 # Colorize stderr in red. Very useful when looking for errors. Thanks to
683 # http://gentoo-wiki.com/wiki/Zsh for the basic script and Mikachu in #zsh on
684 # Freenode (2010-03-07 04:03 CET) for some improvements (-r, printf). It's not
685 # yet perfect and doesn't work with su and git for example, but it can handle
686 # most interactive output quite well (even with no trailing new line) and in
687 # cases it doesn't work, the E alias can be used as workaround.
689 # Moved in the "run commands" section to prevent one unnecessary zsh process
690 # when starting screen (see above).
691 exec 2>>(while read -r -k -u 0 line; do
692 printf '\e[91m%s\e[0m' "$line";
696 # Run reminder and redisplay it every four hours (if it's available).
699 which rem > /dev/null && [ -f ~/.reminders ] && rem -h
703 source_debug ". ~/.zsh/rc (done)"