1 # Zsh configuration file.
3 # Copyright (C) 2011-2012 Simon Ruderich
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.
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.
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/>.
19 source_debug '. ~/.zsh/rc'
22 # Warn when creating global variables from inside a function. Needs to be set
23 # before declaring a function.
24 setopt warn_create_global
29 # Return the name of the program which is called in the foreground with `fg`.
30 # $1 is the name of the program (optional). If it's not 'fg' or 'fg *' it's
32 zshrc_resolve_fg_to_resumed_job_name() {
33 # $REPLY is used by convention for scalars ($reply for arrays) to return
34 # values from functions. unset it here to prevent problems when REPLY is
35 # bound to an integer or similar. Thanks to Mikachu in #zsh on Freenode
36 # (2012-09-27 17:14 CEST) for this hint.
39 # Replace fg with the resumed job name.
40 if [[ $1 == fg ]]; then
41 REPLY="${jobtexts[%+]}"
42 elif [[ $1 == fg\ * ]]; then
43 REPLY="${jobtexts[${1#fg }]}"
44 # Normal program, return as is.
51 # MISCELLANEOUS SETTINGS
53 # Be paranoid, new files are readable/writable by me only, but not as root.
54 if [[ $UID -ne 0 ]]; then
61 # Prevent overwriting existing files with '> filename', use '>| filename'
65 # Entering the name of a directory (if it's not a command) will automatically
66 # cd to that directory.
69 # When entering a nonexistent command name automatically try to find a similar
73 # Enable zsh's extended glob abilities.
76 # Don't exit if <C-D> is pressed. Prevents exiting the shell by accident (e.g.
77 # pressing <C-D> twice).
83 # Not all bindings are done here, only those not specific to a given section.
85 # Use Vi(m) style key bindings.
88 # Use jj and jk to exit insert mode.
89 bindkey 'jj' vi-cmd-mode
90 bindkey 'jk' vi-cmd-mode
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'
100 # Make sure every entry in $fpath is unique.
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)
107 # Set correct fpath to allow loading my functions (including completion
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)
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
122 for function in $precmd_functions; do
127 for function in $preexec_functions; do
132 for function in $chpwd_functions; do
138 # Load zmv (zsh move) which is a powerful file renamer.
144 # Use history and store it in ~/.zsh/history.
147 HISTFILE=~/.zsh/history
148 # Append to the history file instead of overwriting it and do it immediately
149 # when a command is executed.
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 # Vim like completions of previous executed commands (also enter Vi-mode). If
157 # called at the beginning it just recalls old commands (like cursor up), if
158 # called after typing something, only lines starting with the typed text are
159 # returned. Very useful to get old commands quickly - in addition to the
160 # history commands (!..). Thanks to Mikachu in #zsh on Freenode (2010-01-17
161 # 12:47 CET) for the information how to a use function with bindkey.
162 zle -N zshrc-vi-history-beginning-search-backward
163 zshrc-vi-history-beginning-search-backward() {
164 local not_at_beginning_of_line
165 if [[ $CURSOR -ne 0 ]]; then
166 not_at_beginning_of_line=yes
169 zle history-beginning-search-backward
171 # Start Vi-mode and stay at the same position (Vi-mode moves one left,
174 if [[ -n $not_at_beginning_of_line ]]; then
178 bindkey '^P' zshrc-vi-history-beginning-search-backward
179 bindkey -a '^P' history-beginning-search-backward # binding for Vi-mode
180 # Here only Vi-mode is necessary as ^P enters Vi-mode and ^N only makes sense
182 bindkey -a '^N' history-beginning-search-forward
184 # Automatically push cd-ed directories on the directory stack.
186 # Don't push duplicates on the directory stack.
187 setopt pushdignoredups
188 # Exchange the meaning of + and - when specifying a directory on the stack.
189 # This way cd -<Tab> lists the last used directory first, which is more
190 # natural because cd - goes to the last directory.
196 # Use colorized output, necessary for prompts and completions.
197 autoload -Uz colors && colors
199 # Necessary for $EPOCHSECONDS, the UNIX time.
200 zmodload zsh/datetime
202 # Some shortcuts for colors. The %{...%} tells zsh that the data in between
203 # doesn't need any space, necessary for correct prompt drawing.
204 local red="%{${fg[red]}%}"
205 local blue="%{${fg[blue]}%}"
206 local green="%{${fg[green]}%}"
207 local yellow="%{${fg[yellow]}%}"
208 local default="%{${fg[default]}%}"
210 # vcs_info was added in 4.3.9 but it works in earlier versions too. So load it
211 # if the necessary files are available in ~/.zsh/functions/vcs_info (often a
212 # symbolic link to current checkout of Zsh's sources).
213 if [[ $ZSH_VERSION == (4.3.<9->*|4.<4->*|<5->*) ||
214 -d ~/.zsh/functions/vcs_info ]]; then
215 # Update fpath to allow loading the vcs_info functions.
216 if [[ -d ~/.zsh/functions/vcs_info ]]; then
217 fpath=(~/.zsh/functions/vcs_info/
218 ~/.zsh/functions/vcs_info/Backends
222 # Load vcs_info to display information about version control repositories.
223 autoload -Uz vcs_info
224 # Only look for git and mercurial repositories; the only I use.
225 zstyle ':vcs_info:*' enable git hg
226 # Check the repository for changes so they can be used in %u/%c (see
227 # below). This comes with a speed penalty for bigger repositories.
228 zstyle ':vcs_info:*' check-for-changes yes
230 # Set style of vcs_info display. The current branch (green) and VCS (blue)
231 # is displayed. If there is an special action going on (merge, rebase)
232 # it's also displayed (red). Also display if there are unstaged or staged
234 if [[ $ZSH_VERSION == (4.3.<11->*|4.<4->*|<5->*) ||
235 -d ~/.zsh/functions/vcs_info ]]; then
236 zstyle ':vcs_info:*' formats \
237 "(${green}%b%u%c${default}:${blue}%s${default})" \
238 "${green}%u%c${default}"
239 zstyle ':vcs_info:*' actionformats \
240 "(${green}%b%u%c${default}/${red}%a${default}:${blue}%s${default})" \
241 "${green}%u%c${default}"
243 # In older versions %u and %c are not defined yet and are not
244 # correctly expanded.
245 zstyle ':vcs_info:*' formats \
246 "(${green}%b${default}:${blue}%s${default})"
247 zstyle ':vcs_info:*' actionformats \
248 "(${green}%b${default}/${red}%a${default}:${blue}%s${default})"
250 # Set style for formats/actionformats when unstaged (%u) and staged (%c)
251 # changes are detected in the repository; check-for-changes must be set to
252 # true for this to work. Thanks to Bart Trojanowski
253 # (http://jukie.net/~bart/blog/pimping-out-zsh-prompt) for the idea
254 # (2010-03-11 00:20 CET).
255 zstyle ':vcs_info:*' unstagedstr '¹'
256 zstyle ':vcs_info:*' stagedstr '²'
258 # Default to run vcs_info. If possible we prevent running it later for
259 # speed reasons. If set to a non empty value vcs_info is run.
260 zshrc_force_run_vcs_info=1
262 # Cache system inspired by Bart Trojanowski
263 # (http://jukie.net/~bart/blog/pimping-out-zsh-prompt).
264 zstyle ':vcs_info:*+pre-get-data:*' hooks pre-get-data
266 # Only Git and Mercurial support and need caching. Abort if any other
268 [[ "$vcs" != git && "$vcs" != hg ]] && return
270 # If the shell just started up or we changed directories (or for other
271 # custom reasons) we must run vcs_info.
272 if [[ -n $zshrc_force_run_vcs_info ]]; then
273 zshrc_force_run_vcs_info=
277 # Don't run vcs_info by default to speed up the shell.
279 # If a git/hg command was run then run vcs_info as the status might
280 # need to be updated.
281 case "$(fc -ln $(($HISTCMD-1)))" in
291 # Must run vcs_info when changing directories.
293 zshrc_force_run_vcs_info=1
295 chpwd_functions+=(prompt_chpwd)
297 # Used by prompt code below to determine if vcs_info should be run.
303 typeset -a zshrc_longrun_data
304 zshrc_longrun_data=()
305 # Display runtime in seconds for long running programs (> 60 seconds) and send
306 # a bell to notify me.
307 zshrc_longrun_preexec() {
312 zshrc_resolve_fg_to_resumed_job_name "$program"
315 # Don't track the time for certain (possible) long running processes which
316 # need no automatic notification.
317 for ignore in elinks man mutt vim; do
319 $ignore | $ignore\ *)
320 zshrc_longrun_data=()
326 zshrc_longrun_data=("$program" $EPOCHSECONDS)
328 zshrc_longrun_precmd() {
329 # No previous timestamp available or disabled for this command, ignore.
330 if [[ -z $zshrc_longrun_data ]]; then
334 local difference=$(( EPOCHSECONDS - zshrc_longrun_data[2] ))
335 if [[ $difference -gt 60 ]]; then
337 echo -n "${fg[yellow]}"
338 echo -n "~> ${(V)zshrc_longrun_data[1]} took $difference seconds."
339 echo -n "${fg[default]}"
340 echo "\a" # send bell
343 # Clear status. Prevents displaying old status information when pressing
344 # enter with an empty command line.
345 zshrc_longrun_data=()
347 preexec_functions+=(zshrc_longrun_preexec)
348 precmd_functions+=(zshrc_longrun_precmd)
350 # Set the prompt. A two line prompt is used. On the top left the current
351 # working directory is displayed, on the right vcs_info (if available) and the
352 # current time in hex. On the bottom left current user name and host is shown,
353 # the exit code of the last command if it wasn't 0, the number of running jobs
356 # The prompt is in green and blue to make easily detectable, the error exit
357 # code in red and bold and the job count in yellow. Designed for dark
360 # Thanks to Adam's prompt for the basic idea of this prompt.
361 zshrc_prompt_precmd() {
362 # Regex to remove elements which take no space. Used to calculate the
363 # width of the top prompt. Thanks to Bart's and Adam's prompt code in
364 # Functions/Prompts/prompt_*_setup.
365 local zero='%([BSUbfksu]|([FB]|){*})'
367 # Call vcs_info before every prompt.
368 if [[ -n $zshrc_use_vcs_info ]]; then
375 # Setup. Create variables holding the formatted content.
377 # Current directory in yellow, truncated if necessary (WIDTH is replaced
379 local directory="${yellow}%WIDTH<..<%~%<<${default}"
380 # Minimal information about the VCS, only displayed if there are
381 # unstaged/staged changes.
382 local vcs_staged="${vcs_info_msg_1_}"
384 # Information about the VCS in this directory.
385 local vcs="${vcs_info_msg_0_}"
386 # Current time (seconds since epoch) in Hex in bright blue.
387 local seconds="${blue}%B0x$(([##16] EPOCHSECONDS))%b${default}"
389 # User name (%n) in bright green.
390 local user="${green}%B%n%b${default}"
391 # Host name (%m) in bright green; underlined if running on a remote system
393 local host="${green}%B%m%b${default}"
394 if [[ -n $SSH_CONNECTION ]]; then
398 # Number of background processes in yellow if not zero.
399 local background="%(1j.${yellow}%j${default}.)"
400 # Exit code in bright red in parentheses if not zero.
401 local exitcode="%(?..(${red}%B%?%b${default}%) )"
403 # Prefix characters in first and second line.
404 local top_prefix="${blue}%B.-%b${default}"
405 local bottom_prefix="${blue}%B'%b${default}"
407 # Combine them to create the prompt.
409 local top_left="${vcs_staged}"
410 local top_right="${vcs}(${seconds})"
412 local width_top_prefix=${#${(S%%)top_prefix//$~zero/}}
413 local width_top_left=${#${(S%%)top_left//$~zero/}}
414 local width_top_right=${#${(S%%)top_right//$~zero/}}
416 # Calculate the maximum width of ${top_left}. -2 are the braces of
417 # ${top_left}, -1 is one separator from ${top_separator} (we want at least
418 # one between left and right parts).
419 local top_left_width_max=$((
420 COLUMNS - $width_top_prefix
421 - $width_top_left - 2
425 # Truncate directory if necessary.
426 top_left="(${directory/WIDTH/${top_left_width_max}})${top_left}"
427 width_top_left=${#${(S%%)top_left//$~zero/}}
429 # Calculate the width of the top prompt to fill the middle with "-".
431 COLUMNS - width_top_prefix - width_top_left - width_top_right
433 local top_separator="%B${blue}${(l:${width}::-:)}%b${default}"
435 PROMPT="${top_prefix}${top_left}${top_separator}${top_right}
436 ${bottom_prefix}${user}@${host} ${background}%# ${exitcode}"
438 precmd_functions+=(zshrc_prompt_precmd)
441 # When GNU screen, tmux, xterm or rxvt is used set the name of the window to
442 # the currently running program.
444 # When a program is started preexec() sets the window's name to it; when it
445 # stops precmd() resets the window's name to 'zsh'. 'fg' is supported and sets
446 # the window's name to the resumed job.
448 # It works with GNU screen, tmux, xterm and rxvt.
450 # If a command is run with sudo or if the shell is running as root then a ! is
451 # added at the beginning of the command to make this clear. If a command is
452 # running on a different computer with ssh a @ is added at the beginning. If
453 # screen/tmux is running on the remote machine instead of @screen @:hostname
454 # (or @tmux ..; hostname replaced by the machine's hostname) is displayed.
455 # This only works if the .zshrc on the server also uses this command.
457 # screen* is necessary as `screen` uses screen.linux for example for a linux
459 if [[ $TERM == screen* || $TERM == xterm* || $TERM == rxvt* ]]; then
460 # Is set to a non empty value to reset the window name in the next
462 zshrc_window_reset=yes
464 zshrc_window_preexec() {
465 # Get the program name with its arguments.
466 local program_name=$1
468 # When sudo is used, use real program name instead, but with an
469 # exclamation mark at the beginning (handled below).
471 if [[ $program_name == sudo* ]]; then
472 program_name=${program_name#sudo }
478 zshrc_resolve_fg_to_resumed_job_name "$program_name"
479 program_name="$REPLY"
481 # Remove all arguments from the program name.
482 program_name=${program_name%% *}
484 # Ignore often used commands which are only running for a very short
485 # time. This prevents a "blinking" name when it's changed to "cd" for
486 # example and then some milliseconds later back to "zsh".
487 [[ $program_name == (cd*|d|ls|l|la|ll|clear|c) ]] && return
489 # Change my shortcuts so the real name of the program is displayed.
490 case $program_name in
505 # Add an exclamation mark at the beginning if running with sudo or if
506 # running zsh as root.
507 if [[ -n $program_sudo || $UID -eq 0 ]]; then
508 program_name=!$program_name
511 # Add an at mark at the beginning if running through ssh on a
512 # different computer.
513 if [[ -n $SSH_CONNECTION ]]; then
514 program_name="@$program_name"
516 # If screen is running in SSH then display "@:hostname" as title
517 # in the term/outer screen.
518 if [[ $program_name == @screen || $program_name == @tmux ]]; then
519 program_name="@:${HOST//.*/}"
520 # Use "@:!hostname" for root screens.
521 elif [[ $program_name == @!screen || $program_name == @!tmux ]]; then
522 program_name="@:!${HOST//.*/}"
526 # Set the window name to the currently running program.
527 zshrc_window_title "$program_name"
529 # Tell precmd() to reset the window name when the program stops.
530 zshrc_window_reset=yes
533 zshrc_window_precmd() {
534 # Abort if no window name reset is necessary.
535 [[ -z $zshrc_window_reset ]] && return
537 # Reset the window name to 'zsh'.
539 # If the function was called with an argument then reset the window
540 # name to '.zsh' (used by clear alias).
545 # Prepend prefixes like in window_preexec().
546 if [[ $UID -eq 0 ]]; then
549 if [[ -n $SSH_CONNECTION ]]; then
552 zshrc_window_title $name
554 # Just reset the name, so no screen reset necessary for the moment.
558 # Sets the window title. Works with GNU screen, tmux (which uses screen as
559 # TERM), xterm and rxvt. (V) escapes all non-printable characters, thanks
560 # to Mikachu in #zsh on Freenode (2010-08-07 17:09 CEST).
561 if [[ $TERM == screen* ]]; then
562 zshrc_window_title() {
563 print -n "\ek${(V)1}\e\\"
565 elif [[ $TERM == xterm* || $TERM == rxvt* ]]; then
566 zshrc_window_title() {
567 print -n "\e]2;${(V)1}\e\\"
570 # Fallback if another TERM is used.
571 zshrc_window_title() { }
574 # Add the preexec() and precmd() hooks.
575 preexec_functions+=(zshrc_window_preexec)
576 precmd_functions+=(zshrc_window_precmd)
578 # Fallback if another TERM is used, necessary to run screen (see below in
580 zshrc_window_preexec() { }
584 # COMPLETION SETTINGS
586 # Load the complist module which provides additional features to completion
587 # lists (coloring, scrolling).
588 zmodload zsh/complist
589 # Use new completion system, store dumpfile in ~/.zsh/cache to prevent
590 # cluttering of ~/. $fpath must be set before calling this. Thanks to Adlai in
591 # #zsh on Freenode (2009-08-07 21:05 CEST) for reminding me of the $fpath
593 autoload -Uz compinit && compinit -d ~/.zsh/cache/zcompdump
595 # Use cache to speed up some slow completions (dpkg, perl modules, etc.).
596 zstyle ':completion:*' use-cache yes
597 zstyle ':completion:*' cache-path ~/.zsh/cache
599 # Let the completion system handle all completions, including expanding of
600 # shell wildcards (which is handled by other shell mechanisms if the default
601 # expand-or-complete is used).
602 bindkey '^I' complete-word
603 # If there are multiple matches after pressing <Tab> always display them
604 # immediately without requiring another <Tab>. a<Tab> completes to aa and
605 # lists aaa, aab, aac as possible completions if the directory contains aaa,
606 # aab, aac, bbb instead of only completing to aa.
607 setopt nolistambiguous
608 # Support completions in the middle of a word, without this option zsh jumps
609 # to the end of the word before the completion process begins. Is required for
610 # the _prefix completer.
611 setopt completeinword
613 zstyle ':completion:::::' completer \
614 _expand _complete _prefix _ignored _approximate
616 # Match specification to be tried when completing items. Each group ('...') is
617 # tried after another if no matches were found, once matches are found no
618 # other groups are tried. Thanks to Mikachu in #zsh on Freenode (2012-08-28
619 # 18:48 CEST) for explanations.
621 # When matching also include the uppercase variant of typed characters
622 # ('m:{a-z}={A-Z}'); using '' before this group would try the unmodified match
623 # first, but I prefer to get all matches immediately (e.g. if Makefile and
624 # makefile exist in the current directory echo m<tab> matches both, with '' it
625 # would only match makefile because it found one match). This allows typing in
626 # lowercase most of the time and completion fixes the case, which is faster.
628 # Don't perform these fixes in _approximate to prevent it from changing the
629 # input too much. Thanks to the book "From Bash to Z Shell" page 249.
630 zstyle ':completion:*:(^approximate):*' matcher-list 'm:{a-z}={A-Z}'
632 # Allow one mistake per three characters. Thanks to the book "From Bash to Z
634 zstyle -e ':completion:*:approximate:*' max-errors \
635 'reply=( $(( ($#PREFIX + $#SUFFIX) / 3 )) )'
637 # Expand shell wildcards to all matching files after <Tab>. echo *<Tab>
638 # results in a b c if the directory contains the files a, b, c. Thanks to the
639 # book "From Bash to Z Shell" page 246.
640 zstyle ':completion:*:expand:*' tag-order all-expansions
641 # Keep prefixes unexpanded if possible: $HOME/<Tab> doesn't expand $HOME,
642 # while $HOME<Tab> does.
643 zstyle ':completion:*:expand:*' keep-prefix yes
645 # When completing multiple path components display all matching ambiguous
646 # components. For example /u/s/d/r/README<Tab> lists all matching READMEs
647 # instead of just the matching paths up to the r/ component. Can be slow if
648 # there are many matching files.
649 zstyle ':completion:*' list-suffixes yes
651 # Use ls-like colors for completions.
652 zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
654 # Make completion lists scrollable so "do you wish to see all n possibilities"
655 # is no longer displayed. Display current position in percent (%p).
656 zstyle ':completion:*:default' list-prompt '%p'
657 # Display group name (%d) (like 'external command', 'alias', etc.), in bold.
658 # Also display a message if _approximate found errors and no matches were
660 zstyle ':completion:*' format ' %B%d%b:'
661 zstyle ':completion:*:corrections' format ' %B%d%b (errors: %e)'
662 zstyle ':completion:*:warnings' format ' %Bno matches for %d%b'
663 # Display different types of matches separately.
664 zstyle ':completion:*' group-name ''
666 # Separate man pages by section.
667 zstyle ':completion:*' separate-sections yes
669 # Don't draw trailing / in bold (new in zsh 4.3.11). Thanks to Mikachu in #zsh
670 # on Freenode for the fix (2010-12-17 13:46 CET).
671 zle_highlight=(suffix:none)
673 # Ignore completion functions.
674 zstyle ':completion:*:functions' ignored-patterns '_*'
675 # Ignore parent directory.
676 zstyle ':completion:*:(cd|mv|cp):*' ignore-parents parent pwd
677 # Always complete file names only once in the current line. This makes it easy
678 # to complete multiple file names because I can just press tab to get all
679 # possible values. Otherwise I would have to skip the first value again and
680 # again. Thanks to Mikachu in #zsh on Freenode (2011-08-11 14:42 CEST) for the
681 # hint to use other. other is necessary so prefix<Tab> lists both prefix and
682 # prefixrest if the directory contains prefix and prefixrest.
683 zstyle ':completion:*:all-files' ignore-line other
684 # Except for mv and cp, because I often want to use to similar names, so I
685 # complete to the same and change it.
686 zstyle ':completion:*:(mv|cp):all-files' ignore-line no
688 # Don't complete ./config.* files, this makes running ./configure much
689 # simpler. Thanks to Nomexous in #zsh on Freenode (2010-03-16 01:54 CET)
690 zstyle ':completion:*:*:-command-:*' ignored-patterns './config.*'
691 # Don't complete unwanted files with Vim. Thanks to Nomexous in #zsh on
692 # Freenode (2010-06-06 04:54 CEST). See below for a way to complete them.
693 zstyle ':completion:*:*:vim:*:all-files' ignored-patterns \
694 '*.aux' '*.log' '*.pdf' \
697 # Provide a fallback completer which always completes files. Useful when Zsh's
698 # completion is too "smart". Thanks to Frank Terbeck <ft@bewatermyfriend.org>
699 # (http://www.zsh.org/mla/users/2009/msg01038.html).
700 zle -C complete-files complete-word _generic
701 zstyle ':completion:complete-files:*' completer _files
702 bindkey '^F' complete-files
705 # CUSTOM ALIASES AND FUNCTIONS
707 # If ^C is pressed while typing a command, add it to the history so it can be
708 # easily retrieved later and then abort like ^C normally does. This is useful
709 # when I want to abort an command to do something in between and then finish
710 # typing the command.
712 # Thanks to Vadim Zeitlin <vz-zsh@zeitlins.org> for a fix (--) so lines
713 # starting with - don't cause errors; and to Nadav Har'El
714 # <nyh@math.technion.ac.il> for a fix (-r) to handle whitespace/quotes
715 # correctly, both on the Zsh mailing list.
717 # Don't store this line in history if histignorespace is enabled and the
718 # line starts with a space.
719 if [[ -o histignorespace && ${BUFFER[1]} = " " ]]; then
723 # Store the current buffer in the history.
724 zle && print -s -r -- $BUFFER
726 # Return the default exit code so Zsh aborts the current command.
730 # Load aliases and similar functions also used by other shells.
731 if [[ -f ~/.shell/aliases ]]; then
735 # Make sure aliases are expanded when using sudo.
738 # Global aliases for often used redirections.
740 alias -g N='>/dev/null'
741 alias -g EN='2>/dev/null'
742 alias -g L='2>&1 | less'
743 alias -g LS='2>&1 | less -S' # -S prevents wrapping of long lines
744 alias -g D='2>&1 | colordiff | less'
745 # Global aliases for often used commands.
754 # Make going up directories simple.
756 alias -g ....='../../..'
757 alias -g .....='../../../..'
759 # If the window naming feature is used (see above) then use ".zsh" (leading
760 # dot) as title name after running clear so it's clear to me that the window
761 # is empty. I open so much windows that I don't know in which I have something
762 # important. This helps me to remember which windows are empty (I run clear
763 # after I finished my work in a window).
764 if [[ -n $zshrc_window_reset ]]; then
765 alias clear='clear; zshrc_window_reset=yes; zshrc_window_precmd reset'
771 # Display all branches (except stash) in gitk but only 200 commits as this is
772 # much faster. Also put in the background and disown. Thanks to drizzd in #git
773 # on Freenode (2010-04-03 17:55 CEST).
774 (( $+commands[gitk] )) && gitk() {
775 command gitk --max-count=200 --branches --remotes --tags "$@" &
778 # Same for tig (except the disown part as it's no GUI program).
779 (( $+commands[tig] )) && tig() {
780 command tig --max-count=200 --branches --remotes --tags "$@"
783 # Pipe output through less.
784 (( $+commands[tree] )) && tree() {
785 command tree -C "$@" | less
788 # Choose the "best" PDF viewer available: xpdf, then zathura (in the past
789 # zathura was preferred, but recent versions are completely broken: still no
790 # working search and no page-wise scrolling anymore). Also setup completion
792 if (( $+commands[xpdf] )); then
794 command xpdf "$@" 2>/dev/null &
798 elif (( $+commands[zathura] )); then
800 command zathura "$@" 2>/dev/null &
803 # No completion for zathura yet.
807 # GHCI doesn't use readline, force it if rlwrap is available.
808 (( $+commands[rlwrap] )) && ghci() {
810 --always-readline --complete-filenames -t dumb \
812 --file ~/.shell/rlwrap/ghci \
817 # OS SPECIFIC SETTINGS
819 if [[ $OSTYPE == linux* ]]; then
820 # Settings when creating Debian packages.
821 export DEBEMAIL=simon@ruderich.org
822 export DEBFULLNAME='Simon Ruderich'
826 # LOAD ADDITIONAL CONFIGURATION FILES
828 # Configuration option for rc.local to use GNU screen/tmux. By default GNU
829 # screen is used. Possible values: screen, tmux and empty (no value).
830 zshrc_use_multiplexer=screen
832 source_config ~/.zsh/rc.local
837 # If not already in screen or tmux, reattach to a running session or create a
838 # new one. This also starts screen/tmux on a remote server when connecting
840 if [[ $TERM != dumb && $TERM != linux && -z $STY && -z $TMUX ]]; then
841 # Get running detached sessions.
842 if [[ $zshrc_use_multiplexer = screen ]]; then
843 session=$(screen -list | grep 'Detached' | awk '{ print $1; exit }')
844 elif [[ $zshrc_use_multiplexer = tmux ]]; then
845 session=$(tmux list-sessions 2>/dev/null \
846 | sed '/(attached)$/ d; s/^\([0-9]\{1,\}\).*$/\1/; q')
849 # As we exec later we have to set the title here.
850 if [[ $zshrc_use_multiplexer = screen ]]; then
851 zshrc_window_preexec screen
852 elif [[ $zshrc_use_multiplexer = tmux ]]; then
853 zshrc_window_preexec tmux
856 # Create a new session if none is running.
857 if [[ -z $session ]]; then
858 if [[ $zshrc_use_multiplexer = screen ]]; then
860 elif [[ $zshrc_use_multiplexer = tmux ]]; then
863 # Reattach to a running session.
865 if [[ $zshrc_use_multiplexer = screen ]]; then
866 exec screen -r $session
867 elif [[ $zshrc_use_multiplexer = tmux ]]; then
868 exec tmux attach-session -t $session
873 # Colorize stderr in red. Very useful when looking for errors. Thanks to
874 # http://gentoo-wiki.com/wiki/Zsh for the basic script and Mikachu in #zsh on
875 # Freenode (2010-03-07 04:03 CET) for some improvements (-r, printf). It's not
876 # yet perfect and doesn't work with su and git for example, but it can handle
877 # most interactive output quite well (even with no trailing new line) and in
878 # cases it doesn't work, the E alias can be used as workaround.
880 # Moved in the "run commands" section to prevent one unnecessary zsh process
881 # when starting GNU screen/tmux (see above).
882 exec 2>>(while read -r -k -u 0 line; do
883 printf '\e[91m%s\e[0m' "$line"
887 # Run the following programs every 4 hours (and when zsh starts).
891 (( $+commands[fortune] )) && fortune -ac
893 (( $+commands[rem] )) && [[ -f ~/.reminders ]] && rem -h
897 source_debug '. ~/.zsh/rc (done)'