Skip to content

Latest commit

 

History

History
668 lines (528 loc) · 17.4 KB

zsh.org

File metadata and controls

668 lines (528 loc) · 17.4 KB

ZSH Configuration file

Load Antigen

I use antigen as plugin manager for my zsh.

source /usr/share/zsh/scripts/antigen/antigen.zsh

Enable extra/plugins/modules

The “command not found” hook.

Automatically search the official repositories, if you enter an unrecognized command.

source /usr/share/doc/pkgfile/command-not-found.zsh

Fish shell like syntax highlighting for Zsh.

This one’s awesome. It highlights what you’re typing in real time.

antigen bundle zsh-users/zsh-syntax-highlighting

Color the highlighting to your liking.

ZSH_HIGHLIGHT_HIGHLIGHTERS=(main brackets pattern)

# Aliases and functions
ZSH_HIGHLIGHT_STYLES[alias]='fg=blue,bold'
ZSH_HIGHLIGHT_STYLES[function]='fg=cyan,bold'

# Commands and builtins
ZSH_HIGHLIGHT_STYLES[command]="fg=green"
ZSH_HIGHLIGHT_STYLES[hashed-command]="fg=green,bold"
ZSH_HIGHLIGHT_STYLES[builtin]="fg=green,bold"
ZSH_HIGHLIGHT_STYLES[precommand]="fg=green,underline"
ZSH_HIGHLIGHT_STYLES[commandseparator]="none"

# Paths
ZSH_HIGHLIGHT_STYLES[path]='fg=white,underline'

# Globbing
ZSH_HIGHLIGHT_STYLES[globbing]='fg=yellow,bold'

# Options and arguments
ZSH_HIGHLIGHT_STYLES[single-hyphen-option]='fg=red'
ZSH_HIGHLIGHT_STYLES[double-hyphen-option]='fg=red'

ZSH_HIGHLIGHT_STYLES[back-quoted-argument]="fg=green"
ZSH_HIGHLIGHT_STYLES[single-quoted-argument]="fg=green"
ZSH_HIGHLIGHT_STYLES[double-quoted-argument]="fg=green"
ZSH_HIGHLIGHT_STYLES[dollar-double-quoted-argument]="fg=green"
ZSH_HIGHLIGHT_STYLES[back-double-quoted-argument]="fg=green"

# Patterns
ZSH_HIGHLIGHT_PATTERNS+=('mv *' 'fg=white,bold,bg=red')
ZSH_HIGHLIGHT_PATTERNS+=('rm -rf *' 'fg=white,bold,bg=red')
ZSH_HIGHLIGHT_PATTERNS+=('sudo ' 'fg=white,bold,bg=red')

ZSH port of Fish shell’s history search feature.

Type part of a command that you have run in the past, push the up|down arrow, or using emacs style like ^N ^P and start going back in time to your previous commands that match that sub string.

antigen bundle zsh-users/zsh-history-substring-search

Settings.

# bind UP and DOWN arrow keys
for keycode in '[' '0'; do
bindkey "^[${keycode}A" history-substring-search-up
  bindkey "^[${keycode}B" history-substring-search-down
done
unset keycode

# bind P and N for EMACS mode
bindkey -M emacs '^P' history-substring-search-up
bindkey -M emacs '^N' history-substring-search-down

Tell antigen that you’re done

You have to add this command after defining all bundles you need, in your zshrc. The completions defined by your bundles will be loaded at this step.

antigen-apply

Quoting URLs

Functions to make it easier to type URLs as command line arguments.

autoload -U url-quote-magic
zle -N self-insert url-quote-magic

Fix Emacs multi-term colors

if [ "$EMACS" ];then
    export TERM=Eterm-color
fi

Glabal options

setopt nobeep                  # i hate beeps
setopt alwaystoend             # when complete from middle, move cursor
setopt autopushd               # automatically append dirs to the push/pop list
setopt cdablevars              # avoid the need for an explicit $
setopt correct_all             # correct all the words in the command line
setopt noflowcontrol           # if I could disable Ctrl-s completely I would!
setopt RM_STAR_WAIT            # confirmation after 'rm *' etc..

Completion stuff

Completion in zsh is awesome. One of the most complex parts of the shell.

Load completions

autoload -U compinit
compinit
zmodload zsh/complist

Options

setopt completealiases         # complete alisases
setopt extendedglob            # weird & wacky pattern matching - yay zsh!
setopt nolisttypes             # show types in completion
setopt autolist                # filename completion
setopt listpacked              # compact completion lists
setopt MARK_DIRS               # Append a trailing `/' to all directory names resulting from filename generation (globbing).
setopt completeinword          # not just at the end

Formatting and messages

