+# List all files in the current directory when pressing tab on an empty input,
+# behave like complete-word otherwise. Thanks to John Eikenberry [1] for the
+# code, read on 2014-03-15.
+#
+# [1]: http://unix.stackexchange.com/a/32426
+complete-word-or-complete-list-of-files() {
+ if [[ $#BUFFER == 0 ]]; then
+ BUFFER='ls '
+ CURSOR=3
+ zle list-choices
+ zle backward-kill-word
+ else
+ zle complete-word
+ fi
+}
+zle -N complete-word-or-complete-list-of-files
+# Let the completion system handle all completions, including expanding of
+# shell wildcards (which is handled by other shell mechanisms if the default
+# expand-or-complete is used).
+bindkey '^I' complete-word-or-complete-list-of-files
+# If there are multiple matches after pressing <Tab> always display them
+# immediately without requiring another <Tab>. a<Tab> completes to aa and
+# lists aaa, aab, aac as possible completions if the directory contains aaa,
+# aab, aac, bbb instead of only completing to aa.
+setopt nolistambiguous
+# Support completions in the middle of a word, without this option zsh jumps
+# to the end of the word before the completion process begins. Is required for
+# the _prefix completer.
+setopt completeinword
+
+# Force a reload of the completion system if nothing matched; this fixes
+# installing a program and then trying to tab-complete its name. Thanks to
+# Alex Munroe [1] for the code, read on 2014-03-03.
+#
+# [1]: https://github.com/eevee/rc/blob/master/.zshrc
+_force_rehash() {
+ if (( CURRENT == 1 )); then
+ rehash
+ fi
+ # We didn't really complete anything.
+ return 1
+}
+
+zstyle ':completion:::::' completer \
+ _force_rehash _expand _complete _prefix _ignored _approximate
+
+# Match specification to be tried when completing items. Each group ('...') is
+# tried after another if no matches were found, once matches are found no
+# other groups are tried. Thanks to Mikachu in #zsh on Freenode (2012-08-28
+# 18:48 CEST) for explanations.
+#
+# When matching also include the uppercase variant of typed characters
+# ('m:{a-z}={A-Z}'); using '' before this group would try the unmodified match
+# first, but I prefer to get all matches immediately (e.g. if Makefile and
+# makefile exist in the current directory echo m<tab> matches both, with '' it
+# would only match makefile because it found one match). This allows typing in
+# lowercase most of the time and completion fixes the case, which is faster.
+#
+# Don't perform these fixes in _approximate to prevent it from changing the
+# input too much. Thanks to the book "From Bash to Z Shell" page 249.
+zstyle ':completion:*:(^approximate):*' matcher-list 'm:{a-z}={A-Z}'
+
+# Allow one mistake per three characters. Thanks to the book "From Bash to Z
+# Shell" page 248.
+zstyle -e ':completion:*:approximate:*' max-errors \
+ 'reply=( $(( ($#PREFIX + $#SUFFIX) / 3 )) )'
+
+# Expand shell wildcards to all matching files after <Tab>. echo *<Tab>
+# results in a b c if the directory contains the files a, b, c. Thanks to the
+# book "From Bash to Z Shell" page 246.
+zstyle ':completion:*:expand:*' tag-order all-expansions
+# Keep prefixes unexpanded if possible: $HOME/<Tab> doesn't expand $HOME,
+# while $HOME<Tab> does.
+zstyle ':completion:*:expand:*' keep-prefix yes
+
+# When completing multiple path components display all matching ambiguous
+# components. For example /u/s/d/r/README<Tab> lists all matching READMEs
+# instead of just the matching paths up to the r/ component. Can be slow if
+# there are many matching files.
+zstyle ':completion:*' list-suffixes yes
+
+# Use ls-like colors for completions.
+zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
+
+# Make completion lists scrollable so "do you wish to see all n possibilities"
+# is no longer displayed. Display current position in percent (%p).
+zstyle ':completion:*:default' list-prompt '%p'
+# Display group name (%d) (like 'external command', 'alias', etc.), in bold.
+# Also display a message if _approximate found errors and no matches were
+# found.
+zstyle ':completion:*' format ' %B%d%b:'
+zstyle ':completion:*:corrections' format ' %B%d%b (errors: %e)'
+zstyle ':completion:*:warnings' format ' %Bno matches for %d%b'
+# Display different types of matches separately.
+zstyle ':completion:*' group-name ''
+
+# Separate man pages by section.
+zstyle ':completion:*' separate-sections yes
+
+# Don't draw trailing / in bold (new in zsh 4.3.11). Thanks to Mikachu in #zsh
+# on Freenode for the fix (2010-12-17 13:46 CET).
+zle_highlight=(suffix:none)
+
+# Ignore completion functions.
+zstyle ':completion:*:functions' ignored-patterns '_*'
+
+# When offering typo corrections, do not propose anything which starts with an
+# underscore (such as many of Zsh's shell functions). Thanks to paradigm [1]
+# for the idea (read on 2013-04-07).
+#
+# [1]: https://github.com/paradigm/dotfiles/blob/master/.zshrc
+CORRECT_IGNORE='_*'
+
+# Ignore parent directory.
+zstyle ':completion:*:(cd|mv|cp):*' ignore-parents parent pwd
+# Always complete file names only once in the current line. This makes it easy
+# to complete multiple file names because I can just press tab to get all
+# possible values. Otherwise I would have to skip the first value again and
+# again. Thanks to Mikachu in #zsh on Freenode (2011-08-11 14:42 CEST) for the
+# hint to use other. other is necessary so prefix<Tab> lists both prefix and
+# prefixrest if the directory contains prefix and prefixrest.
+zstyle ':completion:*:all-files' ignore-line other
+# Except for mv and cp, because I often want to use to similar names, so I
+# complete to the same and change it.
+zstyle ':completion:*:(mv|cp):all-files' ignore-line no
+
+# Don't complete ./config.* files, this makes running ./configure much
+# simpler. Thanks to Nomexous in #zsh on Freenode (2010-03-16 01:54 CET)
+zstyle ':completion:*:*:-command-:*' ignored-patterns './config.*'
+# Don't complete unwanted files with Vim. Thanks to Nomexous in #zsh on
+# Freenode (2010-06-06 04:54 CEST). See below for a way to complete them.
+zstyle ':completion:*:*:vim:*:all-files' ignored-patterns \
+ '*.aux' '*.log' '*.pdf' '*.bbl' '*.blg' '*.out' '*-blx.bib' '*.run.xml' \
+ '*.o' \
+ '*.pyc' \
+ '*.class'
+
+# Provide a fallback completer which always completes files. Useful when Zsh's
+# completion is too "smart". Thanks to Frank Terbeck <ft@bewatermyfriend.org>
+# (http://www.zsh.org/mla/users/2009/msg01038.html).
+zle -C complete-files complete-word _generic
+zstyle ':completion:complete-files:*' completer _files
+bindkey '^F' complete-files
+
+# Completion for my wrapper scripts.
+compdef slocate=locate
+compdef srsync=rsync
+compdef srsync-incremental=rsync
+compdef svalgrind=valgrind
+compdef sc=systemctl
+
+
+# CUSTOM ALIASES AND FUNCTIONS
+
+# If ^C is pressed while typing a command, add it to the history so it can be
+# easily retrieved later and then abort like ^C normally does. This is useful
+# when I want to abort an command to do something in between and then finish
+# typing the command.
+#
+# Thanks to Vadim Zeitlin <vz-zsh@zeitlins.org> for a fix (--) so lines
+# starting with - don't cause errors; and to Nadav Har'El
+# <nyh@math.technion.ac.il> for a fix (-r) to handle whitespace/quotes
+# correctly, both on the Zsh mailing list.
+TRAPINT() {
+ # Don't store this line in history if histignorespace is enabled and the
+ # line starts with a space.
+ if [[ -o histignorespace && ${BUFFER[1]} = ' ' ]]; then
+ return $1
+ fi
+
+ # Store the current buffer in the history.
+ zle && print -s -r -- $BUFFER
+
+ # Return the default exit code so Zsh aborts the current command.
+ return $1
+}
+
+# Load aliases and similar functions also used by other shells.
+if [[ -f ~/.shell/aliases ]]; then
+ . ~/.shell/aliases
+fi
+
+# Make sure aliases are expanded when using sudo.
+alias sudo='sudo '
+
+# Global aliases for often used redirections.
+alias -g E='2>&1'
+alias -g N='>/dev/null'
+alias -g EN='2>/dev/null'
+alias -g L='2>&1 | less'
+alias -g LS='2>&1 | less -S' # -S prevents wrapping of long lines
+alias -g D='2>&1 | colordiff | less'
+# Global aliases for often used commands.
+alias -g A='| awk'
+alias -g A1="| awk '{ print \$1 }'"
+alias -g A2="| awk '{ print \$2 }'"
+alias -g A3="| awk '{ print \$3 }'"
+alias -g G='| grep'
+alias -g GB='| grep -vE "^Binary file .+ matches\$"'
+alias -g H='| head'
+alias -g P='| perl'
+alias -g S='| sort'
+alias -g SL='| sort | less'
+alias -g T='| tail'
+alias -g U='| uniq'
+alias -g X='`xsel -p || xclip -o`' # X selection
+
+# Make going up directories simple.
+alias -g ...='../..'
+alias -g ....='../../..'
+alias -g .....='../../../..'
+
+# If the window naming feature is used (see above) then use ".zsh" (leading
+# dot) as title name after running clear so it's clear to me that the window
+# is empty. I open so much windows that I don't know in which I have something
+# important. This helps me to remember which windows are empty (I run clear
+# after I finished my work in a window).
+if [[ -n $zshrc_window_reset ]]; then
+ alias clear='clear; zshrc_window_reset=yes; zshrc_window_precmd reset'
+fi
+
+
+# CUSTOM COMMANDS
+
+# Display all branches (except stash) in gitk but only 200 commits as this is
+# much faster. Also put in the background and disown. Thanks to drizzd in #git
+# on Freenode (2010-04-03 17:55 CEST).
+(( $+commands[gitk] )) && gitk() {
+ command gitk --max-count=200 --branches --remotes --tags "$@" &
+ disown %command
+}
+# Same for tig (except the disown part as it's no GUI program).
+(( $+commands[tig] )) && tig() {
+ command tig --max-count=200 --branches --remotes --tags "$@"
+}
+
+# Choose the "best" PDF viewer available. Also setup completion for `pdf`.
+if (( $+commands[katarakt] )); then
+ pdf() {
+ command katarakt "$@" 2>/dev/null &
+ disown %command
+ }
+ # No completion for katarakt yet.
+ compdef pdf=xpdf
+elif (( $+commands[xpdf] )); then
+ pdf() {
+ command xpdf "$@" 2>/dev/null &
+ disown %command
+ }
+ compdef pdf=xpdf
+elif (( $+commands[zathura] )); then
+ pdf() {
+ command zathura "$@" 2>/dev/null &
+ disown %command
+ }
+ # No completion for zathura yet.
+ compdef pdf=xpdf
+fi
+
+
+# OS SPECIFIC SETTINGS
+
+if [[ $OSTYPE == linux* ]]; then
+ # Settings when creating Debian packages.
+ export DEBEMAIL=simon@ruderich.org
+ export DEBFULLNAME='Simon Ruderich'
+fi
+
+
+# LOAD ADDITIONAL CONFIGURATION FILES
+
+# Configuration options for rc.local.
+
+# Multiplexer to use. By default GNU screen is used. Possible values: screen,
+# tmux and empty (no multiplexer).
+zshrc_use_multiplexer=screen
+# Additional arguments for fortune.
+zshrc_fortune_arguments=()
+
+source_config ~/.zsh/rc.local
+
+
+# RUN COMMANDS
+
+# Make sure the multiplexer is available. Otherwise the exec terminates our
+# session.
+if [[ -n $zshrc_use_multiplexer ]]; then
+ if ! (( $+commands[$zshrc_use_multiplexer] )); then
+ echo "Multiplexer '$zshrc_use_multiplexer' not found." >&2
+ zshrc_use_multiplexer=
+ fi
+fi
+
+# If not already in screen or tmux, reattach to a running session or create a
+# new one. This also starts screen/tmux on a remote server when connecting
+# through ssh.
+if [[ $TERM != dumb && $TERM != dialup && $TERM != linux
+ && -z $STY && -z $TMUX ]]; then
+ # Get running detached sessions.
+ if [[ $zshrc_use_multiplexer = screen ]]; then
+ session=$(screen -list | grep 'Detached' | awk '{ print $1; exit }')
+ elif [[ $zshrc_use_multiplexer = tmux ]]; then
+ session=$(tmux list-sessions 2>/dev/null \
+ | sed '/(attached)$/ d; s/^\([0-9]\{1,\}\).*$/\1/; q')
+ fi
+
+ # As we exec later we have to set the title here.
+ if [[ $zshrc_use_multiplexer = screen ]]; then
+ zshrc_window_preexec screen
+ elif [[ $zshrc_use_multiplexer = tmux ]]; then
+ zshrc_window_preexec tmux
+ fi
+
+ # Create a new session if none is running.
+ if [[ -z $session ]]; then
+ if [[ $zshrc_use_multiplexer = screen ]]; then
+ exec screen
+ elif [[ $zshrc_use_multiplexer = tmux ]]; then
+ exec tmux
+ fi
+ # Reattach to a running session.
+ else
+ if [[ $zshrc_use_multiplexer = screen ]]; then
+ exec screen -r $session
+ elif [[ $zshrc_use_multiplexer = tmux ]]; then
+ exec tmux attach-session -t $session
+ fi
+ fi
+fi
+
+# Colorize stderr in bold red. Very useful when looking for errors.
+if [[ $LD_PRELOAD != *libcoloredstderr.so* ]]; then
+ # coloredstderr found, use it.
+ if [[ -f ~/.zsh/libcoloredstderr.so ]]; then
+ export LD_PRELOAD="$HOME/.zsh/libcoloredstderr.so:$LD_PRELOAD"
+ export COLORED_STDERR_FDS=2,
+ export COLORED_STDERR_PRE=$'\033[91m' # bright red
+ export COLORED_STDERR_IGNORED_BINARIES=/usr/bin/tset
+ # Use the fallback solution.
+ #
+ # Thanks to http://gentoo-wiki.com/wiki/Zsh for the basic script and
+ # Mikachu in #zsh on Freenode (2010-03-07 04:03 CET) for some improvements
+ # (-r, printf). It's not yet perfect and doesn't work with su and git for
+ # example, but it can handle most interactive output quite well (even with
+ # no trailing new line) and in cases it doesn't work, the E alias can be
+ # used as workaround.
+ #
+ # Moved in the "run commands" section to prevent one unnecessary zsh
+ # process when starting GNU screen/tmux (see above).
+ else
+ exec 2>>(while read -r -k -u 0 line; do
+ printf '\e[91m%s\e[0m' $line
+ print -n $'\0'
+ done &)
+ fi
+fi
+
+# Display possible log messages from ~/.xinitrc (if `xmessage` wasn't
+# installed). No race condition as xinitrc has finished before a shell is
+# executed and only one shell is started on login.
+if [[ -f ~/.xinitrc.errors ]]; then
+ echo "${fg_bold[red]}xinitrc failed!${fg_bold[default]}"
+ echo
+ cat ~/.xinitrc.errors
+ rm ~/.xinitrc.errors
+ echo
+fi
+
+# Run the following programs every 4 hours (and when zsh starts).
+PERIOD=14400
+periodic() {
+ # Display fortunes.
+ (( $+commands[fortune] )) && fortune -ac "${zshrc_fortune_arguments[@]}"
+ # Display reminders.
+ (( $+commands[rem] )) && [[ -f ~/.reminders ]] && rem -h
+}
+
+
+# RESTART SETTINGS
+
+zmodload -F zsh/stat b:zstat
+
+# Remember startup time. Used to perform automatic restarts when ~/.zshrc is
+# modified.
+zshrc_startup_time=$EPOCHSECONDS
+
+# Automatically restart Zsh if ~/.zshrc was modified.
+zshrc_restart_precmd() {
+ local stat
+ if ! zstat -A stat +mtime ~/.zshrc; then
+ return
+ fi
+
+ # ~/.zshrc wasn't modified, nothing to do.
+ if [[ $stat -le $zshrc_startup_time ]]; then
+ return
+ fi
+
+ local startup
+ strftime -s startup '%Y-%m-%d %H:%M:%S' $zshrc_startup_time
+
+ echo -n "${fg[magenta]}"
+ echo -n "~/.zshrc modified since startup ($startup) ... "
+ echo -n "${fg[default]}"
+
+ if [[ -n $zshrc_disable_restart ]]; then
+ echo 'automatic restart disabled.'
+ return
+ fi
+
+ # Don't exec if we have background processes because execing will let us
+ # lose control over them.
+ if [[ ${#${(k)jobstates}} -ne 0 ]]; then
+ echo 'active background jobs!'
+ return
+ fi
+
+ # Try to start a new interactive shell. If it fails, something is wrong.
+ # Don't kill our current session by execing it, abort instead.
+ zsh -i -c 'exit 42'
+ if [[ $? -ne 42 ]]; then
+ echo -n ${fg_bold[red]}
+ echo 'failed to start new zsh!'
+ echo -n ${fg_bold[default]}
+ return
+ fi
+
+ echo 'restarting zsh.'
+ echo
+
+ exec zsh
+}
+precmd_functions+=(zshrc_restart_precmd)
+
+
+# RELOAD SETTINGS
+
+zshenv_reload_time=0 # load before first command
+zshenv_boot_time=$(date -d "$(uptime -s)" '+%s') # uptime in epoch seconds
+
+# Automatically source ~/.zsh/env.update when the file changes (and exists).
+# Can be used e.g. to update SSH_AGENT_PID and GPG_AGENT_INFO variables in
+# running zsh processes. Sourced immediately before executing shell commands
+# (preexec) to ensure the environment is always up to date.
+zshenv_reload_preexec() {
+ local file
+ file=~/.zsh/env.update
+
+ local stat
+ if ! zstat -A stat +mtime $file 2>/dev/null; then
+ return
+ fi
+ # File was modified before reboot. Skip it to prevent loading of old
+ # values.
+ if [[ $stat -lt $zshenv_boot_time ]]; then
+ return
+ fi
+ # File wasn't modified, nothing to do.
+ if [[ $stat -le $zshenv_reload_time ]]; then
+ return
+ fi
+ zshenv_reload_time=$EPOCHSECONDS
+
+ unsetopt warn_create_global
+ . $file
+ setopt warn_create_global
+}
+preexec_functions+=(zshenv_reload_preexec)
+
+# vim: ft=zsh