# # Generated at Sun Jan 18 23:32:11 MSK 2015 # Version: 4c1bb5ad044208329e6c7c1bf23481c9c9c2ad28 # From https://github.com/azat/dot_files # # Begining of ./bash.bashrc # {{{ # System-wide .bashrc file for interactive bash(1) shells. # # To enable the settings / commands in this file for login shells as well, # this file has to be sourced in /etc/profile. # If not running interactively, don't do anything [ -z "$PS1" ] && return shopt -s checkwinsize # set variable identifying the chroot you work in (used in the prompt below) if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then debian_chroot=$(cat /etc/debian_chroot) fi PROMPT_COMMAND='' for bash_d_it in /etc/bash.d/*.sh; do . $bash_d_it done 2>/dev/null unset bash_d_it # make less more friendly for non-text input files, see lesspipe(1) [ -x /usr/bin/lesspipe ] && eval "$(lesspipe)" # }}} # Begining of /usr/lib/git-core/git-sh-prompt # {{{ # bash/zsh git prompt support # # Copyright (C) 2006,2007 Shawn O. Pearce # Distributed under the GNU General Public License, version 2.0. # # This script allows you to see repository status in your prompt. # # To enable: # # 1) Copy this file to somewhere (e.g. ~/.git-prompt.sh). # 2) Add the following line to your .bashrc/.zshrc: # source ~/.git-prompt.sh # 3a) Change your PS1 to call __git_ps1 as # command-substitution: # Bash: PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ ' # ZSH: setopt PROMPT_SUBST ; PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ ' # the optional argument will be used as format string. # 3b) Alternatively, for a slightly faster prompt, __git_ps1 can # be used for PROMPT_COMMAND in Bash or for precmd() in Zsh # with two parameters,
 and , which are strings
#        you would put in $PS1 before and after the status string
#        generated by the git-prompt machinery.  e.g.
#        Bash: PROMPT_COMMAND='__git_ps1 "\u@\h:\w" "\\\$ "'
#          will show username, at-sign, host, colon, cwd, then
#          various status string, followed by dollar and SP, as
#          your prompt.
#        ZSH:  precmd () { __git_ps1 "%n" ":%~$ " "|%s" }
#          will show username, pipe, then various status string,
#          followed by colon, cwd, dollar and SP, as your prompt.
#        Optionally, you can supply a third argument with a printf
#        format string to finetune the output of the branch status
#
# The repository status will be displayed only if you are currently in a
# git repository. The %s token is the placeholder for the shown status.
#
# The prompt status always includes the current branch name.
#
# In addition, if you set GIT_PS1_SHOWDIRTYSTATE to a nonempty value,
# unstaged (*) and staged (+) changes will be shown next to the branch
# name.  You can configure this per-repository with the
# bash.showDirtyState variable, which defaults to true once
# GIT_PS1_SHOWDIRTYSTATE is enabled.
#
# You can also see if currently something is stashed, by setting
# GIT_PS1_SHOWSTASHSTATE to a nonempty value. If something is stashed,
# then a '$' will be shown next to the branch name.
#
# If you would like to see if there're untracked files, then you can set
# GIT_PS1_SHOWUNTRACKEDFILES to a nonempty value. If there're untracked
# files, then a '%' will be shown next to the branch name.  You can
# configure this per-repository with the bash.showUntrackedFiles
# variable, which defaults to true once GIT_PS1_SHOWUNTRACKEDFILES is
# enabled.
#
# If you would like to see the difference between HEAD and its upstream,
# set GIT_PS1_SHOWUPSTREAM="auto".  A "<" indicates you are behind, ">"
# indicates you are ahead, "<>" indicates you have diverged and "="
# indicates that there is no difference. You can further control
# behaviour by setting GIT_PS1_SHOWUPSTREAM to a space-separated list
# of values:
#
#     verbose       show number of commits ahead/behind (+/-) upstream
#     name          if verbose, then also show the upstream abbrev name
#     legacy        don't use the '--count' option available in recent
#                   versions of git-rev-list
#     git           always compare HEAD to @{upstream}
#     svn           always compare HEAD to your SVN upstream
#
# By default, __git_ps1 will compare HEAD to your SVN upstream if it can
# find one, or @{upstream} otherwise.  Once you have set
# GIT_PS1_SHOWUPSTREAM, you can override it on a per-repository basis by
# setting the bash.showUpstream config variable.
#
# If you would like to see more information about the identity of
# commits checked out as a detached HEAD, set GIT_PS1_DESCRIBE_STYLE
# to one of these values:
#
#     contains      relative to newer annotated tag (v1.6.3.2~35)
#     branch        relative to newer tag or branch (master~4)
#     describe      relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
#     default       exactly matching tag
#
# If you would like a colored hint about the current dirty state, set
# GIT_PS1_SHOWCOLORHINTS to a nonempty value. The colors are based on
# the colored output of "git status -sb" and are available only when
# using __git_ps1 for PROMPT_COMMAND or precmd.

# check whether printf supports -v
__git_printf_supports_v=
printf -v __git_printf_supports_v -- '%s' yes >/dev/null 2>&1