zstyle ':completion:*' verbose yes
zstyle ':completion:*:descriptions' format $'%{\e[0;33m%} %B%d%b%{\e[0m%}'
zstyle ':completion:*:messages' format '%d'
zstyle ':completion:*:warnings' format 'No matches for: %d'
zstyle ':completion:*:corrections' format '%B%d (errors: %e)%b'
zstyle ':completion:*' group-name ''
zstyle ':completion:*:manuals' separate-sections true
zstyle ':completion:*' auto-description 'specify: %d'
zstyle ':completion:*:default' list-prompt'%S%M matches%s'
zstyle ':completion:*:prefix:*' add-space true

Speed up zsh completion

zstyle ':completion:*:paths' accept-exact '*(N)'
zstyle ':completion::complete:*' use-cache on
zstyle ':completion:*' cache-path ~/.zsh/cache

Zsh auto rehash commands

Sometimes zsh not recognize the executable when installing a new program. To rebuild the cache of executable commands, add the following line to your ~/.zshrc file.

zstyle ':completion:*' rehash true

Case sensitive, partial word and substring completion

zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=*' 'l:|=* r:|=*'

Activate menu selection

Autocompletion with an arrow-key driven interface.

zstyle ':completion:*' menu select=2

Color/list

Get zsh to color the completed part of the results when using tab completion.

zstyle ':completion:*' list-colors "=(#b) #([0-9]#)*=34=36"

My process (killer) completion

I really like the kill|all autocomplete functionality of zsh.

zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#)*=0=01;31'
zstyle ':completion:*:kill:*' command 'ps -u $(whoami) -o pid,%cpu,tty,cputime,cmd'
zstyle ':completion:*:*:killall:*' menu yes select
zstyle ':completion:*:killall:*' force-list always

Starting and Stopping Processes: Signals, Job Control

Report CPU usage for commands running longer than 10 seconds.

export TIMEFMT="%U user %S system %P cpu %*E total, running %J"
REPORTTIME=10

Directory

Most of these commands are used for quick navigation.

Options

setopt autocd                   # change to dirs without cd
setopt pushd_to_home            # Push to home directory when no argument is given.
setopt auto_pushd               # Push the old directory onto the stack on cd.
setopt auto_name_dirs           # Auto add variable-stored paths to ~ list.
setopt pushd_ignore_dups        # Do not store duplicates in the stack.

Functions

cd () {
  if   [[ "x$*" == "x..." ]]; then
    cd ../..
  elif [[ "x$*" == "x...." ]]; then
    cd ../../..
  elif [[ "x$*" == "x....." ]]; then
    cd ../../..
  elif [[ "x$*" == "x......" ]]; then
    cd ../../../..
  else
    builtin cd "$@"
  fi
}

function mcd() {
    mkdir -p "$1" && cd "$1";
}

Aliases

alias ..='cd ..'
alias cd..='cd ..'
alias cd...='cd ../..'
alias cd....='cd ../../..'
alias cd.....='cd ../../../..'
alias cd/='cd /'

alias 1='cd -'
alias 2='cd +2'
alias 3='cd +3'
alias 4='cd +4'
alias 5='cd +5'
alias 6='cd +6'
alias 7='cd +7'
alias 8='cd +8'
alias 9='cd +9'

alias d='dirs -v | head -10'

History

Variables

HISTFILE=$HOME/.zsh_history
HISTSIZE=10000
SAVEHIST=10000

Options

setopt append_history     # Allow multiple terminal sessions to all append to one zsh command history
setopt extended_history   # Include more information about when the command was executed, etc
setopt hist_ignore_dups   # Ignore duplication command history list
setopt hist_reduce_blanks # Remove extra blanks from each command line being added to history
setopt inc_append_history # Add comamnds as they are typed, don't wait until shell exit'
setopt hist_find_no_dups  # When searching history don't display results already cycled through twice'
setopt share_history      # Share command history data

Terminal

dircolors

Configure the color of ls directory.

eval `dircolors ~/.dircolors`

Aliases

Compile/Sources

alias cm='./configure && make'
alias mmi='make && sudo make install'
alias pmmi='perl Makefile.PL && mmi'
alias maek='make'
alias mkae='make'
alias pipr='pip install --no-deps --ignore-installed'

Emacs

alias emacs='emacsclient -ca'
alias ec='emacsclient -c'
alias et='emacsclient -t'
alias eamcs='emacs'
alias emcs='emacs'
alias em='emacsclient -n -a ""'
alias es="SUDO_EDITOR=\"emacsclient -t -a emacs\" sudoedit"
alias E='es'
alias magit='et -e "(magit-status \"$(pwd)\")"'
alias top='et -e "(proced)"'
alias efm='et -e "(dired-jump \"$(pwd)\")"'
alias emacs_compile="emacs -batch -f batch-byte-compile"

