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 # Don't add lines starting with a space to the history.
116 setopt histignorespace
117 # Vim like completions of previous executed commands (also enter Vi-mode). If
118 # called at the beginning it just recalls old commands (like cursor up), if
119 # called after typing something, only lines starting with the typed text are
120 # returned. Very useful to get old commands quickly - in addition to the
121 # history commands (!..). Thanks to Mikachu in #zsh on Freenode (2010-01-17
122 # 12:47 CET) for the information how to a use function with bindkey.
123 zle -N my-vi-history-beginning-search-backward
124 my-vi-history-beginning-search-backward() {
125 local not_at_beginning_of_line
126 if [[ $CURSOR -ne 0 ]]; then
127 not_at_beginning_of_line=yes
130 zle history-beginning-search-backward
132 # Start Vi-mode and stay at the same position (Vi-mode moves one left,
135 if [[ -n $not_at_beginning_of_line ]]; then
139 bindkey '^P' my-vi-history-beginning-search-backward
140 bindkey -a '^P' history-beginning-search-backward # binding for Vi-mode
141 # Here only Vi-mode is necessary as ^P enters Vi-mode and ^N only makes sense
143 bindkey -a '^N' history-beginning-search-forward
145 # Automatically push cd-ed directories on the directory stack.
147 # Don't push duplicates on the directory stack.
148 setopt pushdignoredups
149 # Exchange the meaning of + and - when specifying a directory on the stack.
150 # This way cd -<Tab> lists the last used directory first, which is more
151 # natural because cd - goes to the last directory.
157 # Use colorized output, necessary for prompts and completions.
158 autoload -Uz colors && colors
160 # Necessary for $EPOCHSECONDS, the UNIX time.
161 zmodload zsh/datetime
163 # Some shortcuts for colors. The %{...%} tells zsh that the data in between
164 # doesn't need any space, necessary for correct prompt drawing.
165 local red="%{${fg[red]}%}"
166 local blue="%{${fg[blue]}%}"
167 local green="%{${fg[green]}%}"
168 local yellow="%{${fg[yellow]}%}"
169 local default="%{${fg[default]}%}"
171 # vcs_info was added in 4.3.9 but it works in earlier versions too. So load it
172 # if the necessary files are available in ~/.zsh/functions/vcs_info (often a
173 # symbolic link to current checkout of Zsh's sources).
174 if [[ $ZSH_VERSION == (4.3.<9->|4.<4->*|<5->*) ||
175 -d ~/.zsh/functions/vcs_info ]]; then
176 # Update fpath to allow loading the vcs_info functions.
177 if [[ -d ~/.zsh/functions/vcs_info ]]; then
178 fpath=(~/.zsh/functions/vcs_info/
179 ~/.zsh/functions/vcs_info/Backends
183 # Load vcs_info to display information about version control repositories.
184 autoload -Uz vcs_info
185 # Only look for git and mercurial repositories; the only I use.
186 zstyle ':vcs_info:*' enable git hg
187 # Check the repository for changes so they can be used in %u/%c (see
188 # below). This comes with a speed penalty for bigger repositories.
189 zstyle ':vcs_info:*' check-for-changes yes
191 # Set style of vcs_info display. The current branch (green) and VCS (blue)
192 # is displayed. If there is an special action going on (merge, rebase)
193 # it's also displayed (red). Also display if there are unstaged or staged
195 if [[ $ZSH_VERSION == (4.3.<11->|4.<4->*|<5->*) ||
196 -d ~/.zsh/functions/vcs_info ]]; then
197 zstyle ':vcs_info:*' formats \
198 "($green%b%u%c$default:$blue%s$default)"
199 zstyle ':vcs_info:*' actionformats \
200 "($green%b%u%c$default/$red%a$default:$blue%s$default)"
202 # In older versions %u and %c are not defined yet and are not
203 # correctly expanded.
204 zstyle ':vcs_info:*' formats \
205 "($green%b$default:$blue%s$default)"
206 zstyle ':vcs_info:*' actionformats \
207 "($green%b$default/$red%a$default:$blue%s$default)"
209 # Set style for formats/actionformats when unstaged (%u) and staged (%c)
210 # changes are detected in the repository; check-for-changes must be set to
211 # true for this to work. Thanks to Bart Trojanowski
212 # (http://jukie.net/~bart/blog/pimping-out-zsh-prompt) for the idea
213 # (2010-03-11 00:20 CET).
214 zstyle ':vcs_info:*' unstagedstr '¹'
215 zstyle ':vcs_info:*' stagedstr '²'
217 # Default to run vcs_info. If possible we prevent running it later for
218 # speed reasons. If set to a non empty value vcs_info is run.
221 # Cache system inspired by Bart Trojanowski
222 # (http://jukie.net/~bart/blog/pimping-out-zsh-prompt).
223 zstyle ':vcs_info:*+pre-get-data:*' hooks pre-get-data
225 # Only Git and Mercurial support and need caching. Abort if any other
227 [[ "$vcs" != git && "$vcs" != hg ]] && return
229 # If the shell just started up or we changed directories (or for other
230 # custom reasons) we must run vcs_info.
231 if [[ -n $FORCE_RUN_VCS_INFO ]]; then
236 # Don't run vcs_info by default to speed up the shell.
238 # If a git/hg command was run then run vcs_info as the status might
239 # need to be updated.
240 case "$(fc -ln $(($HISTCMD-1)))" in
250 # Must run vcs_info when changing directories.
254 add-zsh-hook chpwd prompt_chpwd
256 # Used by prompt code below to determine if vcs_info should be run.
262 # Set the prompt. A two line prompt is used. On the top left the current
263 # working directory is displayed, on the right vcs_info (if available) and the
264 # current time in hex. On the bottom left current user name and host is shown,
265 # the exit code of the last command if it wasn't 0, the number of running jobs
268 # The prompt is in green and blue to make easily detectable, the error exit
269 # code in red and bold and the job count in yellow.
271 # Thanks to Adam's prompt for the basic idea of this prompt.
273 # Regex to remove elements which take no space. Used to calculate the
274 # width of the top prompt. Thanks to Bart's and Adam's prompt code in
275 # Functions/Prompts/prompt_*_setup.
276 local zero='%([BSUbfksu]|([FB]|){*})'
278 # Call vcs_info before every prompt.
279 if [[ -n $RUN_VCS_INFO ]]; then
285 local width width_left width_right
286 local top_left top_right
288 # Display the current time in HEX in bright blue and vcs_info (if used) on
289 # the right in the top prompt.
290 top_right="$vcs_info_msg_0_($blue%B0x$(([##16] EPOCHSECONDS))%b$default)"
291 width_right=${#${(S%%)top_right//$~zero/}}
292 # Remove it if it would get too long.
293 if [[ $(( COLUMNS - 4 - 1 - width_right )) -lt 0 ]]; then
298 # Display current directory on the left in the top prompt. Truncate the
299 # directory if necessary.
300 width=$(( COLUMNS - 4 - 1 - width_right ))
301 top_left=".-$default%b($yellow%$width<..<%~%<<$default)%B$blue"
303 # Calculate the width of the top prompt to fill the middle with "-".
304 width_left=${#${(S%%)top_left//$~zero/}}
305 width_right=${#${(S%%)top_right//$~zero/}}
306 width=$(( COLUMNS - width_left - width_right ))
308 PROMPT="$blue%B$top_left${(l:$width::-:)}%b$default$top_right
310 $green%B%n%b$default@$green%B%m%b$default %(1j.$yellow%j$default.)%# \
311 %(?..($red%B%?%b$default%) )"
313 add-zsh-hook precmd prompt_precmd
316 # When screen, xterm or rxvt is used set the name of the window to the
317 # currently running program.
319 # When a program is started preexec() sets the window's name to it; when it
320 # stops precmd() resets the window's name to 'zsh'. 'fg' is supported and sets
321 # the window's name to the resumed job.
323 # It works with screen, xterm and rxvt.
325 # If a command is run with sudo or if the shell is running as root then a ! is
326 # added at the beginning of the command to make this clear. If a command is
327 # running on a different computer with ssh a @ is added at the beginning. If
328 # screen is running on the remote machine instead of @screen @:hostname
329 # (hostname replaced by the machine's hostname) is displayed. This only works
330 # if the .zshrc on the server also uses this command.
332 # screen* is necessary as `screen` uses screen.linux for example for a linux
334 if [[ $TERM == screen* || $TERM == xterm* || $TERM == rxvt* ]]; then
335 # Is set to a non empty value to reset the window name in the next
338 # Is set to a non empty value when the shell is running as root.
339 if [[ $UID -eq 0 ]]; then
344 # Get the program name with its arguments.
345 local program_name=$1
347 # When sudo is used use real program name instead, but with an
348 # exclamation mark at the beginning (handled below).
350 if [[ $program_name == sudo* ]]; then
351 program_name=${program_name#sudo }
355 # Replace fg with the resumed job name.
356 if [[ $program_name == fg ]]; then
357 program_name=${jobtexts[%+]}
358 elif [[ $program_name == fg* ]]; then
359 program_name=${jobtexts[${program_name#fg }]}
362 # Remove all arguments from the program name.
363 program_name=${program_name%% *}
365 # Ignore often used commands which are only running for a very short
366 # time. This prevents a "blinking" name when it's changed to "cd" for
367 # example and then some milliseconds later back to "zsh".
368 [[ $program_name == (cd*|d|ls|l|la|ll|clear|c) ]] && return
370 # Change my shortcuts so the real name of the program is displayed.
371 case $program_name in
386 # Add an exclamation mark at the beginning if running with sudo or if
387 # running zsh as root.
388 if [[ -n $program_sudo || -n $window_root ]]; then
389 program_name=!$program_name
392 # Add an at mark at the beginning if running through ssh on a
393 # different computer.
394 if [[ -n $SSH_CONNECTION ]]; then
395 program_name="@$program_name"
397 # If screen is running in SSH then display "@:hostname" as title
398 # in the term/outer screen.
399 if [[ $program_name == @screen ]]; then
400 program_name="@:${HOST//.*/}"
401 # Use "@:!hostname" for root screens.
402 elif [[ $program_name == @!screen ]]; then
403 program_name="@:!${HOST//.*/}"
407 # Set the window name to the currently running program.
408 window_title "$program_name"
410 # Tell precmd() to reset the window name when the program stops.
415 # Abort if no window name reset is necessary.
416 [[ -z $window_reset ]] && return
418 # Reset the window name to 'zsh'.
420 # If the function was called with an argument then reset the window
421 # name to '.zsh' (used by clear alias).
426 # Prepend prefixes like in window_preexec().
427 if [[ -n $window_root ]]; then
430 if [[ -n $SSH_CONNECTION ]]; then
435 # Just reset the name, so no screen reset necessary for the moment.
439 # Sets the window title. Works with screen, xterm and rxvt. (V) escapes
440 # all non-printable characters. Thanks to Mikachu in #zsh on Freenode
441 # (2010-08-07 17:09 CEST).
442 if [[ $TERM == screen* ]]; then
444 print -n "\ek${(V)1}\e\\"
446 elif [[ $TERM == xterm* || $TERM == rxvt* ]]; then
448 print -n "\e]2;${(V)1}\e\\"
451 # Fallback if another TERM is used.
455 # Add the preexec() and precmd() hooks.
456 add-zsh-hook preexec window_preexec
457 add-zsh-hook precmd window_precmd
459 # Fallback if another TERM is used, necessary to run screen (see below in
465 # COMPLETION SETTINGS
467 # Load the complist module which provides additional features to completion
468 # lists (coloring, scrolling).
469 zmodload zsh/complist
470 # Use new completion system, store dumpfile in ~/.zsh/cache to prevent
471 # cluttering of ~/. $fpath must be set before calling this. Thanks to Adlai in
472 # #zsh on Freenode (2009-08-07 21:05 CEST) for reminding me of the $fpath
474 autoload -Uz compinit && compinit -d ~/.zsh/cache/zcompdump
476 # Use cache to speed up some slow completions (dpkg, perl modules, etc.).
477 zstyle ':completion:*' use-cache yes
478 zstyle ':completion:*' cache-path ~/.zsh/cache
480 # Let the completion system handle all completions, including expanding of
481 # shell wildcards (which is handled by other shell mechanisms if the default
482 # expand-or-complete is used).
483 bindkey '^I' complete-word
484 # If there are multiple matches after pressing <Tab> always display them
485 # immediately without requiring another <Tab>. a<Tab> completes to aa and
486 # lists aaa, aab, aac as possible completions if the directory contains aaa,
487 # aab, aac, bbb instead of only completing to aa.
488 setopt nolistambiguous
489 # Support completions in the middle of a word, without this option zsh jumps
490 # to the end of the word before the completion process begins. Is required for
491 # the _prefix completer.
492 setopt completeinword
494 zstyle ':completion:::::' completer \
495 _expand _complete _prefix _ignored _approximate
497 # Try uppercase if the currently typed string doesn't match. This allows
498 # typing in lowercase most of the time and completion fixes the case. Don't
499 # perform these fixes in _approximate to prevent it from changing the input
500 # too much. Thanks to the book "From Bash to Z Shell" page 249.
501 zstyle ':completion:*:(^approximate):*' matcher-list 'm:{a-z}={A-Z}'
503 # Allow one mistake per three characters. Thanks to the book "From Bash to Z
505 zstyle -e ':completion:*:approximate:*' max-errors \
506 'reply=( $(( ($#PREFIX + $#SUFFIX) / 3 )) )'
508 # Expand shell wildcards to all matching files after <Tab>. echo *<Tab>
509 # results in a b c if the directory contains the files a, b, c. Thanks to the
510 # book "From Bash to Z Shell" page 246.
511 zstyle ':completion:*:expand:*' tag-order all-expansions
512 # Keep prefixes unexpanded if possible: $HOME/<Tab> doesn't expand $HOME,
513 # while $HOME<Tab> does.
514 zstyle ':completion:*:expand:*' keep-prefix yes
516 # When completing multiple path components display all matching ambiguous
517 # components. For example /u/s/d/r/README<Tab> lists all matching READMEs
518 # instead of just the matching paths up to the r/ component. Can be slow if
519 # there are many matching files.
520 zstyle ':completion:*' list-suffixes yes
522 # Use ls-like colors for completions.
523 zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
525 # Make completion lists scrollable so "do you wish to see all n possibilities"
526 # is no longer displayed. Display current position in percent (%p).
527 zstyle ':completion:*:default' list-prompt '%p'
528 # Display group name (%d) (like 'external command', 'alias', etc.), in bold.
529 # Also display a message if _approximate found errors and if no matches were
531 zstyle ':completion:*' format ' %B%d%b:'
532 zstyle ':completion:*:corrections' format ' %B%d%b (errors: %e)'
533 zstyle ':completion:*:warnings' format ' %Bno matches for %d%b'
534 # Display different types of matches separately.
535 zstyle ':completion:*' group-name ''
537 # Separate man pages by section.
538 zstyle ':completion:*' separate-sections yes
540 # Don't draw trailing / in bold (new in zsh 4.3.11). Thanks to Mikachu in #zsh
541 # on Freenode for the fix (2010-12-17 13:46 CET).
542 zle_highlight=(suffix:none)
544 # Ignore completion functions.
545 zstyle ':completion:*:functions' ignored-patterns '_*'
546 # Ignore parent directory.
547 zstyle ':completion:*:(cd|mv|cp):*' ignore-parents parent pwd
548 # Always complete file names only once in the current line. This makes it easy
549 # to complete multiple file names because I can just press tab to get all
550 # possible values. Otherwise I would have to skip the first value again and
551 # again. Thanks to Mikachu in #zsh on Freenode (2011-08-11 14:42 CEST) for the
552 # hint to use other. other is necessary so prefix<Tab> lists both prefix and
553 # prefixrest if the directory contains prefix and prefixrest.
554 zstyle ':completion:*:all-files' ignore-line other
555 # Except for mv and cp, because I often want to use to similar names, so I
556 # complete to the same and change it.
557 zstyle ':completion:*:(mv|cp):all-files' ignore-line no
559 # Don't complete ./config.* files, this makes running ./configure much
560 # simpler. Thanks to Nomexous in #zsh on Freenode (2010-03-16 01:54 CET)
561 zstyle ':completion:*:*:-command-:*' ignored-patterns './config.*'
562 # Don't complete unwanted files with Vim. Thanks to Nomexous in #zsh on
563 # Freenode (2010-06-06 04:54 CEST). See below for a way to complete them.
564 zstyle ':completion:*:*:vim:*:all-files' ignored-patterns \
565 '*.aux' '*.log' '*.pdf' \
568 # Provide a fallback completer which always completes files. Useful when Zsh's
569 # completion is too "smart". Thanks to Frank Terbeck <ft@bewatermyfriend.org>
570 # (http://www.zsh.org/mla/users/2009/msg01038.html).
571 zle -C complete-files complete-word _generic
572 zstyle ':completion:complete-files:*' completer _files
573 bindkey '^F' complete-files
576 # CUSTOM ALIASES AND FUNCTIONS
578 # If ^C is pressed while typing a command, add it to the history so it can be
579 # easily retrieved later and then abort like ^C normally does. This is useful
580 # when I want to abort an command to do something in between and then finish
581 # typing the command.
583 # Thanks to Vadim Zeitlin <vz-zsh@zeitlins.org> for a fix (--) so lines
584 # starting with - don't cause errors; and to Nadav Har'El
585 # <nyh@math.technion.ac.il> for a fix (-r) to handle whitespace/quotes
586 # correctly, both on the Zsh mailing list.
588 # Store the current buffer in the history.
589 zle && print -s -r -- $BUFFER
591 # Return the default exit code so Zsh aborts the current command.
595 # Load aliases and similar functions also used by other shells.
596 if [[ -f ~/.shell/aliases ]]; then
600 # Make sure aliases are expanded when using sudo.
603 # Global aliases for often used commands in the command line.
605 alias -g L='E | less'
606 alias -g D='E | colordiff L'
613 # Make going up directories simple.
615 alias -g ....='../../..'
616 alias -g .....='../../../..'
618 # If the window naming feature is used (see above) then use ".zsh" (leading
619 # dot) as title name after running clear so it's clear to me that the window
620 # is empty. I open so much windows that I don't know in which I have something
621 # important. This helps me to remember which windows are empty (I run clear
622 # after I finished my work in a window).
623 if [[ -n $window_reset ]]; then
624 alias clear='clear; window_reset=yes; window_precmd reset'
630 # Display all branches (except stash) in gitk but only 200 commits as this is
631 # much faster. Also put in the background and disown. Thanks to sitaram in
632 # #git on Freenode (2009-04-20 15:51).
636 $(git rev-parse --symbolic-full-name --remotes --branches) \
640 # Same for tig (except the disown part as it's no GUI program).
644 $(git rev-parse --symbolic-full-name --remotes --branches) \
648 # Pipe output through less.
650 command tree -C "$@" | less
653 # Automatically disown.
660 # OS SPECIFIC SETTINGS
662 if [[ $OSTYPE == linux* ]]; then
663 # Settings when creating Debian packages.
664 DEBEMAIL=simon@ruderich.org
666 DEBFULLNAME='Simon Ruderich'
671 # LOAD ADDITIONAL CONFIGURATION FILES
673 source_config ~/.zsh/rc.local
678 # If not already in screen reattach to a running session or create a new one.
679 # This also starts screen on a remote server when connecting through ssh.
680 if [[ $TERM != dumb && $TERM != linux && -z $STY ]]; then
681 # Get running detached sessions.
682 session=$(screen -list | grep 'Detached' | awk '{ print $1; exit }')
684 # As we exec later we have to set the title here.
685 window_preexec "screen"
687 # Create a new session if none is running.
688 if [[ -z $session ]]; then
690 # Reattach to a running session.
692 exec screen -r $session
696 # Colorize stderr in red. Very useful when looking for errors. Thanks to
697 # http://gentoo-wiki.com/wiki/Zsh for the basic script and Mikachu in #zsh on
698 # Freenode (2010-03-07 04:03 CET) for some improvements (-r, printf). It's not
699 # yet perfect and doesn't work with su and git for example, but it can handle
700 # most interactive output quite well (even with no trailing new line) and in
701 # cases it doesn't work, the E alias can be used as workaround.
703 # Moved in the "run commands" section to prevent one unnecessary zsh process
704 # when starting screen (see above).
705 exec 2>>(while read -r -k -u 0 line; do
706 printf '\e[91m%s\e[0m' "$line";
710 # Run reminder and redisplay it every four hours (if it's available).
713 which rem > /dev/null && [ -f ~/.reminders ] && rem -h
717 source_debug ". ~/.zsh/rc (done)"