# stores the divergence from upstream in $p
# used by GIT_PS1_SHOWUPSTREAM
__git_ps1_show_upstream ()
{
	local key value
	local svn_remote svn_url_pattern count n
	local upstream=git legacy="" verbose="" name=""

	svn_remote=()
	# get some config options from git-config
	local output="$(git config -z --get-regexp '^(svn-remote\..*\.url|bash\.showupstream)$' 2>/dev/null | tr '\0\n' '\n ')"
	while read -r key value; do
		case "$key" in
		bash.showupstream)
			GIT_PS1_SHOWUPSTREAM="$value"
			if [[ -z "${GIT_PS1_SHOWUPSTREAM}" ]]; then
				p=""
				return
			fi
			;;
		svn-remote.*.url)
			svn_remote[$((${#svn_remote[@]} + 1))]="$value"
			svn_url_pattern="$svn_url_pattern\\|$value"
			upstream=svn+git # default upstream is SVN if available, else git
			;;
		esac
	done <<< "$output"

	# parse configuration values
	for option in ${GIT_PS1_SHOWUPSTREAM}; do
		case "$option" in
		git|svn) upstream="$option" ;;
		verbose) verbose=1 ;;
		legacy)  legacy=1  ;;
		name)    name=1 ;;
		esac
	done

	# Find our upstream
	case "$upstream" in
	git)    upstream="@{upstream}" ;;
	svn*)
		# get the upstream from the "git-svn-id: ..." in a commit message
		# (git-svn uses essentially the same procedure internally)
		local -a svn_upstream
		svn_upstream=($(git log --first-parent -1 \
					--grep="^git-svn-id: \(${svn_url_pattern#??}\)" 2>/dev/null))
		if [[ 0 -ne ${#svn_upstream[@]} ]]; then
			svn_upstream=${svn_upstream[${#svn_upstream[@]} - 2]}
			svn_upstream=${svn_upstream%@*}
			local n_stop="${#svn_remote[@]}"
			for ((n=1; n <= n_stop; n++)); do
				svn_upstream=${svn_upstream#${svn_remote[$n]}}
			done

			if [[ -z "$svn_upstream" ]]; then
				# default branch name for checkouts with no layout:
				upstream=${GIT_SVN_ID:-git-svn}
			else
				upstream=${svn_upstream#/}
			fi
		elif [[ "svn+git" = "$upstream" ]]; then
			upstream="@{upstream}"
		fi
		;;
	esac

	# Find how many commits we are ahead/behind our upstream
	if [[ -z "$legacy" ]]; then
		count="$(git rev-list --count --left-right \
				"$upstream"...HEAD 2>/dev/null)"
	else
		# produce equivalent output to --count for older versions of git
		local commits
		if commits="$(git rev-list --left-right "$upstream"...HEAD 2>/dev/null)"
		then
			local commit behind=0 ahead=0
			for commit in $commits
			do
				case "$commit" in
				"<"*) ((behind++)) ;;
				*)    ((ahead++))  ;;
				esac
			done
			count="$behind	$ahead"
		else
			count=""
		fi
	fi

	# calculate the result
	if [[ -z "$verbose" ]]; then
		case "$count" in
		"") # no upstream
			p="" ;;
		"0	0") # equal to upstream
			p="=" ;;
		"0	"*) # ahead of upstream
			p=">" ;;
		*"	0") # behind upstream
			p="<" ;;
		*)	    # diverged from upstream
			p="<>" ;;
		esac
	else
		case "$count" in
		"") # no upstream
			p="" ;;
		"0	0") # equal to upstream
			p=" u=" ;;
		"0	"*) # ahead of upstream
			p=" u+${count#0	}" ;;
		*"	0") # behind upstream
			p=" u-${count%	0}" ;;
		*)	    # diverged from upstream
			p=" u+${count#*	}-${count%	*}" ;;
		esac
		if [[ -n "$count" && -n "$name" ]]; then
			__git_ps1_upstream_name=$(git rev-parse \
				--abbrev-ref "$upstream" 2>/dev/null)
			if [ $pcmode = yes ] && [ $ps1_expanded = yes ]; then
				p="$p \${__git_ps1_upstream_name}"
			else
				p="$p ${__git_ps1_upstream_name}"
				# not needed anymore; keep user's
				# environment clean
				unset __git_ps1_upstream_name
			fi
		fi
	fi

}

# Helper function that is meant to be called from __git_ps1.  It
# injects color codes into the appropriate gitstring variables used
# to build a gitstring.
__git_ps1_colorize_gitstring ()
{
	if [[ -n ${ZSH_VERSION-} ]]; then
		local c_red='%F{red}'
		local c_green='%F{green}'
		local c_lblue='%F{blue}'
		local c_clear='%f'
	else
		# Using \[ and \] around colors is necessary to prevent
		# issues with command line editing/browsing/completion!
		local c_red='\[\e[31m\]'
		local c_green='\[\e[32m\]'
		local c_lblue='\[\e[1;34m\]'
		local c_clear='\[\e[0m\]'
	fi
	local bad_color=$c_red
	local ok_color=$c_green
	local flags_color="$c_lblue"

	local branch_color=""
	if [ $detached = no ]; then
		branch_color="$ok_color"
	else
		branch_color="$bad_color"
	fi
	c="$branch_color$c"

	z="$c_clear$z"
	if [ "$w" = "*" ]; then
		w="$bad_color$w"
	fi
	if [ -n "$i" ]; then
		i="$ok_color$i"
	fi
	if [ -n "$s" ]; then
		s="$flags_color$s"
	fi
	if [ -n "$u" ]; then
		u="$bad_color$u"
	fi
	r="$c_clear$r"
}