Apps

alias sl="screen -list"  # GNU/Screen
alias wiki='wiki-search' # Archlinux-Wiki
alias rat='ratpoison'    # Ratpoison
alias itmages='itmages-upload' # Picture uploade script for ITmages.ru
alias stinth='printf "#%02X%02X%02X" $(stint)""' # suckless-style color grabber

PACMAN/AUR

alias pacman='pacman --color=always'
alias pachist="awk -F' ' /\(starting\|upgraded\|downgraded\|installed\)/'{print \$1,\$2,\$5,\$6,\$7,\$8}' /var/log/pacman.log | sed 's/.*full.*//'"
alias pac_mirror_update='sudo mv /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.backup+`date +"%m-%d-%y"`; sudo reflector -l 10 --sort rate --save /etc/pacman.d/mirrorlist'
alias cower='cower --color=always'
alias cowerd='cower --download --force --target=/home/ivo/abs'
alias updates='checkupdates && cower -u'

PKGBUILD’s

alias mp='makepkg'
alias mpf='makepkg -f'
alias mpsi='makepkg -si'
alias mpg='makepkg -g >> PKGBUILD'
alias mps='makepkg -g >> PKGBUILD && makepkg -f'
alias ms='makepkg --source'
alias msf='makepkg --source -f'

Systemd

alias ctl='sudo systemctl'
startd() { ctl start $1.service; ctl status $1.service; }
stopd() { ctl stop $1.service; ctl status $1.service; }
restartd() { ctl restart $1.service; ctl status $1.service; }
statusd() { ctl status $1.service; }
enabled() { ctl enable $1.service; listd; }
disabled() { ctl disable $1.service; listd; }

Maintenance

Show logs.

alias journalctl-error='sudo journalctl -b --priority 0..3'

Trashes files.

  1. Trash a file
  2. Remove all files from the trashcan
alias rm='trash-put'
alias trash='trash-empty'

Auto extension stuff

alias -s {ogg,mp3,wav,wma}="mplayer"
alias -s {avi,mpeg,mpg,mov,m2v,flv}="mplayer"
alias -s {png,gif,jpg,jpeg}="sxiv"
alias -s {doc,pdf}="xpdf"
alias -s {txt,c,h,conf,tex}=$EDITOR
alias -s PKGBUILD=$EDITOR
alias -s {html,php,com,net,org,gov}=$BROWSER
alias -s torrent='transmission-gtk'

No/Correct commands

alias man='nocorrect man'
alias mv='nocorrect mv'
alias mysql='nocorrect mysql'
alias mkdir='nocorrect mkdir'
alias sudo='nocorrect sudo'

General

alias cp='cp -RPv'
alias la='ls -a'
alias lsa='ls -lah'
alias l='ls -la'
alias ll='ls -l'
alias ls='ls -Xp --color=auto'
alias mk='mkdir -p'
alias mkdir='mk'
alias mv='mv -i'
alias wget='wget -c'
alias history='fc -l 1'
alias h='history'
alias ssh='ssh -X'
alias grep='grep --color=auto'
alias free='free -m'
alias open='xdg-open'
alias c='clear'
alias q='exit'
alias Q='q'
alias t='touch'
alias j='jobs'

Mount devices

alias cdmount='sudo mount /dev/sr0 /mnt/cdrom/'
alias usb='sudo mount /dev/sdb1 /mnt/usb'
alias uusb='sudo umount /mnt/usb'

Wireless/Network

alias myip='curl ifconfig.me'
alias pi='ping -c 4 archlinux.org'
alias fw='sudo iptables -L'
alias netctl='sudo netctl'
alias netctl-auto='sudo netctl-auto'
alias myserver='python -m SimpleHTTPServer 8000'
alias speedtest='speedtest-cli --simple'

Global aliases

alias -g H="| head"
alias -g T="| tail"
alias -g G="| grep"
alias -g L="| less"
alias -g M="| most"
alias -g B="&|"
alias -g H="--help"
alias -g LL="2>&1 | less"
alias -g CA="2>&1 | cat -A"
alias -g NE="2> /dev/null"
alias -g NUL="> /dev/null 2>&1"

functions

Packing in the archive

pk () {
    if [ $1 ] ; then
        case $1 in
            tbz) tar cjvf $2.tar.bz2 $2 ;;
            tgz) tar czvf $2.tar.gz $2 ;;
            tar) tar cpvf $2.tar $2 ;;
            bz2) bzip $2 ;;
            gz) gzip -c -9 -n $2 > $2.gz ;;
            zip) zip -r $2.zip $2 ;;
            7z) 7z a $2.7z $2 ;;
            *) echo "'$1' cannot be packed via pk()" ;;
        esac
    else
        echo "'$1' is not a valid file"
    fi
}

