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 true
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 on
467 zstyle ':completion:*' cache-path ~/.zsh/cache
469 # Complete arguments and fix spelling mistakes when possible.
470 zstyle ':completion:*' completer _complete _match _correct _approximate
472 # If there are multiple matches after pressing <Tab> always display them
473 # immediately without requiring another <Tab>. a<Tab> lists aaa, aab, aac as
474 # possible completions if the directory contains aaa, aab, aac, bbb.
475 setopt nolistambiguous
476 # Allow completions in the middle of a text, i.e. "/usr/bin/<TAB>whatever"
477 # completes like "/usr/bin/<TAB>". Useful when adding new options to commands.
478 bindkey '^I' expand-or-complete-prefix
479 # Try uppercase if the currently typed string doesn't match. This allows
480 # typing in lowercase most of the time and completion fixes the case.
481 zstyle ':completion:*' matcher-list '' 'm:{a-z}={A-Z}'
483 # Use ls-like colors for completions.
484 zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
486 # Make completion lists scrollable so "do you wish to see all n possibilities"
487 # is no longer displayed. Display current position in percent (%p).
488 zstyle ':completion:*' list-prompt '%p'
489 # Display group name (%d) (like 'external command', 'alias', etc.), in bold.
490 zstyle ':completion:*' format ' %B%d%b:'
491 # Display different types of matches separately.
492 zstyle ':completion:*' group-name ''
494 # Don't draw trailing / in bold (new in zsh 4.3.11). Thanks to Mikachu in #zsh
495 # on Freenode for the fix (2010-12-17 13:46 CET).
496 zle_highlight=(suffix:none)
498 # Ignore completion functions.
499 zstyle ':completion:*:functions' ignored-patterns '_*'
500 # Ignore parent directory.
501 zstyle ':completion:*:(cd|mv|cp):*' ignore-parents parent pwd
502 # Always complete one value (file name) only once in the current line. This
503 # makes it easy to complete multiple values because I can just press tab to
504 # get all possible values. Otherwise I would have to skip the first value
506 zstyle ':completion:*' ignore-line yes
507 # Except for mv and cp, because I often want to use to similar names, so I
508 # complete to the same and change it.
509 zstyle ':completion:*:(mv|cp):*' ignore-line no
510 # Don't complete ./config.* files, this makes running ./configure much
511 # simpler. Thanks to Nomexous in #zsh on Freenode (2010-03-16 01:54 CET)
512 zstyle ':completion:*:*:-command-:*' ignored-patterns './config.*'
514 # Don't complete unwanted files with Vim. Thanks to Nomexous in #zsh on
515 # Freenode (2010-06-06 04:54 CEST). See below for a way to complete them.
516 zstyle ':completion:*:*:vim:*:all-files' ignored-patterns \
517 '*.aux' '*.log' '*.pdf' \
520 # Provide a fallback completer which always completes files. Useful when Zsh's
521 # completion is too "smart". Thanks to Frank Terbeck <ft@bewatermyfriend.org>
522 # (http://www.zsh.org/mla/users/2009/msg01038.html).
523 zle -C complete-files complete-word _generic
524 zstyle ':completion:complete-files:*' completer _files
525 bindkey '^F' complete-files
528 # CUSTOM ALIASES AND FUNCTIONS
530 # If ^C is pressed while typing a command, add it to the history so it can be
531 # easily retrieved later and then abort like ^C normally does. This is useful
532 # when I want to abort an command to do something in between and then finish
533 # typing the command.
535 # Thanks to Vadim Zeitlin <vz-zsh@zeitlins.org> for a fix (--) so lines
536 # starting with - don't cause errors; and to Nadav Har'El
537 # <nyh@math.technion.ac.il> for a fix (-r) to handle whitespace/quotes
538 # correctly, both on the Zsh mailing list.
540 # Store the current buffer in the history.
541 zle && print -s -r -- $BUFFER
543 # Return the default exit code so Zsh aborts the current command.
547 # Load aliases and similar functions also used by other shells.
548 if [[ -f ~/.shell/aliases ]]; then
552 # Make sure aliases are expanded when using sudo.
555 # Global aliases for often used commands in the command line.
557 alias -g L='E | less'
558 alias -g D='E | colordiff L'
565 # Make going up directories simple.
567 alias -g ....='../../..'
568 alias -g .....='../../../..'
570 # If the window naming feature is used (see above) then use ".zsh" (leading
571 # dot) as title name after running clear so it's clear to me that the window
572 # is empty. I open so much windows that I don't know in which I have something
573 # important. This helps me to remember which windows are empty (I run clear
574 # after I finished my work in a window).
575 if [[ -n $window_reset ]]; then
576 alias clear='clear; window_reset=yes; window_precmd reset'
579 # Display all branches (except stash) in gitk but only 200 commits as this is
580 # much faster. Also put in the background and disown. Thanks to sitaram in
581 # #git on Freenode (2009-04-20 15:51).
585 $(git rev-parse --symbolic-full-name --remotes --branches) \
589 # Same for tig (except the disown part as it's no GUI program).
593 $(git rev-parse --symbolic-full-name --remotes --branches) \
597 # Pipe output through less.
599 command tree -C "$@" | less
602 # Automatically disown.
609 # OS SPECIFIC SETTINGS
611 if [[ $OSTYPE == linux* ]]; then
612 # Settings when creating Debian packages.
613 DEBEMAIL=simon@ruderich.org
615 DEBFULLNAME='Simon Ruderich'
620 # LOAD ADDITIONAL CONFIGURATION FILES
622 source_config ~/.zsh/rc.local
627 # If not already in screen reattach to a running session or create a new one.
628 # This also starts screen on a remote server when connecting through ssh.
629 if [[ $TERM != dumb && $TERM != linux && -z $STY ]]; then
630 # Get running detached sessions.
631 session=$(screen -list | grep 'Detached' | awk '{ print $1; exit }')
633 # As we exec later we have to set the title here.
634 window_preexec "screen"
636 # Create a new session if none is running.
637 if [[ -z $session ]]; then
639 # Reattach to a running session.
641 exec screen -r $session
645 # Colorize stderr in red. Very useful when looking for errors. Thanks to
646 # http://gentoo-wiki.com/wiki/Zsh for the basic script and Mikachu in #zsh on
647 # Freenode (2010-03-07 04:03 CET) for some improvements (-r, printf). It's not
648 # yet perfect and doesn't work with su and git for example, but it can handle
649 # most interactive output quite well (even with no trailing new line) and in
650 # cases it doesn't work, the E alias can be used as workaround.
652 # Moved in the "run commands" section to prevent one unnecessary zsh process
653 # when starting screen (see above).
654 exec 2>>(while read -r -k -u 0 line; do
655 printf '\e[91m%s\e[0m' "$line";
659 # Run reminder and redisplay it every four hours (if it's available).
662 which rem > /dev/null && [ -f ~/.reminders ] && rem -h
666 source_debug ". ~/.zsh/rc (done)"