__git_eread ()
{
	f="$1"
	shift
	test -r "$f" && read "$@" <"$f"
}

# __git_ps1 accepts 0 or 1 arguments (i.e., format string)
# when called from PS1 using command substitution
# in this mode it prints text to add to bash PS1 prompt (includes branch name)
#
# __git_ps1 requires 2 or 3 arguments when called from PROMPT_COMMAND (pc)
# in that case it _sets_ PS1. The arguments are parts of a PS1 string.
# when two arguments are given, the first is prepended and the second appended
# to the state string when assigned to PS1.
# The optional third parameter will be used as printf format string to further
# customize the output of the git-status string.
# In this mode you can request colored hints using GIT_PS1_SHOWCOLORHINTS=true
__git_ps1 ()
{
	local pcmode=no
	local detached=no
	local ps1pc_start='\u@\h:\w '
	local ps1pc_end='\$ '
	local printf_format=' (%s)'

	case "$#" in
		2|3)	pcmode=yes
			ps1pc_start="$1"
			ps1pc_end="$2"
			printf_format="${3:-$printf_format}"
		;;
		0|1)	printf_format="${1:-$printf_format}"
		;;
		*)	return
		;;
	esac

	# ps1_expanded:  This variable is set to 'yes' if the shell
	# subjects the value of PS1 to parameter expansion:
	#
	#   * bash does unless the promptvars option is disabled
	#   * zsh does not unless the PROMPT_SUBST option is set
	#   * POSIX shells always do
	#
	# If the shell would expand the contents of PS1 when drawing
	# the prompt, a raw ref name must not be included in PS1.
	# This protects the user from arbitrary code execution via
	# specially crafted ref names.  For example, a ref named
	# 'refs/heads/$(IFS=_;cmd=sudo_rm_-rf_/;$cmd)' might cause the
	# shell to execute 'sudo rm -rf /' when the prompt is drawn.
	#
	# Instead, the ref name should be placed in a separate global
	# variable (in the __git_ps1_* namespace to avoid colliding
	# with the user's environment) and that variable should be
	# referenced from PS1.  For example:
	#
	#     __git_ps1_foo=$(do_something_to_get_ref_name)
	#     PS1="...stuff...\${__git_ps1_foo}...stuff..."
	#
	# If the shell does not expand the contents of PS1, the raw
	# ref name must be included in PS1.
	#
	# The value of this variable is only relevant when in pcmode.
	#
	# Assume that the shell follows the POSIX specification and
	# expands PS1 unless determined otherwise.  (This is more
	# likely to be correct if the user has a non-bash, non-zsh
	# shell and safer than the alternative if the assumption is
	# incorrect.)
	#
	local ps1_expanded=yes
	[ -z "$ZSH_VERSION" ] || [[ -o PROMPT_SUBST ]] || ps1_expanded=no
	[ -z "$BASH_VERSION" ] || shopt -q promptvars || ps1_expanded=no

	local repo_info rev_parse_exit_code
	repo_info="$(git rev-parse --git-dir --is-inside-git-dir \
		--is-bare-repository --is-inside-work-tree \
		--short HEAD 2>/dev/null)"
	rev_parse_exit_code="$?"

	if [ -z "$repo_info" ]; then
		if [ $pcmode = yes ]; then
			#In PC mode PS1 always needs to be set
			PS1="$ps1pc_start$ps1pc_end"
		fi
		return
	fi

	local short_sha
	if [ "$rev_parse_exit_code" = "0" ]; then
		short_sha="${repo_info##*$'\n'}"
		repo_info="${repo_info%$'\n'*}"
	fi
	local inside_worktree="${repo_info##*$'\n'}"
	repo_info="${repo_info%$'\n'*}"
	local bare_repo="${repo_info##*$'\n'}"
	repo_info="${repo_info%$'\n'*}"
	local inside_gitdir="${repo_info##*$'\n'}"
	local g="${repo_info%$'\n'*}"

	local r=""
	local b=""
	local step=""
	local total=""
	if [ -d "$g/rebase-merge" ]; then
		__git_eread "$g/rebase-merge/head-name" b
		__git_eread "$g/rebase-merge/msgnum" step
		__git_eread "$g/rebase-merge/end" total
		if [ -f "$g/rebase-merge/interactive" ]; then
			r="|REBASE-i"
		else
			r="|REBASE-m"
		fi
	else
		if [ -d "$g/rebase-apply" ]; then
			__git_eread "$g/rebase-apply/next" step
			__git_eread "$g/rebase-apply/last" total
			if [ -f "$g/rebase-apply/rebasing" ]; then
				__git_eread "$g/rebase-apply/head-name" b
				r="|REBASE"
			elif [ -f "$g/rebase-apply/applying" ]; then
				r="|AM"
			else
				r="|AM/REBASE"
			fi
		elif [ -f "$g/MERGE_HEAD" ]; then
			r="|MERGING"
		elif [ -f "$g/CHERRY_PICK_HEAD" ]; then
			r="|CHERRY-PICKING"
		elif [ -f "$g/REVERT_HEAD" ]; then
			r="|REVERTING"
		elif [ -f "$g/BISECT_LOG" ]; then
			r="|BISECTING"
		fi

		if [ -n "$b" ]; then
			:
		elif [ -h "$g/HEAD" ]; then
			# symlink symbolic ref
			b="$(git symbolic-ref HEAD 2>/dev/null)"
		else
			local head=""
			if ! __git_eread "$g/HEAD" head; then
				if [ $pcmode = yes ]; then
					PS1="$ps1pc_start$ps1pc_end"
				fi
				return
			fi
			# is it a symbolic ref?
			b="${head#ref: }"
			if [ "$head" = "$b" ]; then
				detached=yes
				b="$(
				case "${GIT_PS1_DESCRIBE_STYLE-}" in
				(contains)
					git describe --contains HEAD ;;
				(branch)
					git describe --contains --all HEAD ;;
				(describe)
					git describe HEAD ;;
				(* | default)
					git describe --tags --exact-match HEAD ;;
				esac 2>/dev/null)" ||

				b="$short_sha..."
				b="($b)"
			fi
		fi
	fi

	if [ -n "$step" ] && [ -n "$total" ]; then
		r="$r $step/$total"
	fi

	local w=""
	local i=""
	local s=""
	local u=""
	local c=""
	local p=""

	if [ "true" = "$inside_gitdir" ]; then
		if [ "true" = "$bare_repo" ]; then
			c="BARE:"
		else
			b="GIT_DIR!"
		fi
	elif [ "true" = "$inside_worktree" ]; then
		if [ -n "${GIT_PS1_SHOWDIRTYSTATE-}" ] &&
		   [ "$(git config --bool bash.showDirtyState)" != "false" ]
		then
			git diff --no-ext-diff --quiet --exit-code || w="*"
			if [ -n "$short_sha" ]; then
				git diff-index --cached --quiet HEAD -- || i="+"
			else
				i="#"
			fi
		fi
		if [ -n "${GIT_PS1_SHOWSTASHSTATE-}" ] &&
		   git rev-parse --verify --quiet refs/stash >/dev/null
		then
			s="$"
		fi

		if [ -n "${GIT_PS1_SHOWUNTRACKEDFILES-}" ] &&
		   [ "$(git config --bool bash.showUntrackedFiles)" != "false" ] &&
		   git ls-files --others --exclude-standard --error-unmatch -- '*' >/dev/null 2>/dev/null
		then
			u="%${ZSH_VERSION+%}"
		fi

		if [ -n "${GIT_PS1_SHOWUPSTREAM-}" ]; then
			__git_ps1_show_upstream
		fi
	fi

	local z="${GIT_PS1_STATESEPARATOR-" "}"

	# NO color option unless in PROMPT_COMMAND mode
	if [ $pcmode = yes ] && [ -n "${GIT_PS1_SHOWCOLORHINTS-}" ]; then
		__git_ps1_colorize_gitstring
	fi

	b=${b##refs/heads/}
	if [ $pcmode = yes ] && [ $ps1_expanded = yes ]; then
		__git_ps1_branch_name=$b
		b="\${__git_ps1_branch_name}"
	fi

	local f="$w$i$s$u"
	local gitstring="$c$b${f:+$z$f}$r$p"

	if [ $pcmode = yes ]; then
		if [ "${__git_printf_supports_v-}" != yes ]; then
			gitstring=$(printf -- "$printf_format" "$gitstring")
		else
			printf -v gitstring -- "$printf_format" "$gitstring"
		fi
		PS1="$ps1pc_start$gitstring$ps1pc_end"
	else
		printf -- "$printf_format" "$gitstring"
	fi
}