Extract files

extract () {
    if [ -f $1 ] ; then
        case $1 in
            *.tar.bz2) tar xvjf $1 ;;
            *.tar.gz) tar xvzf $1 ;;
            *.bz2) bunzip2 $1 ;;
            *.rar) rar x $1 ;;
            *.gz) gunzip $1 ;;
            *.tar) tar xvf $1 ;;
            *.tbz2) tar xvjf $1 ;;
            *.tgz) tar xvzf $1 ;;
            *.zip) unzip $1 ;;
            *.Z) uncompress $1 ;;
            *.7z) 7z x $1 ;;
            *) echo "don't know how to extract '$1′…" ;;
        esac
     else
        echo "'$1′ is not a valid file!"
     fi
}

Remove orphans (Archlinux)

orphans() {
    if [[ ! -n $(pacman -Qdt) ]]; then
        echo no orphans to remove
    else
        sudo pacman -Rs $(pacman -Qdtq)
    fi
}

Diff

if command -v colordiff > /dev/null 2>&1; then
    alias diff="colordiff -Nuar"
else
    alias diff="diff -Nuar"
fi

Profile

ENV

export EDITOR="emacs"
export CC="/usr/bin/gcc"
export BROWSER="conkeror"
export HOMEPAGE="https://bbs.archlinux.org/search.php?action=show_new"
export SDL_AUDIODRIVER='alsa'
export GTK2_RC_FILES="$HOME/.gtkrc-2.0"
export XDG_CONFIG_HOME="$HOME/.config"
export PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:$HOME/bin"

Encoding

export LANG="en_US.UTF-8"
export LC_ALL=$LANG
export LC_COLLATE=$LANG
export LC_CTYPE=$LANG
export LC_MESSAGES=$LANG
export LC_MONETARY=$LANG
export LC_NUMERIC=$LANG
export LC_TIME=$LANG
export LC_NAME=$LANG
export LC_TELEPHONE=$LANG
export LESSCHARSET="UTF-8"

The Prompt

Setting up my zsh prompt.

prompt_subst is not set by default.

Turns on command substitution in the prompt (and parameter expansion and arithmetic expansion).

setopt prompt_subst

Load the colors

autoload -U colors && colors

Git prompt

function prompt_char {
    git branch >/dev/null 2>/dev/null && echo '±' && return
    hg root >/dev/null 2>/dev/null && echo '' && return
    echo '$'
}

function git_branch {
    BRANCH="$(git symbolic-ref HEAD 2>/dev/null | cut -d'/' -f3)"
    if ! test -z $BRANCH; then
        COL="%{$fg[green]%}" # Everything's fine
        [[ $(git log origin/master..HEAD 2> /dev/null ) != "" ]] && COL="%{$fg[red]%}" # We have changes to push
        [[ $(git status --porcelain 2> /dev/null) != "" ]] && COL="%{$fg[yellow]%}" # We have uncommited changes
        echo "%{$fg[green]%}(%{$fg[cyan]%}$(prompt_char) $COL$BRANCH%{$fg[green]%})"
    fi
}

Prompt

PROMPT='$(git_branch)%{$fg[green]%}(%~)%{$reset_color%}%# '
RPROMPT="%(?,%{$fg[green]%};%),%{$fg[red]%};()%f"
#RPROMPT="%{$fg[green]%}%T%{$reset_color%}"
SPROMPT="Correct %{$fg[red]%}%R to %{$fg[green]%}%r?%{$reset_color%} ([%{$fg[green]%}Y%{$reset_color%}]es/[%{$fg[red]%}N%{$reset_color%}]o/[%{$fg[yellow]%}E%{$reset_color%}]dit/[%{$fg[red]%}A%{$reset_color%}]bort) "

Keybindings

Use emacs style

bindkey -e
bindkey '\ew' kill-region
bindkey -s '\el' "ls\n"
bindkey '^r' history-incremental-search-backward
bindkey "^[[5~" up-line-or-history
bindkey "^[[6~" down-line-or-history
bindkey '^[[A' up-line-or-search
bindkey '^[[B' down-line-or-search
bindkey "^[[H" beginning-of-line
bindkey "^[[1~" beginning-of-line
bindkey "^[OH" beginning-of-line
bindkey "^[[4~" end-of-line
bindkey "^[OF" end-of-line
bindkey ' ' magic-space
bindkey "^F" forward-word
bindkey "^B" backward-word
bindkey '^[[Z' reverse-menu-complete
bindkey '^?' backward-delete-char
bindkey "^[[3~" delete-char
bindkey "^[3;5~" delete-char
bindkey "\e[3~" delete-char