# }}}

# Begining of ./bash.d/aliases.sh
# {{{

if [ "$TERM" != "dumb" ]; then
    eval "`dircolors -b`"
    alias ls='ls --color=auto'
    alias dir='ls --color=auto --format=vertical'
    alias vdir='ls --color=auto --format=long'
    alias lss='ls --color=never'
    alias grep='grep --color=auto'
fi

alias ll='ls -l'
alias la='ls -A'
alias l='ls -CF'
alias tm='tmux attach || tmux new'
alias sortfast="sort -S$(($(sed '/MemT/!d;s/[^0-9]*//g' /proc/meminfo)/1024-200)) --parallel=$(($(grep -c ^proc /proc/cpuinfo)*2))"
alias save_kde_session='qdbus org.kde.ksmserver /KSMServer org.kde.KSMServerInterface.saveCurrentSession'
alias f='find ./ -name'
alias strings='strings -a'

# }}}

# Begining of ./bash.d/autocd.sh
# {{{

# 
shopt -s autocd

# }}}

# Begining of ./bash.d/awk.sh
# {{{


alias awksum='awk "{sum += \$NF} END {print sum}"'


# }}}

# Begining of ./bash.d/colors.sh
# {{{

# Colors
# @link http://mediadoneright.com/content/ultimate-git-ps1-bash-prompt 

# Reset
Color_Off="\[\e[0m\]"       # Text Reset

# Regular Colors
Black="\[\e[0;30m\]"        # Black
Red="\[\e[0;31m\]"          # Red
Green="\[\e[0;32m\]"        # Green
Yellow="\[\e[0;33m\]"       # Yellow
Blue="\[\e[0;34m\]"         # Blue
Purple="\[\e[0;35m\]"       # Purple
Cyan="\[\e[0;36m\]"         # Cyan
White="\[\e[0;37m\]"        # White

# Bold
BBlack="\[\e[1;30m\]"       # Black
BRed="\[\e[1;31m\]"         # Red
BGreen="\[\e[1;32m\]"       # Green
BYellow="\[\e[1;33m\]"      # Yellow
BBlue="\[\e[1;34m\]"        # Blue
BPurple="\[\e[1;35m\]"      # Purple
BCyan="\[\e[1;36m\]"        # Cyan
BWhite="\[\e[1;37m\]"       # White

# Underline
UBlack="\[\e[4;30m\]"       # Black
URed="\[\e[4;31m\]"         # Red
UGreen="\[\e[4;32m\]"       # Green
UYellow="\[\e[4;33m\]"      # Yellow
UBlue="\[\e[4;34m\]"        # Blue
UPurple="\[\e[4;35m\]"      # Purple
UCyan="\[\e[4;36m\]"        # Cyan
UWhite="\[\e[4;37m\]"       # White

# Background
On_Black="\[\e[40m\]"       # Black
On_Red="\[\e[41m\]"         # Red
On_Green="\[\e[42m\]"       # Green
On_Yellow="\[\e[43m\]"      # Yellow
On_Blue="\[\e[44m\]"        # Blue
On_Purple="\[\e[45m\]"      # Purple
On_Cyan="\[\e[46m\]"        # Cyan
On_White="\[\e[47m\]"       # White

# High Intensty
IBlack="\[\e[0;90m\]"       # Black
IRed="\[\e[0;91m\]"         # Red
IGreen="\[\e[0;92m\]"       # Green
IYellow="\[\e[0;93m\]"      # Yellow
IBlue="\[\e[0;94m\]"        # Blue
IPurple="\[\e[0;95m\]"      # Purple
ICyan="\[\e[0;96m\]"        # Cyan
IWhite="\[\e[0;97m\]"       # White

# Bold High Intensty
BIBlack="\[\e[1;90m\]"      # Black
BIRed="\[\e[1;91m\]"        # Red
BIGreen="\[\e[1;92m\]"      # Green
BIYellow="\[\e[1;93m\]"     # Yellow
BIBlue="\[\e[1;94m\]"       # Blue
BIPurple="\[\e[1;95m\]"     # Purple
BICyan="\[\e[1;96m\]"       # Cyan
BIWhite="\[\e[1;97m\]"      # White

# High Intensty backgrounds
On_IBlack="\[\e[0;100m\]"   # Black
On_IRed="\[\e[0;101m\]"     # Red
On_IGreen="\[\e[0;102m\]"   # Green
On_IYellow="\[\e[0;103m\]"  # Yellow
On_IBlue="\[\e[0;104m\]"    # Blue
On_IPurple="\[\e[10;95m\]"  # Purple
On_ICyan="\[\e[0;106m\]"    # Cyan
On_IWhite="\[\e[0;107m\]"   # White


# }}}

# Begining of ./bash.d/complete.sh
# {{{

complete -cf sudo
complete -cf gksu
complete -cf kdesudo
complete -cf whereis
complete -cf watch

# }}}

# Begining of ./bash.d/completion.sh
# {{{

#
# bash autocomplete, that parse --help of program
# and use autocomplete in bash!
#
# Use: complete -F complete_by_help -o default {BINARY_NAME}
#

# Known to work with bash 3.* with programmable completion and extended
# pattern matching enabled (use 'shopt -s extglob progcomp' to enable
# these if they are not already enabled).
shopt -s extglob

_get_options()
{
    $* --help 2>&1 | fgrep -- - \
        | awk '{for (i=1; i<=NF; i++) print $i}' \
        | awk -F= '{for (i=1; i<=NF; i++) print $i}' \
        | tr -d ',' | tr -d '[' | tr -d ']' \
        | tr -d '(' | tr -d ')' \
        | tr '|' $'\n' \
        | grep -- ^- | grep -v ^-$ | grep -v ^--$ \
        | sort -u
}

complete_by_help()
{
    local cur
    eval local cmd=$( quote "$1" )

    if [ ! -f "$cmd" ] && ! $( whereis $cmd >& /dev/null ); then
        return 0
    fi

    COMPREPLY=()
    cur="$(_get_cword)"
    prev="$(_get_pword)"

    case "$prev" in
        # Argh...  This looks like a bash bug...
        # Redirections are passed to the completion function
        # although it is managed by the shell directly...
        '<'|'>'|'>>'|[12]'>'|[12]'>>')
            return
            ;;
    esac

    COMPREPLY=( $(compgen -W "$(_get_options $cmd)" -- $cur) )

    return 0
}


# }}}

# Begining of ./bash.d/custom-prompt.sh
# {{{

# Custom prompt
# @link http://awesomerails.wordpress.com/2009/09/21/show-last-two-directories-of-pwd-in-bash-prompt/

# Various variables you might want for your PS1 prompt instead
Prompt_Time12h="\T"
Prompt_Time12a="\@"
Prompt_PathShort="\w"
Prompt_PathFull="\W"
Prompt_NewLine="\n"
Prompt_Jobs="\j"
Prompt_User="\u"

PS1='${debian_chroot:+($debian_chroot)}'

# number of trailing directory components to retain when expanding  the  \w  and  \W
PROMPT_DIRTRIM=2
CUSTOM_PROMPT_LAST_COMMAND_STATUS=0

if [ $USER = "root" ] ; then
	currentUserColor=$URed
	currentUserPostfix='#'
else
	currentUserColor=$UGreen
	currentUserPostfix='\$'
fi

# Simplest PS1
simpleColoredPromptUser=$PS1$currentUserColor$Prompt_User$Color_Off
simpleColoredPromptPath=:$BBlue$Prompt_PathShort$Color_Off
if [ -n "$SSH_CONNECTION" ]; then
	simpleColoredPromptBegin=$simpleColoredPromptUser$currentUserColor@'\h'$Color_Off$simpleColoredPromptPath
else
	simpleColoredPromptBegin=$simpleColoredPromptUser$simpleColoredPromptPath
fi

simpleColoredPrompt=$simpleColoredPromptBegin$currentUserPostfix' '

# git
# If REPO/.git/.repository_is_quite_big is exist, than don't request git-status or something like this.
function _custom_prompt_colored_git()
{
	GIT_DIR="$(git rev-parse --git-dir 2>/dev/null)"
	GIT_PS="$(__git_ps1 " (%s)")"

	if [ -z $GIT_DIR ]; then
		return
	fi

	if [ -f $GIT_DIR/.repository_is_quite_big ] ||
		[[ $GIT_PS =~ ^\ \(BARE: ]] ||
		[[ $GIT_PS = " (GIT_DIR!)" ]]; then
		echo -en $Purple$GIT_PS$Color_Off
		return
	fi

	AHEAD_BEHIND="$(git_ahead_behind)"
	# Trim behind commits (if there is no one)
	AHEAD_BEHIND="${AHEAD_BEHIND%|0}"

	HAVE_CHANGES=1
	if $(git branch &> /dev/null) && $(git status | grep -q "nothing to commit"); then
		HAVE_CHANGES=0
	fi

	if [ $HAVE_CHANGES = "0" ]; then
		echo -en $Green$GIT_PS
	else
		echo -en $Yellow$GIT_PS
	fi
	if [ ! "$AHEAD_BEHIND" = 0 ]; then
		echo -en "["$AHEAD_BEHIND"]"
	fi
	echo -en $Color_Off
}

function _jobs_prompt()
{
	JOBS_NUM=$(jobs -p | xargs -r ps -opid | tail -n+2 | wc -l)

	if [ $JOBS_NUM -gt 0 ]; then
		echo -en " [$ICyan$JOBS_NUM$Color_Off]"
	fi
}

function _date_prompt()
{
	echo -en " | $Green$(date +'%Y-%b-%d %H:%M:%S')$Color_Off"
}

function _render_prompt_preamble()
{
    CUSTOM_PROMPT_LAST_COMMAND_STATUS=$?
}
function _render_prompt()
{
	PS1=
	if [ ! $CUSTOM_PROMPT_LAST_COMMAND_STATUS -eq 0 ]; then
		PS1+="$Red$CUSTOM_PROMPT_LAST_COMMAND_STATUS|"
	fi
	PS1+=$simpleColoredPromptBegin
	if [ $(which git) ] ; then
		PS1+=$(_custom_prompt_colored_git)
	fi
	PS1+=$(_jobs_prompt)
	if (( $DATE_PROMPT )); then
		PS1+=$(_date_prompt)
	fi
	PS1+=$currentUserPostfix' '
}

if [ -n "$PROMPT_COMMAND" ] && [ ! "${PROMPT_COMMAND: -1}" = ';' ]; then
	PROMPT_COMMAND+=';'
fi

# Set window title (Redhat way)
case $TERM in
	xterm*|rxvt*)
		PROMPT_COMMAND+='printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}"; '
	;;
	screen)
		PROMPT_COMMAND+='printf "\033]0;%s@%s:%s\033\\" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}"; '
	;;
esac
PROMPT_COMMAND="_render_prompt_preamble; $PROMPT_COMMAND _render_prompt; "

# }}}

# Begining of ./bash.d/editor.sh
# {{{

export EDITOR=vim

# }}}

# Begining of ./bash.d/functions.sh
# {{{

#
# Bash functions
#

function get_base_name()
{
	local _path=${1/*\//}
	echo "${_path%.*}"
}

function get_path()
{
	# If don't have "/" at all
	if $(expr index "$1" / &>/dev/null); then
		echo "${1/%\/*/}"
	else
		echo "./"
	fi
}

make_file()
{
	local _bin_name="$(get_path "$1")/$(get_base_name "$1")"
	echo "Making '$1' to '$_bin_name'" >&2
	if [ ! -f "$_bin_name" ]; then
		gcc -ofast -std=c99 -o "$_bin_name" "$1"
	fi
	echo "$_bin_name"
}

# mk & cd
function mkcd() {
	[ -n "$1" ] && mkdir -p "$@" && cd "$1";
}

# Search commandlinefu.com from the command line using the API
function cmdfu() {
	curl "http://www.commandlinefu.com/commands/matching/$@/$(echo -n $@ | openssl base64)/plaintext";
}

# mini scp deploy
function scpdeploy() {
	if [ ! "$1" ] ; then
		echo "Usage scpdeploy SERVER_AND_PATH"
		return;
	fi

	cd .. && tar -czf $OLDPWD.tgz `basename $OLDPWD` && scp $OLDPWD.tgz $1 && cd -
}

# mini scp deploy
function scpmdeploy() {
	if [ ! "$1" ] ; then
		echo "Usage scpdeploy SERVER_AND_PATH"
		return;
	fi

	make clean && cd .. && export NOW=`basename $OLDPWD` && rm -f $NOW.tgz && tar -czf $NOW.tgz $NOW && scp $NOW.tgz $1 && cd -
}


# MS Word grep
# Using "antiword" package
function wgrep() {
	if [ $# -lt 2 ]; then
		echo "Usage: wgrep pattern file[ file ...]" > /dev/sderr
		return;
	fi

	WORD=$1

	i=0
	#for file in `ls *.doc | grep -v '^~'`; do
	for file in "$@"; do
		# pattern
		i=$[$i+1]
		if [ $i -eq 1 ]; then
			continue
		fi

		OLDIFS=$IFS
		IFS=""
		out=`antiword $file | grep -niH $WORD`
		if [ $? -eq 0 ]; then
			echo `echo $out | sed -e "s/\(standard input\)/$file/g"`
		fi
		IFS=$OLDIFS
	done
}

# Bak file/dir
# Usage `bak dir1 [ dir2]`
function bak() {
	if [ $# -lt 1 ]; then
		echo "Usage: bak file1[ file2 ...]" > /dev/stderr
	fi

	i=0
	for path in "$@"; do
		i=$[$i+1]
		file=`basename $path`
		len=`echo "${#path}-${#file}" | bc`
		dir=${path:0:len}
		if [ "x$dir" == "x" ]; then
			dir="./"
		fi

		mv "$path" "$dir.$file.bak"
	done
}

# Unbak file/dir
# Usage `unbak dir1 [ dir2]`
function unbak() {
	if [ $# -lt 1 ]; then
		echo "Usage: unbak file1[ file2 ...]" > /dev/stderr
	fi

	i=0
	for path in "$@"; do
		i=$[$i+1]

		# Replace './'
		path=`echo $path | sed 's/^\.\/|\/\.\///g'`

		replace=`echo $path | sed 's/^\.\(.*\)\.bak$/\1/'`
		if [ "$path" == "$replace" ] ; then
			# try to change src file
			file=`basename $path`
			len=`echo "${#path}-${#file}" | bc`
			dir=${path:0:len}
			if [ "x$dir" == "x" ]; then
				dir="./"
			fi
			new_file="$dir/.$file.bak"

			if [ -f $new_file ] ; then
				path=$new_file
			else
				echo "$file is not backup-ed" > /dev/stderr
				continue
			fi
		fi

		mv "$path" "$replace"
	done
}

function random()
{
	head -c${2:-"5000"} /dev/urandom | env LANG=c sed 's/[^0-9a-z]*//g' | \
		tr -d $'\n' | head -c${1:-"10"}; echo
}

# }}}

# Begining of ./bash.d/git.sh
# {{{

function git_ahead_behind()
{
    curr_branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
    curr_remote=$(git config branch.$curr_branch.remote)
    if [ -z "$curr_remote" ]; then
        echo "0|0"
        return
    fi
    curr_merge_branch=$(git config branch.$curr_branch.merge | cut -d / -f 3)
    diff=$(git rev-list --left-right --count $curr_branch...$curr_remote/$curr_merge_branch 2>/dev/null)
    if [ -z "$diff" ]; then
        echo "N"
        return
    fi
    echo "$diff" | tr -s '\t' '|'
}

GIT_REVIEW_DIFF=$(git config diff.tool) : ${GIT_REVIEW_DIFF:="git diff"}
export GIT_REVIEW_DIFF

#
# Change directory relative to git root.
#
function git_cd()
{
    local dir="$1"
    if [ ! ${dir:0:1} = "/" ]; then
        dir="$(git rev-parse --git-dir)/../$dir"
    fi
    cd $dir
}
function _git_cd_completion()
{
    local cur="$(_get_cword)"

    if [ -z $cur ]; then
        cur="$(readlink -f $(git rev-parse --git-dir)/../$(_get_cword))/"
    fi

    _filedir
}
complete -F _git_cd_completion git_cd

#
# short stat
#
git_stat()
{
    verbose=0
    while getopts "vh" o; do
        case "$o" in
            v)   verbose=$((verbose+1)) ;;
            h)   echo "Usage: git_stat [-v] [-s]"; return 0 ;;
            \?)  echo "Invalid option: -$OPTARG" >&2; return 1 ;;
        esac
    done

    for i in $(git ls-files); do
        if [ ! -f $i ]; then
            continue;
        fi
        if [[ $verbose -gt 0 ]]; then
            echo "Processing $i" >&2
        fi

        git blame --line-porcelain $i | sed -n 's/^author //p'
    done | sort | uniq -c | sort -rn
}

git_avg()
{
    for i in $(git log --format=%h "$@"); do
        echo -n "$i " >& 2
        git log --format=%B $i -1 | tee -a >(head -1) >(tail -n+3) >/dev/null | wc
    done |& awk '\
{
    if (!$2) {
        print "Empty commit " $1;
    }
    lines += $2;
    words += $3;
    bytes += $4;
    ++commits;
}
END {
    printf("Commits: %.0f\n", commits);
    printf("Avg commit lines: %.1f\n", (lines / commits));
    printf("Avg commit words: %.0f\n", (words / commits));
    printf("Avg commit bytes: %.0f\n", (bytes / commits));
}
'
}

git_rebase_run()
{
    local buildSystem=ninja
    local buildDir="$PWD" # git rebase --exec will change it
    local upstream=origin/master
    local OPTIND OPTARG
    while getopts "b:u:B:" o; do
        case "$o" in
            b) buildSystem="$OPTARG"; shift 2;;
            B) buildDir="$OPTARG"; shift 2;;
            u) upstream="$OPTARG"; shift 2;;
            *) echo "$0 [ -b ] [ -u ] [ another-steps ]" >&2; return 1;;
        esac
    done

    local a=""
    [ ! -z "$@" ] && a="&& $@"
    git rebase -i --exec "cd $buildDir && $buildSystem $a" "$upstream"
}


# }}}

# Begining of ./bash.d/gpg.sh
# {{{

export GPG_TTY=$(tty)

# }}}

# Begining of ./bash.d/history.sh
# {{{

export HISTSIZE=100000
# don't put duplicate lines in the history. See bash(1) for more options
export HISTCONTROL="ignoreboth:erasedups"
export HISTIGNORE="&:ls:[bf]g:exit:history:cat:l:ll:ps:history *:pwd:free:w:jobs"

# all history in 1
shopt -s histappend
PROMPT_COMMAND+='history -a ;'
#many strings commands
shopt -s cmdhist

# }}}

# Begining of ./bash.d/identifiers.sh
# {{{

# Different identifiers

export EMAIL=$(git config user.email)
export EMAIL_ADDRESS="$EMAIL"

export NAME=$(git config user.name)
export CHANGE_LOG_NAME=$NAME


# }}}

# Begining of ./bash.d/less.sh
# {{{


# TODO: if we have this options here, maybe drop it from readline config?
export LESS=FRSX


# }}}

# Begining of ./bash.d/prevent-overwrite-in-redirect.sh
# {{{

# Not overwrite files after redirect with ">"
# For more infor see `help set`

set -C

# }}}

# Begining of ./bash.d/svn-aliases.sh
# {{{


function svn()
{
    case "$1" in
        grep)
            shift
            command grep --exclude='*.svn-*' --exclude='entries' "$@"
            ;;
        commit-revert)
            command svn merge -c -$2 ${3:-"."}
            ;;
        show)
            command svn diff -c $2
            ;;
        *)
            command svn "$@"
            ;;
    esac
}


# }}}

# Begining of ./bash.d/tmux.sh
# {{{


#
# TODO: maybe use rename pane?
#

settitle() {
	printf "\033k$1\033\\"
}

ssh() {
	# Non in tmux
	if [ -z "$TMUX" ]; then
		command ssh "$@"
		return
	fi

	# Non-interactive shell, will spawned on remote,
	# in this case settitle will just print headers
	# with command output, which is bad
	last="${@: -1}"
	nextToLast="${@: -2:1}"
	if [[ -n "$last" ]] && [[ ! "$last" =~ ^- ]] &&
		[[ -n "$nextToLast" ]] && [[ ! "$nextToLast" =~ ^- ]] && [[ ! "$nextToLast" =~ bash$ ]]; then
		command ssh "$@"
		return
	fi

	server="$last"
	settitle "$server"
	command ssh "$@"
	settitle "bash"
}

# $1 - session:windowNum
tmuxcatwindow()
{
	session_window="$1"
	start=${2:-"-1000000000"}
	[ -n "$session_window" ] || return
	(for i in $(tmux list-pane -t "$session_window" | awk -F: '{print $1}'); do tmux -q capture-pane -t "$session_window".$i -p -S "$start"; done)
}

tmuxcapture()
{
	local pattern=${1:-"tmux.%n.%w.%p"}
	local start=${2:-"-1000000000"}

	local n w p _ name
	while read w n _; do
		w=${w/:}
		for p in $(tmux list-pane -t "$w" | cut -d: -f1); do
			echo "Dumping window $n:$w:$p"

			name="$pattern"
			name=${name/\%n/$n}
			name=${name/\%w/$w}
			name=${name/\%p/$p}

			tmux -q capture-pane -t "${w}.${p}" -p -S "$start" >| "$name"
		done
	done < <(tmux list-windows)
}

# }}}

# Begining of ./bash.d/toolchain-aliases.sh
# {{{


# clean make
function cm()
{
    make $* > /dev/null
}

function c_const_generate()
{
    local headers=$(cat <<-EOL
        stdint.h limits.h \
        stdio.h stdlib.h unistd.h fcntl.h \
        sys/types.h sys/stat.h \
        sys/socket.h netinet/in.h arpa/inet.h
        errno.h
EOL
)
    for header in $@ $headers; do
        printf "#include <%s>\n" "$header"
    done
}
function c_const()
{
    const="$1"
    shift

    c_const_generate $@ | g++ -E -dM -xc++ - | fgrep $const | fgrep define
    c_const_generate $@ | g++ -E -xc++ - | fgrep $const | fgrep typedef
}

# }}}

# Begining of ./bash.d/user.sh
# {{{

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

# }}}

# Begining of ./bash.d/xargs.sh
# {{{

alias xargs='xargs -r'

# }}}