Skip to content

Instantly share code, notes, and snippets.

@ldong
Created April 29, 2018 04:04
Show Gist options
  • Save ldong/513dfbdbc80fb18cf12995ad6faa65ed to your computer and use it in GitHub Desktop.
Save ldong/513dfbdbc80fb18cf12995ad6faa65ed to your computer and use it in GitHub Desktop.
zshrc
# Path to your oh-my-zsh installation.
export ZSH=~/.oh-my-zsh
# Set name of the theme to load.
# Look in ~/.oh-my-zsh/themes/
# Optionally, if you set this to "random", it'll load a random theme each
# time that oh-my-zsh is loaded.
ZSH_THEME="robbyrussell"
# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"
# Uncomment the following line to use hyphen-insensitive completion. Case
# sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"
# Uncomment the following line to disable bi-weekly auto-update checks.
# DISABLE_AUTO_UPDATE="true"
# Uncomment the following line to change how often to auto-update (in days).
# export UPDATE_ZSH_DAYS=13
# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"
# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"
# Uncomment the following line to enable command auto-correction.
ENABLE_CORRECTION="true"
# Uncomment the following line to display red dots whilst waiting for completion.
# COMPLETION_WAITING_DOTS="true"
# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"
# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# HIST_STAMPS="mm/dd/yyyy"
# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder
# Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*)
# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(git fasd tmux zsh-syntax-highlighting git-aliases command-not-found)
# User configuration
# export PATH="/usr/bin:/bin:/usr/sbin:/sbin:$PATH"
# export MANPATH="/usr/local/man:$MANPATH"
source $ZSH/oh-my-zsh.sh
# You may need to manually set your language environment
# export LANG=en_US.UTF-8
# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
# export EDITOR='vim'
# else
# export EDITOR='mvim'
# fi
# Compilation flags
# export ARCHFLAGS="-arch x86_64"
# ssh
# export SSH_KEY_PATH="~/.ssh/dsa_id"
# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"
# =============================== Git Only =====================================
alias gpushPages='git push origin gh-pages'
alias gpush='git push origin master'
alias gpushHead='git push origin head'
alias gpull='git pull origin master'
alias gitname='git config --global user.name "Alan Dong"'
alias gitemail='git config --global user.email "[email protected]"'
alias gclean='git reset --hard && git clean -dfx'
alias gitcopy='git clone --depth 1 '
alias gs='git status'
alias gsf='git status --untracked-files'
alias gst='git stash'
alias gsp='git stash pop'
alias grm='git rebase master'
alias gpo='git pull origin'
alias gcob='git checkout -b'
alias gUpdateLocalBranches='git remote update origin --prune';
# git diff mybranch master -- myfile.cs
# git diff --name-only commit1 commit2
alias gitShowOrigin='git config --get remote.origin.url'
alias gitlog="git log --all --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative"
# Show files for specific commits
function gitShowFileChanges() {
# gitShowFileChanges f73630faa
git diff-tree --no-commit-id --name-only -r $@
# git diff-tree --no-commit-id --name-only -r $1
}
function gitDeleteRemoteBranch() {
git push origin --delete $@
}
function gitDeleteLocalBranch() {
git branch -D $@
}
# http://stackoverflow.com/a/26359665/2305243
function gitCommitAllExceptFiles() {
git add -u
git reset -- $@
}
function gitRebaseOursAndContinue() {
git checkout --ours $@
git add $@
git rebase --continue
}
function gitRebaseTheirsAndContinue() {
git checkout --theirs $@
git add $@
git rebase --continue
}
# =============================== Mac Only =====================================
# Set Solarized color
export CLICOLOR=1
export LSCOLORS=exfxcxdxbxegedabagacad
# kill docks
alias killdock='killall -KILL Dock'
# hide apps, i.e. sudo chflags hidden /Applications/Game\ Center.app
alias hideapp='sudo chflags hidden '
# edit host
alias edithosts='sudo vim /private/etc/hosts'
# pdf_join merged.pdf 1.pdf 2.pdf
function pdf_join {
join_py="/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/join.py"
read "output_file?Name of output file > "
"$join_py" -o $output_file $@ && open $output_file
}
# proxy list
# https://github.com/mrdulin/blog/issues/18
alias proxy='export all_proxy=socks5://127.0.0.1:1086'
alias unproxy='unset all_proxy'
# export http_proxy=http://127.0.0.1:1087;export https_proxy=http://127.0.0.1:1087;
# function proxy_off(){
# unset http_proxy
# unset https_proxy
# echo -e "Proxy is OFF"
# }
# function proxy_on() {
# export no_proxy="localhost,127.0.0.1,localaddress,.localdomain.com"
# export http_proxy="http://127.0.0.1:8118"
# export https_proxy=$http_proxy
# echo -e "Proxy is ON"
# }
# whatis $(ls /bin | gshuf -n 1)
alias cleanDNS='sudo discoveryutil udnsflushcaches'
alias cleanDNSResponder='sudo killall -HUP mDNSResponder'
alias resetSparkInspector="rm '~/Library/Application Support/.spark_settings'"
alias prettyjson='python -m json.tool'
# ============================= Linux Only =====================================
# Set Solarized color
# eval `dircolors ~/.dircolors`
# echo "Did you know that:"; whatis $(ls /bin | shuf -n 1)
# ============================ Theme ===========================================
# Set the colors to your liking
local vi_normal_marker="%{$fg[green]%}%BN%b%{$reset_color%}"
local vi_insert_marker="%{$fg[cyan]%}%BI%b%{$reset_color%}"
local vi_unknown_marker="%{$fg[red]%}%BU%b%{$reset_color%}"
local vi_mode="$vi_insert_marker"
vi_mode_indicator () {
case ${KEYMAP} in
(vicmd) echo $vi_normal_marker ;;
(main|viins) echo $vi_insert_marker ;;
(*) echo $vi_unknown_marker ;;
esac
}
# ZSH theme
ZSH_THEME_GIT_PROMPT_PREFIX="%{$fg[magenta]%}➦ %{$fg[red]%}"
ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%}"
ZSH_THEME_GIT_PROMPT_DIRTY=" %{$fg[red]%}✗%{$reset_color%}"
ZSH_THEME_GIT_PROMPT_ADDED="%{$fg[green]%}✚ "
ZSH_THEME_GIT_PROMPT_MODIFIED="%{$fg[yellow]%}⚑ "
ZSH_THEME_GIT_PROMPT_DELETED="%{$fg[red]%}✖ "
ZSH_THEME_GIT_PROMPT_RENAMED="%{$fg[blue]%}▴ "
ZSH_THEME_GIT_PROMPT_UNMERGED="%{$fg[cyan]%}§ "
ZSH_THEME_GIT_PROMPT_UNTRACKED="%{$fg[grey]%}◒ "
ZSH_THEME_GIT_PROMPT_CLEAN=" %{$fg[green]%}✔%{$reset_color%}"
local return_code="%(?..%{$fg[red]%}%? %{$reset_color%})"
# local PROMPT='%F{green}➜ %2c%F{blue} [%f'
local RPROMPT='$(git_prompt_info) %F{blue}] %F{gray}${vi_mode} %F{green}%D{%L:%M} %F{yellow}%D{%p}%f'
if [ "$USER" '==' "vagrant" ]; then
# ZSH_THEME_GIT_PROMPT_CLEAN="%{$fg[green]%}✔%{$reset_color%}"
PROMPT='%F{green}➜ %2c%F{blue} [%f '
else
# ZSH_THEME_GIT_PROMPT_CLEAN="%{$fg[green]%}%{$reset_color%}"
PROMPT='%F{green}%2c%F{blue} [%f '
fi
# ======================== Customized Scripts ==================================
# extract filename.zip
extract () {
if [ -f $1 ] ; then
case $1 in
*.tar.bz2) tar xjf $1 ;;
*.tar.gz) tar xzf $1 ;;
*.bz2) bunzip2 $1 ;;
*.rar) unrar e $1 ;;
*.gz) gunzip $1 ;;
*.tar) tar xf $1 ;;
*.tbz2) tar xjf $1 ;;
*.tgz) tar xzf $1 ;;
*.zip) unzip $1 ;;
*.Z) uncompress $1 ;;
*.7z) 7z x $1 ;;
*) echo "'$1'cannot be extracted via extract()" ;;
esac
else
echo "'$1' is not a valid file"
fi
}
# color man page
man() {
/usr/bin/man $* | \
col -b | \
vim -R -c 'set ft=man nomod nolist' -
}
# json pretty print
alias json="python -mjson.tool"
# alias c1="awk '{print \$1}'"
# alias c2="awk '{print \$2}'"
# alias c3="awk '{print \$3}'"
# alias c4="awk '{print \$4}'"
# alias c5="awk '{print \$5}'"
# alias c6="awk '{print \$6}'"
# alias c7="awk '{print \$7}'"
# alias c8="awk '{print \$8}'"
# alias c9="awk '{print \$9}'"
function c() { awk "{print \$$1}" }
# example: ls -l | c 4
if [[ -r /usr/local/bin/virtualenvwrapper.sh ]]; then
source /usr/local/bin/virtualenvwrapper.sh;
else
echo "WARNING: Can't find virtualenvwrapper.sh"
fi
## Alias
alias bbb="brew update && brew upgrade && brew cleanup"
# find the name with regex
findi() {
find . -iname $1;
}
findj() {
noglob find . -iname $1"*"
}
findk() {
noglob find . -iname "*"$1"*"
}
timedHistory(){
perl -lne 'm#: (\d+):\d+;(.+)# && printf "%s :: %s\n",scalar localtime $1,$2' $HISTFILE
}
# ========================= Percol Only =======================
# Python 2.7
# sudo apt-get install python-setuptools
# sudo easy_install pip
# sudo pip install percol
# =============================================================
alias show_process="ps aux | percol | awk '{ print $2 }'"
alias kill_process="ps aux | percol | awk '{ print $2 }' | xargs kill"
# Interactive pgrep / pkill
function ppgrep() {
if [[ $1 == "" ]]; then
PERCOL=percol
else
PERCOL="percol --query $1"
fi
ps aux | eval $PERCOL | awk '{print $2}'
}
function ppkill() {
if [[ $1 =~ "^-" ]]; then
QUERY="" # options only
else
QUERY=$1 # with a query
[[ $# > 0 ]] && shift
fi
ppgrep $QUERY | xargs kill $*
}
# zsh history search
function exists { which $1 &> /dev/null }
if exists percol; then
function percol_select_history() {
local tac
exists gtac && tac="gtac" || { exists tac && tac="tac" || { tac="tail -r" } }
BUFFER=$(fc -l -n 1 | eval $tac | percol --query "$LBUFFER")
CURSOR=$#BUFFER # move cursor
zle -R -c # refresh
}
zle -N percol_select_history
bindkey '^R' percol_select_history
bindkey -M vicmd '^R' percol_select_history
fi
# ZLE key binding
# http://www.cs.elte.hu/zsh-manual/zsh_14.html
# http://zsh.sourceforge.net/Guide/zshguide04.html
bindkey -v
bindkey -M viins 'JJ' vi-cmd-mode
bindkey -M vicmd '?' history-incremental-search-backward
bindkey -M vicmd '??' history-incremental-search-forward
bindkey -M vicmd 'H' percol_select_history
bindkey '^K' kill-line
bindkey '^A' beginning-of-line
bindkey '^E' end-of-line
# do history expansion on space
bindkey " " magic-space
# Search for history key bindings
# ctrl+v UP
#bindkey "^[OA" up-line-or-history
# ctrl+v DOWN
#bindkey "^[OB" down-line-or-history
# bindkey "^[[A" up-line-or-history
# bindkey "^[[B" down-line-or-history
# bindkey "^R" history-incremental-search-backward
# Tetris
# autoload -U tetris
# zle -N tetris
# bindkey ^T tetris
# Seach file in vim CtrlP
ctrlp() {
</dev/tty vim -c 'Unite file_rec/async'
}
zle -N ctrlp
bindkey "^p" ctrlp
# Edit command in vim ctrl-e
autoload edit-command-line
zle -N edit-command-line
bindkey '^e' edit-command-line
# works without vim mode
#autoload -U up-line-or-beginning-search
#autoload -U down-line-or-beginning-search
#zle -N up-line-or-beginning-search
#zle -N down-line-or-beginning-search
#bindkey "^[[A" up-line-or-beginning-search # Up
#bindkey "^[[B" down-line-or-beginning-search # Down
# You may already have those in your .zshrc somewhere
# autoload -U promptinit && promptinit
# autoload -U colors && colors
# setopt prompt_subst
#
# Reset mode-marker and prompt whenever the keymap changes
function zle-line-init zle-keymap-select {
vi_mode="$(vi_mode_indicator)"
zle reset-prompt
}
zle -N zle-line-init
zle -N zle-keymap-select
# Multiline-prompts don't quite work with reset-prompt; we work around this by
# printing the first line(s) via a precmd which is executed before the prompt
# is printed. The following can be integrated into PROMPT for single-line
# prompts.
# local user_host='%B%n%b@%m'
# local current_dir='%~'
# precmd () print -rP"${user_host} ${current_dir}"
# completer widget that sets a flag for the duration of
# the completion so the SIGINT handler knows whether completion
# is active. It would be better if we could check some internal
# zsh parameter to determine if completion is running, but as
# far as I'm aware that isn't possible.
function interruptible-expand-or-complete {
COMPLETION_ACTIVE=1
# Bonus feature: automatically interrupt completion
# after a three second timeout.
# (sleep 3; kill -INT $$) &!
zle expand-or-complete
COMPLETION_ACTIVE=0
}
# Bind our completer widget to tab.
zle -N interruptible-expand-or-complete
bindkey '^I' interruptible-expand-or-complete
# Interrupt only if completion is active.
function TRAPINT {
if [[ $COMPLETION_ACTIVE == 1 ]]; then
COMPLETION_ACTIVE=0
zle -M "Completion canceled."
# Returning non-zero tells zsh to handle SIGINT,
# which will interrupt the completion function.
return 1
else
# Returning zero tells zsh that we handled SIGINT;
# don't interrupt whatever is currently running.
return 0
fi
}
## FZF
# brew install fzf
function findAll() {
# find * -type f | fzf -m > selected
find * -type f | fzf -m
}
zle -N findAll
bindkey '^F' findAll
bindkey -M vicmd '^F' findAll
# AG silver search
function agc() {
ag --color --group $@ | cut -c -100
}
function agi() {
ag --ignore-case $@
}
function agSearchExtensionWithKeyword {
# ag -G '\.(hbs|handlebars|js)$' keyword
ag -G "\.($1)" $2
}
# AG
# ag -G '\.(filetypes)$' keyword
# ag -G '\.(hbs|html)$' keyword
# Find out my ip, http://ifconfig.me
alias wanip='dig +short myip.opendns.com @resolver1.opendns.com'
alias lanip="ifconfig | sed -n 's/.*inet addr:\([0-9.]\+\)\s.*/\1/p'"
alias whatsmyip="curl http://httpbin.org/ip"
alias myip='curl ifconfig.co'
alias myip2='curl cip.cc'
alias myip3='curl ip.gs'
alias myip4='curl http://checkip.amazonaws.com'
alias myip5='curl ip.cn'
# Kill process of retaining port
#sudo lsof -i :9000
#sudo kill -9 61342
# Nodejs
alias npmls="npm ls --depth=0 "$@" 2>/dev/null"
# display the colors
#alias colors='bash ~/.dotfiles/color.sh'
#alias color256='python ~/.dotfiles/checkColor.py'
# remove .DS_Store file
alias rmDSStore='find . -name ".DS_Store" -depth -exec rm {} \;'
# remove vim cache files
alias rmswp='find . -name \*.swp -type f -delete'
# remove python pyc files
alias rmpyc='find . -name \*.pyc -type f -delete'
# echo "text" | rot13
alias rot13="tr '[A-Za-z]' '[N-ZA-Mn-za-m]'"
# Count files
alias countFiles='ls -1 | wc -l'
# download uses aria2
alias download='aria2c -s 10 '
alias downloadDirectory='wget -r -np '
# Rails
alias railsUP='rails s -b 0.0.0.0'
# local http servers use python
alias httphere='python -m SimpleHTTPServer 8080'
alias httphere3='python3 -m http.server 8080'
alias httphereWithUpload='python ~/.dotfiles/SimpleHTTPServerWithUpload.py 8080'
if [ "$(uname -s)" '==' "Darwin" ]; then
alias ls='ls -F -G'
else
alias ls='ls -F --color=auto'
fi
alias vi='vim'
alias javac="javac -J-Dfile.encoding=utf8"
alias grep="grep --color=auto"
alias -s html=vi # open files in vim
alias -s rb=vi
alias -s py=vi
alias -s js=vi
alias -s c=vi
alias -s java=vi
alias -s txt=vi
alias -s gz='tar -xzvf'
alias -s tgz='tar -xzvf'
alias -s zip='unzip'
alias -s bz2='tar -xjvf'
alias cp='cp -i'
alias mv='mv -i'
alias rm='rm -i'
alias rm='rmtrash'
alias rmdir='rmdirtrash'
alias sudo='sudo '
alias grep='grep --color=auto'
## Source utils
# source ~/.utils/gitjump.sh
function gi() { curl -L -s https://www.gitignore.io/api/$@ ;}
if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi
# curl -L https://iterm2.com/misc/install_shell_integration.sh | bash
# This will set your window title, http://stackoverflow.com/a/38484310/2305243
export PROMPT_COMMAND='echo -ne "\033]0;${PWD##*/}\007"'
source ~/.iterm2_shell_integration.`basename $SHELL`
# This creates the var currentDir to use later on, \(user.currentDir) as badge
function iterm2_print_user_vars() {
iterm2_set_user_var currentDir $(echo ${PWD##*/})
}
export NVM_DIR="$HOME/.nvm"
# [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
#export NVM_DIR=~/.nvm
#source $(brew --prefix nvm)/nvm.sh
. "/usr/local/opt/nvm/nvm.sh"
function youtube-dl-best() {
youtube-dl -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best' $@
}
# export JAVA_HOME="$(/usr/libexec/java_home -v 1.9)"
export JAVA_HOME="$(/usr/libexec/java_home -v 9)"
# /Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home
alias enable3rdPartyApps="sudo spctl --master-disable"
alias jsonifyFile="python -mjson.tool "
# lbys = ls by size
alias lbys='ls -alhS'
# lbyt = ls by time
alias lbyt='ls -alht'
# cl = copy last output
alias cl='bash -c "$(fc -ln -1)" | pbcopy'
# copy last commandline
alias last='fc -ln -1 | pbcopy'
# Save paste to file
alias new='pbpaste | cat >'
alias save='pbpaste | cat >'
alias today='date +"%A, %B %-d, %Y"'
alias bzip2='bzip2 -v'
alias j=jobs
# cd
alias cd..="cd .."
#Use human-readable filesizes
alias du="du -h"
alias df="df -h"
#Aliases for improved directory listings
#The --color=tty option shows items in different colors according to their type.
#For example, directories are blue, executable files are green, symlinks are cyan, etc.
#The -F option appends a symbol after entries to indicate their types.
#You might not like both options at the same time.
#alias ls='ls -F --color=tty' #regular ls
#alias l.='ls -dF .[a-zA-Z0-9]* --color=tty' #only show dotfiles
#alias ll='ls -lhF --color=tty' #long listing
alias lsl='ls -hal'
alias lsd='ls -d */'
#Automatically do an ls after each cd
#cd() {
# if [ -n "$1" ]; then
# builtin cd "$@" && ls
# else
# builtin cd ~ && ls
# fi
#}
export SSH_AUTH_SOCK=$HOME/.yubiagent/sock
export PATH="/usr/local/opt/python/libexec/bin:$PATH"
. $HOME/.asdf/asdf.sh
. $HOME/.asdf/completions/asdf.bash
@ldong
Copy link
Author

ldong commented Sep 17, 2018

Updated: 9/16/2018

# Path to your oh-my-zsh installation.
export ZSH=~/.oh-my-zsh

# Set name of the theme to load.
# Look in ~/.oh-my-zsh/themes/
# Optionally, if you set this to "random", it'll load a random theme each
# time that oh-my-zsh is loaded.
ZSH_THEME="robbyrussell"

# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"

# Uncomment the following line to use hyphen-insensitive completion. Case
# sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"

# Uncomment the following line to disable bi-weekly auto-update checks.
# DISABLE_AUTO_UPDATE="true"

# Uncomment the following line to change how often to auto-update (in days).
# export UPDATE_ZSH_DAYS=13

# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"

# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"

# Uncomment the following line to enable command auto-correction.
ENABLE_CORRECTION="true"

# Uncomment the following line to display red dots whilst waiting for completion.
# COMPLETION_WAITING_DOTS="true"

# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"

# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# HIST_STAMPS="mm/dd/yyyy"

# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder

# Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*)
# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(git fasd tmux zsh-syntax-highlighting git-aliases command-not-found)

# User configuration

# export PATH="/usr/bin:/bin:/usr/sbin:/sbin:$PATH"
# export MANPATH="/usr/local/man:$MANPATH"

source $ZSH/oh-my-zsh.sh

# You may need to manually set your language environment
# export LANG=en_US.UTF-8

# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
#   export EDITOR='vim'
# else
#   export EDITOR='mvim'
# fi

# Compilation flags
# export ARCHFLAGS="-arch x86_64"

# ssh
# export SSH_KEY_PATH="~/.ssh/dsa_id"

# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"


# =============================== Git Only =====================================
alias gpushPages='git push origin gh-pages'
alias gpush='git push origin master'
alias gpull='git pull origin master'
alias gpushHead='git push origin head'
alias gitname='git config --global user.name "Alan Dong"'
alias gitemail='git config --global user.email "[email protected]"'
alias gclean='git reset --hard && git clean -dfx'
alias gitcopy='git clone --depth 1 '
alias gs='git status'
alias gsf='git status --untracked-files'
alias gst='git stash'
alias gsp='git stash pop'
alias grm='git rebase master'
alias gpo='git pull origin'
alias gcob='git checkout -b'
alias gUpdateLocalBranches='git remote update origin --prune';
# git diff mybranch master -- myfile.cs
# git diff --name-only commit1 commit2
alias gitShowOrigin='git config --get remote.origin.url'
alias gitlog="git log --all --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative"
# Show files for specific commits
function gitShowFileChanges() {
  # gitShowFileChanges f73630faa
  git diff-tree --no-commit-id --name-only -r $@
  # git diff-tree --no-commit-id --name-only -r $1
}
# https://stackoverflow.com/a/24186641/2305243
alias gitRebaseNumberOfCommits='git rev-list master.. --count'
#git rebase -i HEAD~$(gitRebaseNumberOfCommits)

function gitDeleteRemoteBranch() {
  git push origin --delete $@
}

function gitDeleteLocalBranch() {
  git branch -D $@
}

# git config --global alias.clean-branches "!git branch | grep -v master | xargs git branch -D"
alias gitDeleteAllLocalBranchesButMaster='git branch | grep -v "master" | xargs git branch -D'


# http://stackoverflow.com/a/26359665/2305243
function gitCommitAllExceptFiles() {
  git add -u
  git reset -- $@
}
function gitRebaseOursAndContinue() {
  git checkout --ours $@
  git add $@
  git rebase --continue
}
function gitRebaseTheirsAndContinue() {
  git checkout --theirs $@
  git add $@
  git rebase --continue
}

# =============================== Mac Only =====================================
# Set Solarized color
export CLICOLOR=1
export LSCOLORS=exfxcxdxbxegedabagacad

# show full path in finder
# defaults write com.apple.finder _FXShowPosixPathInTitle -bool YES
# show hidden files in finder
# defaults write com.apple.finder AppleShowAllFiles -boolean true ; killall Finder
# hide hidden files in finder
# defaults write com.apple.finder AppleShowAllFiles -boolean false ; killall Finder

# kill docks
alias killdock='killall -KILL Dock'

# hide apps, i.e. sudo chflags hidden /Applications/Game\ Center.app
alias hideapp='sudo chflags hidden '

# edit host
alias edithosts='sudo vim /private/etc/hosts'

# pdf_join merged.pdf 1.pdf 2.pdf
function pdf_join {
  join_py="/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/join.py"
  read "output_file?Name of output file > "
  "$join_py" -o $output_file $@ && open $output_file
}

# proxy list
# https://github.com/mrdulin/blog/issues/18
alias proxy='export all_proxy=socks5://127.0.0.1:1086'
alias unproxy='unset all_proxy'
# export http_proxy=http://127.0.0.1:1087;export https_proxy=http://127.0.0.1:1087;
# function proxy_off(){
#     unset http_proxy
#     unset https_proxy
#     echo -e "Proxy is OFF"
# }
# function proxy_on() {
#     export no_proxy="localhost,127.0.0.1,localaddress,.localdomain.com"
#     export http_proxy="http://127.0.0.1:8118"
#     export https_proxy=$http_proxy
#     echo -e "Proxy is ON"
# }


# whatis $(ls /bin | gshuf -n 1)
alias enable3rdPartyApps="sudo spctl --master-disable"
alias cleanDNS='sudo discoveryutil udnsflushcaches'
alias cleanDNSResponder='sudo killall -HUP mDNSResponder'
alias resetSparkInspector="rm '~/Library/Application Support/.spark_settings'"
alias prettyjson='python -m json.tool'

# ============================= Linux Only =====================================
# Set Solarized color
# eval `dircolors ~/.dircolors`

# echo "Did you know that:"; whatis $(ls /bin | shuf -n 1)
# ============================ Theme ===========================================
# Set the colors to your liking
local vi_normal_marker="%{$fg[green]%}%BN%b%{$reset_color%}"
local vi_insert_marker="%{$fg[cyan]%}%BI%b%{$reset_color%}"
local vi_unknown_marker="%{$fg[red]%}%BU%b%{$reset_color%}"
local vi_mode="$vi_insert_marker"
vi_mode_indicator () {
  case ${KEYMAP} in
    (vicmd)      echo $vi_normal_marker ;;
    (main|viins) echo $vi_insert_marker ;;
    (*)          echo $vi_unknown_marker ;;
  esac
}

# ZSH theme
ZSH_THEME_GIT_PROMPT_PREFIX="%{$fg[magenta]%}➦ %{$fg[red]%}"
ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%}"
ZSH_THEME_GIT_PROMPT_DIRTY=" %{$fg[red]%}✗%{$reset_color%}"
ZSH_THEME_GIT_PROMPT_ADDED="%{$fg[green]%}✚ "
ZSH_THEME_GIT_PROMPT_MODIFIED="%{$fg[yellow]%}⚑ "
ZSH_THEME_GIT_PROMPT_DELETED="%{$fg[red]%}✖ "
ZSH_THEME_GIT_PROMPT_RENAMED="%{$fg[blue]%}▴ "
ZSH_THEME_GIT_PROMPT_UNMERGED="%{$fg[cyan]%}§ "
ZSH_THEME_GIT_PROMPT_UNTRACKED="%{$fg[grey]%}◒ "
ZSH_THEME_GIT_PROMPT_CLEAN=" %{$fg[green]%}✔%{$reset_color%}"

local return_code="%(?..%{$fg[red]%}%? %{$reset_color%})"
# local PROMPT='%F{green}➜ %2c%F{blue} [%f'
local RPROMPT='$(git_prompt_info) %F{blue}] %F{gray}${vi_mode} %F{green}%D{%L:%M} %F{yellow}%D{%p}%f'

if [ "$USER" '==' "vagrant" ]; then
  # ZSH_THEME_GIT_PROMPT_CLEAN="%{$fg[green]%}✔%{$reset_color%}"
  PROMPT='%F{green}➜ %2c%F{blue} [%f '
else
  # ZSH_THEME_GIT_PROMPT_CLEAN="%{$fg[green]%}%{$reset_color%}"
  PROMPT='%F{green}%2c%F{blue} [%f '
fi


# ======================== Customized Scripts ==================================
# extract filename.zip
extract () {
    if [ -f $1 ] ; then
      case $1 in
        *.tar.bz2)   tar xjf $1     ;;
        *.tar.gz)    tar xzf $1     ;;
        *.bz2)       bunzip2 $1     ;;
        *.rar)       unrar e $1     ;;
        *.gz)        gunzip $1      ;;
        *.tar)       tar xf $1      ;;
        *.tbz2)      tar xjf $1     ;;
        *.tgz)       tar xzf $1     ;;
        *.zip)       unzip $1       ;;
        *.Z)         uncompress $1  ;;
        *.7z)        7z x $1        ;;
        *)     echo "'$1'cannot be extracted via extract()" ;;
         esac
     else
         echo "'$1' is not a valid file"
     fi
}

# color man page
man() {
  /usr/bin/man $* | \
    col -b | \
    vim -R -c 'set ft=man nomod nolist' -
}

# json pretty print
alias json="python -mjson.tool"

# VIRTUALENVWRAPPER_PYTHON=/usr/bin/python
# VIRTUALENVWRAPPER_PYTHON=/usr/local/opt/python/libexec/bin
# VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python
# alias c1="awk '{print \$1}'"
# alias c2="awk '{print \$2}'"
# alias c3="awk '{print \$3}'"
# alias c4="awk '{print \$4}'"
# alias c5="awk '{print \$5}'"
# alias c6="awk '{print \$6}'"
# alias c7="awk '{print \$7}'"
# alias c8="awk '{print \$8}'"
# alias c9="awk '{print \$9}'"
function c() { awk "{print \$$1}" }
# example: ls -l | c 4

# export PATH="/usr/local/opt/python/libexec/bin:$PATH"
# VIRTUALENVWRAPPER_PYTHON=/usr/bin/python
# VIRTUALENVWRAPPER_PYTHON=/usr/local/opt/python/libexec/bin
# VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python

if [[ -r /usr/local/bin/virtualenvwrapper.sh ]]; then
  source /usr/local/bin/virtualenvwrapper.sh;
else
  echo "WARNING: Can't find virtualenvwrapper.sh"
fi

## Alias
alias bbb="brew update && brew upgrade && brew cleanup"

# find the name with regex
findi() {
  find . -iname $1;
}

findj() {
  noglob find . -iname $1"*"
}

findk() {
  noglob find . -iname "*"$1"*"
}

timedHistory(){
  perl -lne 'm#: (\d+):\d+;(.+)# && printf "%s :: %s\n",scalar localtime $1,$2' $HISTFILE
}

# ========================= Percol Only =======================
# Python 2.7
# sudo apt-get install python-setuptools
# sudo easy_install pip
# sudo pip install percol
# =============================================================
alias show_process="ps aux | percol | awk '{ print $2 }'"
alias kill_process="ps aux | percol | awk '{ print $2 }' | xargs kill"

# Interactive pgrep / pkill
function ppgrep() {
    if [[ $1 == "" ]]; then
        PERCOL=percol
    else
        PERCOL="percol --query $1"
    fi
    ps aux | eval $PERCOL | awk '{print $2}'
}

function ppkill() {
    if [[ $1 =~ "^-" ]]; then
        QUERY=""            # options only
    else
        QUERY=$1            # with a query
        [[ $# > 0 ]] && shift
    fi
    ppgrep $QUERY | xargs kill $*
}
# zsh history search
function exists { which $1 &> /dev/null }

if exists percol; then
    function percol_select_history() {
        local tac
        exists gtac && tac="gtac" || { exists tac && tac="tac" || { tac="tail -r" } }
        BUFFER=$(fc -l -n 1 | eval $tac | percol --query "$LBUFFER")
        CURSOR=$#BUFFER         # move cursor
        zle -R -c               # refresh
    }

    zle -N percol_select_history
    bindkey '^R' percol_select_history
    bindkey -M vicmd '^R' percol_select_history
    bindkey -M vicmd 'H' percol_select_history
fi


# ZLE key binding
# http://www.cs.elte.hu/zsh-manual/zsh_14.html
# http://zsh.sourceforge.net/Guide/zshguide04.html
bindkey -v
bindkey -M viins 'JJ' vi-cmd-mode
bindkey -M vicmd '?' history-incremental-search-backward
bindkey -M vicmd '/' history-incremental-search-forward
bindkey -M vicmd '??' history-incremental-search-forward
bindkey -M vicmd 'H' percol_select_history

# https://www.johnhawthorn.com/2012/09/vi-escape-delays/
# Make Vi mode transitions faster (KEYTIMEOUT is in hundredths of a second)
# default KEYTIMEOUT=400
export KEYTIMEOUT=80

# http://stratus3d.com/blog/2017/10/26/better-vi-mode-in-zshell/
# No VIM Profile
# export EDITOR='vim -u NONE'
bindkey -M vicmd v edit-command-line
bindkey -M vicmd "^V" edit-command-line
bindkey -M viins 'qq' send-break

# Beginning search with arrow keys
# bindkey "^[OA" up-line-or-beginning-search
# bindkey "^[OB" down-line-or-beginning-search
# bindkey -M vicmd "k" up-line-or-beginning-search
# bindkey -M vicmd "j" down-line-or-beginning-search

bindkey '^K' kill-line
bindkey '^A' beginning-of-line
bindkey '^E' end-of-line



# do history expansion on space
bindkey " " magic-space

# Search for history key bindings
# ctrl+v UP
#bindkey "^[OA" up-line-or-history
# ctrl+v DOWN
#bindkey "^[OB" down-line-or-history
# bindkey "^[[A" up-line-or-history
# bindkey "^[[B" down-line-or-history
# bindkey "^R" history-incremental-search-backward

# Tetris
# autoload -U tetris
# zle -N tetris
# bindkey ^T tetris

# Seach file in vim CtrlP
ctrlp() {
  </dev/tty vim -c 'Unite file_rec/async'
}
zle -N ctrlp
bindkey "^p" ctrlp


# Edit command in vim ctrl-e
autoload edit-command-line
zle -N edit-command-line
bindkey '^e' edit-command-line

# works without vim mode
#autoload -U up-line-or-beginning-search
#autoload -U down-line-or-beginning-search
#zle -N up-line-or-beginning-search
#zle -N down-line-or-beginning-search
#bindkey "^[[A" up-line-or-beginning-search # Up
#bindkey "^[[B" down-line-or-beginning-search # Down


# You may already have those in your .zshrc somewhere
# autoload -U promptinit && promptinit
# autoload -U colors     && colors
# setopt prompt_subst
#
# Reset mode-marker and prompt whenever the keymap changes
function zle-line-init zle-keymap-select {
  vi_mode="$(vi_mode_indicator)"
  zle reset-prompt
}
zle -N zle-line-init
zle -N zle-keymap-select

# Multiline-prompts don't quite work with reset-prompt; we work around this by
# printing the first line(s) via a precmd which is executed before the prompt
# is printed.  The following can be integrated into PROMPT for single-line
# prompts.

# local user_host='%B%n%b@%m'
# local current_dir='%~'
# precmd () print -rP"${user_host} ${current_dir}"



# completer widget that sets a flag for the duration of
# the completion so the SIGINT handler knows whether completion
# is active. It would be better if we could check some internal
# zsh parameter to determine if completion is running, but as
# far as I'm aware that isn't possible.
function interruptible-expand-or-complete {
    COMPLETION_ACTIVE=1

    # Bonus feature: automatically interrupt completion
    # after a three second timeout.
    # (sleep 3; kill -INT $$) &!

    zle expand-or-complete

    COMPLETION_ACTIVE=0
}

# Bind our completer widget to tab.
zle -N interruptible-expand-or-complete
bindkey '^I' interruptible-expand-or-complete

# Interrupt only if completion is active.
function TRAPINT {
    if [[ $COMPLETION_ACTIVE == 1 ]]; then
        COMPLETION_ACTIVE=0
        zle -M "Completion canceled."

        # Returning non-zero tells zsh to handle SIGINT,
        # which will interrupt the completion function.
        return 1
    else
        # Returning zero tells zsh that we handled SIGINT;
        # don't interrupt whatever is currently running.
        return 0
    fi
}


# https://www.gnu.org/software/bash/manual/html_node/Miscellaneous-Commands.html
# https://gist.github.com/srustamo/93b9b9fc16bde207d80b
copy() {
  if [[ $1 =~ ^-?[hH] ]]; then

    echo "Intelligently copies command results, text file, or raw text to"
    echo "OS X clipboard"
    echo
    echo "Usage: copy [command or text]"
    echo "  or pipe a command: [command] | copy"
    return
  fi

  local output
  local res=false
  local tmpfile="${TMPDIR}/copy.$RANDOM.txt"
  local msg=""

  if [[ $# == 0 ]]; then
    output=$(cat)
    msg="Input copied to clipboard"
    res=true
  else
    local cmd=""
    for arg in $@; do
      cmd+="\"$(echo -en $arg|sed -E 's/"/\\"/g')\" "
    done
    output=$(eval "$cmd" 2> /dev/null)
    if [[ $? == 0 ]]; then
      msg="Results of command are in the clipboard"
      res=true
    else
      if [[ -f $1 ]]; then
        output=""
        for arg in $@; do
          if [[ -f $arg ]]; then
            type=`file "$arg"|grep -c text`
            if [ $type -gt 0 ]; then
              output+=$(cat $arg)
              msg+="Contents of $arg are in the clipboard.\n"
              res=true
            else
              msg+="File \"$arg\" is not plain text.\n"
            fi
          fi
        done
      else
        output=$@
        msg="Text copied to clipboard"
        res=true
      fi
    fi
  fi

  $res && echo -ne "$output" | pbcopy -Prefer txt
  echo -e "$msg"
}

## FZF
# brew install fzf
function findAll() {
  # find * -type f | fzf -m > selected
  find * -type f | fzf -m
}

zle -N findAll
bindkey '^F' findAll
bindkey -M vicmd '^F' findAll

# AG silver search
function agc() {
  ag --color --group $@ | cut -c -100
}

function agi() {
  ag --ignore-case $@
}

function agSearchExtensionWithKeyword {
  # ag -G '\.(hbs|handlebars|js)$' keyword
  ag -G "\.($1)" $2
}

function agShowNumberOfFilesHasExactKeyword {
  ag -w $@ -c | wc -l
}
# AG
# ag -G '\.(filetypes)$' keyword
# ag -G '\.(hbs|html)$' keyword

# Create a new directory and enter it
function mkd() {
    mkdir -p "$@" && cd "$_";
}

# Create a .tar.gz archive, using `zopfli`, `pigz` or `gzip` for compression
function targz() {
    local tmpFile="${@%/}.tar";
    tar -cvf "${tmpFile}" --exclude=".DS_Store" "${@}" || return 1;

    size=$(
        stat -f"%z" "${tmpFile}" 2> /dev/null; # macOS `stat`
        stat -c"%s" "${tmpFile}" 2> /dev/null;  # GNU `stat`
    );

    local cmd="";
    if (( size < 52428800 )) && hash zopfli 2> /dev/null; then
        # the .tar file is smaller than 50 MB and Zopfli is available; use it
        cmd="zopfli";
    else
        if hash pigz 2> /dev/null; then
            cmd="pigz";
        else
            cmd="gzip";
        fi;
    fi;

    echo "Compressing .tar ($((size / 1000)) kB) using \`${cmd}\`…";
    "${cmd}" -v "${tmpFile}" || return 1;
    [ -f "${tmpFile}" ] && rm "${tmpFile}";

    zippedSize=$(
        stat -f"%z" "${tmpFile}.gz" 2> /dev/null; # macOS `stat`
        stat -c"%s" "${tmpFile}.gz" 2> /dev/null; # GNU `stat`
    );

    echo "${tmpFile}.gz ($((zippedSize / 1000)) kB) created successfully.";
}


# Start an HTTP server from a directory, optionally specifying the port
function server() {
    local port="${1:-8000}";
    # sleep 1 && open "http://localhost:${port}/" &
    # Set the default Content-Type to `text/plain` instead of `application/octet-stream`
    # And serve everything as UTF-8 (although not technically correct, this doesn’t break anything for binary files)
    python -c $'import SimpleHTTPServer;\nmap = SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map;\nmap[""] = "text/plain";\nfor key, value in map.items():\n\tmap[key] = value + ";charset=UTF-8";\nSimpleHTTPServer.test();' "$port";
}

# Syntax-highlight JSON strings or files,similar to json format
# Usage: `json '{"foo":42}'` or `echo '{"foo":42}' | json`
function json() {
    if [ -t 0 ]; then # argument
        python -mjson.tool <<< "$*" | pygmentize -l javascript;
    else # pipe
        python -mjson.tool | pygmentize -l javascript;
    fi;
}

# `v` with no arguments opens the current directory in Vim, otherwise opens the
# given location
function v() {
    if [ $# -eq 0 ]; then
        vim .;
    else
        vim "$@";
    fi;
}

# Find out my ip, http://ifconfig.me
alias wanip='dig +short myip.opendns.com @resolver1.opendns.com'
alias lanip="ifconfig | sed -n 's/.*inet addr:\([0-9.]\+\)\s.*/\1/p'"
alias whatsmyip="curl http://httpbin.org/ip"
alias myip='curl ifconfig.co'
alias myip2='curl cip.cc'
alias myip3='curl ip.gs'
alias myip4='curl http://checkip.amazonaws.com'
alias myip5='curl ip.cn'

# Kill process of retaining port
#sudo lsof -i :9000
#sudo kill -9 61342

# Nodejs
alias npmls="npm ls --depth=0 "$@" 2>/dev/null"

# display the colors
#alias colors='bash ~/.dotfiles/color.sh'
#alias color256='python ~/.dotfiles/checkColor.py'

# remove .DS_Store file
alias rmDSStore='find . -name ".DS_Store" -depth -exec rm {} \;'
alias rmDSStoreLocal='find . -name '.DS_Store' -type f -delete'
# remove vim cache files
alias rmswp='find . -name \*.swp -type f -delete'

# remove python pyc files
alias rmpyc='find . -name \*.pyc -type f -delete'

# echo "text" | rot13
alias rot13="tr '[A-Za-z]' '[N-ZA-Mn-za-m]'"

# Count files
alias countFiles='ls -1 | wc -l'

# download uses aria2
alias download='aria2c -s 10 '
alias downloadDirectory='wget -r -np '

# Rails
alias railsUP='rails s -b 0.0.0.0'

# local http servers use python
alias httphere='python -m SimpleHTTPServer 8080'
alias httphere3='python3 -m http.server 8080'
alias httphereWithUpload='python ~/.dotfiles/SimpleHTTPServerWithUpload.py 8080'

if [ "$(uname -s)" '==' "Darwin" ]; then
  alias ls='ls -F -G'
else
  alias ls='ls -F --color=auto'
fi

alias vi='vim'
alias javac="javac -J-Dfile.encoding=utf8"
alias grep="grep --color=auto"
alias -s html=vi  # open files in vim
alias -s rb=vi
alias -s py=vi
alias -s js=vi
alias -s c=vi
alias -s java=vi
alias -s txt=vi
alias -s gz='tar -xzvf'
alias -s tgz='tar -xzvf'
alias -s zip='unzip'
alias -s bz2='tar -xjvf'

alias cp='cp -i'
alias mv='mv -i'
alias rm='rm -i'
alias rm='rmtrash'
alias rmdir='rmdirtrash'
alias sudo='sudo '
alias grep='grep --color=auto'

## Source utils
# source ~/.utils/gitjump.sh

function gi() { curl -L -s https://www.gitignore.io/api/$@ ;}
if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi

# curl -L https://iterm2.com/misc/install_shell_integration.sh | bash
# This will set your window title, http://stackoverflow.com/a/38484310/2305243
export PROMPT_COMMAND='echo -ne "\033]0;${PWD##*/}\007"'

source ~/.iterm2_shell_integration.`basename $SHELL`

# This creates the var currentDir to use later on, \(user.currentDir) as badge
function iterm2_print_user_vars() {
  iterm2_set_user_var currentDir $(echo ${PWD##*/})
}

export NVM_DIR="$HOME/.nvm"
# [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
export NVM_DIR=~/.nvm
source $(brew --prefix nvm)/nvm.sh
# . "/usr/local/opt/nvm/nvm.sh"

function phone() {
 open "tel://$*"
}




function youtube-dl-best() {
  youtube-dl -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best' $@
}

# export JAVA_HOME="$(/usr/libexec/java_home -v 1.9)"
# export JAVA_HOME="$(/usr/libexec/java_home -v 9)"
# export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"
# /Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home

# echo $JAVA_HOME
# /Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home
alias enable3rdPartyApps="sudo spctl --master-disable"

alias jsonifyFile="python -mjson.tool "

# lbys = ls by size
alias lbys='ls -alhS'

# lbyt = ls by time
alias lbyt='ls -alht'

# cl = copy last output
alias cl='bash -c "$(fc -ln -1)" | pbcopy'

# copy last commandline
alias last='fc -ln -1 | pbcopy'

# Save paste to file
alias new='pbpaste | cat >'
alias save='pbpaste | cat >'

alias today='date +"%A, %B %-d, %Y"'
alias bzip2='bzip2 -v'
alias j=jobs
# cd
alias cd..="cd .."

#Use human-readable filesizes
alias du="du -h"
alias df="df -h"

#Aliases for improved directory listings
#The --color=tty option shows items in different colors according to their type.
#For example, directories are blue, executable files are green, symlinks are cyan, etc.
#The -F option appends a symbol after entries to indicate their types.
#You might not like both options at the same time.
#alias ls='ls -F --color=tty' #regular ls
#alias l.='ls -dF .[a-zA-Z0-9]* --color=tty' #only show dotfiles
#alias ll='ls -lhF --color=tty' #long listing
alias lsl='ls -hal'
alias lsd='ls -d */'
#Automatically do an ls after each cd
#cd() {
#  if [ -n "$1" ]; then
#    builtin cd "$@" && ls
#  else
#    builtin cd ~ && ls
#  fi
#}

export SSH_AUTH_SOCK=$HOME/.yubiagent/sock
export PATH="/usr/local/opt/python/libexec/bin:$PATH"


# /Users/adong/.nvm/versions/node/v8.0.0/bin:/Users/adong/.rbenv/shims:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin
# export PATH="/usr/local/bin:$PATH"

# Fix Brew
# cd "$(brew --repo)" && git fetch && git reset --hard origin/master && brew update


# asdf
. $HOME/.asdf/asdf.sh
. $HOME/.asdf/completions/asdf.bash
asdf_update_java_home() {
  local current
  if current=$(asdf current java); then
    local version=$(echo $current | cut -d ' ' -f 1)
    export JAVA_HOME=$(asdf where java $version)
  else
    echo "No java version set. Type `asdf list-all java` for all versions."
  fi
}
asdf_update_java_home

# Add RVM to PATH for scripting. Make sure this is the last PATH variable change.
export PATH="$PATH:$HOME/.rvm/bin"
export PATH="/usr/local/opt/ncurses/bin:$PATH"


#THIS MUST BE AT THE END OF THE FILE FOR SDKMAN TO WORK!!!
export SDKMAN_DIR="/Users/adong/.sdkman"
[[ -s "/Users/adong/.sdkman/bin/sdkman-init.sh" ]] && source "/Users/adong/.sdkman/bin/sdkman-init.sh"


function hookProxy() {
  export http_proxy=http://127.0.0.1:1087;
  export https_proxy=http://127.0.0.1:1087;
  export all_proxy=socks5://127.0.0.1:1086
  echo 'Proxy is on'
}

function unhookProxy() {
  unset http_proxy
  unset https_proxy
  unset all_proxy
  echo 'Proxy is off'
}

function hookProxy1080() {
  export http_proxy=http://127.0.0.1:1081;
  export https_proxy=http://127.0.0.1:1081;
  export all_proxy=socks5://127.0.0.1:1080
  echo 'Proxy 1080 is on'
}

function unhookProxy1080() {
  unset http_proxy
  unset https_proxy
  unset all_proxy
  echo 'Proxy 1080 is off'
}


@ldong
Copy link
Author

ldong commented Sep 26, 2018

Updated: 9/25/2018

# Path to your oh-my-zsh installation.
export ZSH=~/.oh-my-zsh

# Set name of the theme to load.
# Look in ~/.oh-my-zsh/themes/
# Optionally, if you set this to "random", it'll load a random theme each
# time that oh-my-zsh is loaded.
ZSH_THEME="robbyrussell"

# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"

# Uncomment the following line to use hyphen-insensitive completion. Case
# sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"

# Uncomment the following line to disable bi-weekly auto-update checks.
# DISABLE_AUTO_UPDATE="true"

# Uncomment the following line to change how often to auto-update (in days).
# export UPDATE_ZSH_DAYS=13

# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"

# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"

# Uncomment the following line to enable command auto-correction.
ENABLE_CORRECTION="true"

# Uncomment the following line to display red dots whilst waiting for completion.
# COMPLETION_WAITING_DOTS="true"

# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"

# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# HIST_STAMPS="mm/dd/yyyy"

# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder

# Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*)
# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(git fasd tmux zsh-syntax-highlighting git-aliases command-not-found)

# User configuration

# export PATH="/usr/bin:/bin:/usr/sbin:/sbin:$PATH"
# export MANPATH="/usr/local/man:$MANPATH"

source $ZSH/oh-my-zsh.sh

# You may need to manually set your language environment
# export LANG=en_US.UTF-8

# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
#   export EDITOR='vim'
# else
#   export EDITOR='mvim'
# fi

# Compilation flags
# export ARCHFLAGS="-arch x86_64"

# ssh
# export SSH_KEY_PATH="~/.ssh/dsa_id"

# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"


# =============================== Git Only =====================================
alias gpushPages='git push origin gh-pages'
alias gpush='git push origin master'
alias gpull='git pull origin master'
alias gpushHead='git push origin head'
alias gitname='git config --global user.name "Alan Dong"'
alias gitemail='git config --global user.email "[email protected]"'
alias gclean='git reset --hard && git clean -dfx'
alias gitcopy='git clone --depth 1 '
alias gs='git status'
alias gsf='git status --untracked-files'
alias gst='git stash'
alias gsp='git stash pop'
alias grm='git rebase master'
alias gpo='git pull origin'
alias gcob='git checkout -b'
alias gUpdateLocalBranches='git remote update origin --prune';
# git diff mybranch master -- myfile.cs
# git diff --name-only commit1 commit2
alias gitShowOrigin='git config --get remote.origin.url'
alias gitlog="git log --all --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative"
# Show files for specific commits
function gitShowFileChanges() {
  # gitShowFileChanges f73630faa
  git diff-tree --no-commit-id --name-only -r $@
  # git diff-tree --no-commit-id --name-only -r $1
}
# https://stackoverflow.com/a/24186641/2305243
alias gitRebaseNumberOfCommits='git rev-list master.. --count'
#git rebase -i HEAD~$(gitRebaseNumberOfCommits)

function gitDeleteRemoteBranch() {
  git push origin --delete $@
}

function gitDeleteLocalBranch() {
  git branch -D $@
}

# git config --global alias.clean-branches "!git branch | grep -v master | xargs git branch -D"
alias gitDeleteAllLocalBranchesButMaster='git branch | grep -v "master" | xargs git branch -D'


# http://stackoverflow.com/a/26359665/2305243
function gitCommitAllExceptFiles() {
  git add -u
  git reset -- $@
}
function gitRebaseOursAndContinue() {
  git checkout --ours $@
  git add $@
  git rebase --continue
}
function gitRebaseTheirsAndContinue() {
  git checkout --theirs $@
  git add $@
  git rebase --continue
}

# =============================== Mac Only =====================================
# Set Solarized color
export CLICOLOR=1
export LSCOLORS=exfxcxdxbxegedabagacad

# show full path in finder
# defaults write com.apple.finder _FXShowPosixPathInTitle -bool YES
# show hidden files in finder
# defaults write com.apple.finder AppleShowAllFiles -boolean true ; killall Finder
# hide hidden files in finder
# defaults write com.apple.finder AppleShowAllFiles -boolean false ; killall Finder

# kill docks
alias killdock='killall -KILL Dock'

# hide apps, i.e. sudo chflags hidden /Applications/Game\ Center.app
alias hideapp='sudo chflags hidden '

# edit host
alias edithosts='sudo vim /private/etc/hosts'

# pdf_join merged.pdf 1.pdf 2.pdf
function pdf_join {
  join_py="/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/join.py"
  read "output_file?Name of output file > "
  "$join_py" -o $output_file $@ && open $output_file
}

# proxy list
# https://github.com/mrdulin/blog/issues/18
alias proxy='export all_proxy=socks5://127.0.0.1:1086'
alias unproxy='unset all_proxy'
# export http_proxy=http://127.0.0.1:1087;export https_proxy=http://127.0.0.1:1087;
# function proxy_off(){
#     unset http_proxy
#     unset https_proxy
#     echo -e "Proxy is OFF"
# }
# function proxy_on() {
#     export no_proxy="localhost,127.0.0.1,localaddress,.localdomain.com"
#     export http_proxy="http://127.0.0.1:8118"
#     export https_proxy=$http_proxy
#     echo -e "Proxy is ON"
# }


# whatis $(ls /bin | gshuf -n 1)
alias enable3rdPartyApps="sudo spctl --master-disable"
alias cleanDNS='sudo discoveryutil udnsflushcaches'
alias cleanDNSResponder='sudo killall -HUP mDNSResponder'
alias resetSparkInspector="rm '~/Library/Application Support/.spark_settings'"
alias prettyjson='python -m json.tool'

# ============================= Linux Only =====================================
# Set Solarized color
# eval `dircolors ~/.dircolors`

# echo "Did you know that:"; whatis $(ls /bin | shuf -n 1)
# ============================ Theme ===========================================
# Set the colors to your liking
local vi_normal_marker="%{$fg[green]%}%BN%b%{$reset_color%}"
local vi_insert_marker="%{$fg[cyan]%}%BI%b%{$reset_color%}"
local vi_unknown_marker="%{$fg[red]%}%BU%b%{$reset_color%}"
local vi_mode="$vi_insert_marker"
vi_mode_indicator () {
  case ${KEYMAP} in
    (vicmd)      echo $vi_normal_marker ;;
    (main|viins) echo $vi_insert_marker ;;
    (*)          echo $vi_unknown_marker ;;
  esac
}

# ZSH theme
ZSH_THEME_GIT_PROMPT_PREFIX="%{$fg[magenta]%}➦ %{$fg[red]%}"
ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%}"
ZSH_THEME_GIT_PROMPT_DIRTY=" %{$fg[red]%}✗%{$reset_color%}"
ZSH_THEME_GIT_PROMPT_ADDED="%{$fg[green]%}✚ "
ZSH_THEME_GIT_PROMPT_MODIFIED="%{$fg[yellow]%}⚑ "
ZSH_THEME_GIT_PROMPT_DELETED="%{$fg[red]%}✖ "
ZSH_THEME_GIT_PROMPT_RENAMED="%{$fg[blue]%}▴ "
ZSH_THEME_GIT_PROMPT_UNMERGED="%{$fg[cyan]%}§ "
ZSH_THEME_GIT_PROMPT_UNTRACKED="%{$fg[grey]%}◒ "
ZSH_THEME_GIT_PROMPT_CLEAN=" %{$fg[green]%}✔%{$reset_color%}"

local return_code="%(?..%{$fg[red]%}%? %{$reset_color%})"
# local PROMPT='%F{green}➜ %2c%F{blue} [%f'
local RPROMPT='$(git_prompt_info) %F{blue}] %F{gray}${vi_mode} %F{green}%D{%L:%M} %F{yellow}%D{%p}%f'

if [ "$USER" '==' "vagrant" ]; then
  # ZSH_THEME_GIT_PROMPT_CLEAN="%{$fg[green]%}✔%{$reset_color%}"
  PROMPT='%F{green}➜ %2c%F{blue} [%f '
else
  # ZSH_THEME_GIT_PROMPT_CLEAN="%{$fg[green]%}%{$reset_color%}"
  PROMPT='%F{green}%2c%F{blue} [%f '
fi


# ======================== Customized Scripts ==================================
# extract filename.zip
extract () {
    if [ -f $1 ] ; then
      case $1 in
        *.tar.bz2)   tar xjf $1     ;;
        *.tar.gz)    tar xzf $1     ;;
        *.bz2)       bunzip2 $1     ;;
        *.rar)       unrar e $1     ;;
        *.gz)        gunzip $1      ;;
        *.tar)       tar xf $1      ;;
        *.tbz2)      tar xjf $1     ;;
        *.tgz)       tar xzf $1     ;;
        *.zip)       unzip $1       ;;
        *.Z)         uncompress $1  ;;
        *.7z)        7z x $1        ;;
        *)     echo "'$1'cannot be extracted via extract()" ;;
         esac
     else
         echo "'$1' is not a valid file"
     fi
}

# color man page
man() {
  /usr/bin/man $* | \
    col -b | \
    vim -R -c 'set ft=man nomod nolist' -
}

# json pretty print
alias json="python -mjson.tool"

# VIRTUALENVWRAPPER_PYTHON=/usr/bin/python
# VIRTUALENVWRAPPER_PYTHON=/usr/local/opt/python/libexec/bin
# VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python
# alias c1="awk '{print \$1}'"
# alias c2="awk '{print \$2}'"
# alias c3="awk '{print \$3}'"
# alias c4="awk '{print \$4}'"
# alias c5="awk '{print \$5}'"
# alias c6="awk '{print \$6}'"
# alias c7="awk '{print \$7}'"
# alias c8="awk '{print \$8}'"
# alias c9="awk '{print \$9}'"
function c() { awk "{print \$$1}" }
# example: ls -l | c 4

# export PATH="/usr/local/opt/python/libexec/bin:$PATH"
# VIRTUALENVWRAPPER_PYTHON=/usr/bin/python
# VIRTUALENVWRAPPER_PYTHON=/usr/local/opt/python/libexec/bin
# VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python

if [[ -r /usr/local/bin/virtualenvwrapper.sh ]]; then
  source /usr/local/bin/virtualenvwrapper.sh;
else
  echo "WARNING: Can't find virtualenvwrapper.sh"
fi

## Alias
alias bbb="brew update && brew upgrade && brew cleanup"

# find the name with regex
findi() {
  find . -iname $1;
}

findj() {
  noglob find . -iname $1"*"
}

findk() {
  noglob find . -iname "*"$1"*"
}

timedHistory(){
  perl -lne 'm#: (\d+):\d+;(.+)# && printf "%s :: %s\n",scalar localtime $1,$2' $HISTFILE
}

# ========================= Percol Only =======================
# Python 2.7
# sudo apt-get install python-setuptools
# sudo easy_install pip
# sudo pip install percol
# =============================================================
alias show_process="ps aux | percol | awk '{ print $2 }'"
alias kill_process="ps aux | percol | awk '{ print $2 }' | xargs kill"

# Interactive pgrep / pkill
function ppgrep() {
    if [[ $1 == "" ]]; then
        PERCOL=percol
    else
        PERCOL="percol --query $1"
    fi
    ps aux | eval $PERCOL | awk '{print $2}'
}

function ppkill() {
    if [[ $1 =~ "^-" ]]; then
        QUERY=""            # options only
    else
        QUERY=$1            # with a query
        [[ $# > 0 ]] && shift
    fi
    ppgrep $QUERY | xargs kill $*
}
# zsh history search
function exists { which $1 &> /dev/null }

if exists percol; then
    function percol_select_history() {
        local tac
        exists gtac && tac="gtac" || { exists tac && tac="tac" || { tac="tail -r" } }
        BUFFER=$(fc -l -n 1 | eval $tac | percol --query "$LBUFFER")
        CURSOR=$#BUFFER         # move cursor
        zle -R -c               # refresh
    }

    zle -N percol_select_history
    bindkey '^R' percol_select_history
    bindkey -M vicmd '^R' percol_select_history
    bindkey -M vicmd 'H' percol_select_history
fi


# ZLE key binding
# http://www.cs.elte.hu/zsh-manual/zsh_14.html
# http://zsh.sourceforge.net/Guide/zshguide04.html
bindkey -v
bindkey -M viins 'JJ' vi-cmd-mode
bindkey -M viins 'jj' vi-cmd-mode
bindkey -M vicmd '?' history-incremental-search-backward
bindkey -M vicmd '/' history-incremental-search-forward
bindkey -M vicmd '??' history-incremental-search-forward
bindkey -M vicmd 'H' percol_select_history

# https://www.johnhawthorn.com/2012/09/vi-escape-delays/
# Make Vi mode transitions faster (KEYTIMEOUT is in hundredths of a second)
# default KEYTIMEOUT=400
export KEYTIMEOUT=80

# http://stratus3d.com/blog/2017/10/26/better-vi-mode-in-zshell/
# No VIM Profile
# export EDITOR='vim -u NONE'
bindkey -M vicmd v edit-command-line
bindkey -M vicmd "^V" edit-command-line
bindkey -M viins "^V" edit-command-line
bindkey -M viins 'qq' send-break

# Beginning search with arrow keys
# bindkey "^[OA" up-line-or-beginning-search
# bindkey "^[OB" down-line-or-beginning-search
# bindkey -M vicmd "k" up-line-or-beginning-search
# bindkey -M vicmd "j" down-line-or-beginning-search

bindkey '^K' kill-line
bindkey '^A' beginning-of-line
bindkey '^E' end-of-line



# do history expansion on space
bindkey " " magic-space

# Search for history key bindings
# ctrl+v UP
#bindkey "^[OA" up-line-or-history
# ctrl+v DOWN
#bindkey "^[OB" down-line-or-history
# bindkey "^[[A" up-line-or-history
# bindkey "^[[B" down-line-or-history
# bindkey "^R" history-incremental-search-backward

# Tetris
# autoload -U tetris
# zle -N tetris
# bindkey ^T tetris

# Seach file in vim CtrlP
ctrlp() {
  </dev/tty vim -c 'Unite file_rec/async'
}
zle -N ctrlp
bindkey "^p" ctrlp


# Edit command in vim ctrl-e
autoload edit-command-line
zle -N edit-command-line
bindkey '^e' edit-command-line

# works without vim mode
#autoload -U up-line-or-beginning-search
#autoload -U down-line-or-beginning-search
#zle -N up-line-or-beginning-search
#zle -N down-line-or-beginning-search
#bindkey "^[[A" up-line-or-beginning-search # Up
#bindkey "^[[B" down-line-or-beginning-search # Down


# You may already have those in your .zshrc somewhere
# autoload -U promptinit && promptinit
# autoload -U colors     && colors
# setopt prompt_subst
#
# Reset mode-marker and prompt whenever the keymap changes
function zle-line-init zle-keymap-select {
  vi_mode="$(vi_mode_indicator)"
  zle reset-prompt
}
zle -N zle-line-init
zle -N zle-keymap-select

# Multiline-prompts don't quite work with reset-prompt; we work around this by
# printing the first line(s) via a precmd which is executed before the prompt
# is printed.  The following can be integrated into PROMPT for single-line
# prompts.

# local user_host='%B%n%b@%m'
# local current_dir='%~'
# precmd () print -rP"${user_host} ${current_dir}"



# completer widget that sets a flag for the duration of
# the completion so the SIGINT handler knows whether completion
# is active. It would be better if we could check some internal
# zsh parameter to determine if completion is running, but as
# far as I'm aware that isn't possible.
function interruptible-expand-or-complete {
    COMPLETION_ACTIVE=1

    # Bonus feature: automatically interrupt completion
    # after a three second timeout.
    # (sleep 3; kill -INT $$) &!

    zle expand-or-complete

    COMPLETION_ACTIVE=0
}

# Bind our completer widget to tab.
zle -N interruptible-expand-or-complete
bindkey '^I' interruptible-expand-or-complete

# Interrupt only if completion is active.
function TRAPINT {
    if [[ $COMPLETION_ACTIVE == 1 ]]; then
        COMPLETION_ACTIVE=0
        zle -M "Completion canceled."

        # Returning non-zero tells zsh to handle SIGINT,
        # which will interrupt the completion function.
        return 1
    else
        # Returning zero tells zsh that we handled SIGINT;
        # don't interrupt whatever is currently running.
        return 0
    fi
}


# https://www.gnu.org/software/bash/manual/html_node/Miscellaneous-Commands.html
# https://gist.github.com/srustamo/93b9b9fc16bde207d80b
copy() {
  if [[ $1 =~ ^-?[hH] ]]; then

    echo "Intelligently copies command results, text file, or raw text to"
    echo "OS X clipboard"
    echo
    echo "Usage: copy [command or text]"
    echo "  or pipe a command: [command] | copy"
    return
  fi

  local output
  local res=false
  local tmpfile="${TMPDIR}/copy.$RANDOM.txt"
  local msg=""

  if [[ $# == 0 ]]; then
    output=$(cat)
    msg="Input copied to clipboard"
    res=true
  else
    local cmd=""
    for arg in $@; do
      cmd+="\"$(echo -en $arg|sed -E 's/"/\\"/g')\" "
    done
    output=$(eval "$cmd" 2> /dev/null)
    if [[ $? == 0 ]]; then
      msg="Results of command are in the clipboard"
      res=true
    else
      if [[ -f $1 ]]; then
        output=""
        for arg in $@; do
          if [[ -f $arg ]]; then
            type=`file "$arg"|grep -c text`
            if [ $type -gt 0 ]; then
              output+=$(cat $arg)
              msg+="Contents of $arg are in the clipboard.\n"
              res=true
            else
              msg+="File \"$arg\" is not plain text.\n"
            fi
          fi
        done
      else
        output=$@
        msg="Text copied to clipboard"
        res=true
      fi
    fi
  fi

  $res && echo -ne "$output" | pbcopy -Prefer txt
  echo -e "$msg"
}

## FZF
# brew install fzf
function findAll() {
  # find * -type f | fzf -m > selected
  find * -type f | fzf -m
}

zle -N findAll
bindkey '^F' findAll
bindkey -M vicmd '^F' findAll

# AG silver search
function agc() {
  ag --color --group $@ | cut -c -100
}

function agi() {
  ag --ignore-case $@
}

function agSearchExtensionWithKeyword {
  # ag -G '\.(hbs|handlebars|js)$' keyword
  ag -G "\.($1)" $2
}

function agShowNumberOfFilesHasExactKeyword {
  ag -w $@ -c | wc -l
}
# AG
# ag -G '\.(filetypes)$' keyword
# ag -G '\.(hbs|html)$' keyword

# Create a new directory and enter it
function mkd() {
    mkdir -p "$@" && cd "$_";
}

# Create a .tar.gz archive, using `zopfli`, `pigz` or `gzip` for compression
function targz() {
    local tmpFile="${@%/}.tar";
    tar -cvf "${tmpFile}" --exclude=".DS_Store" "${@}" || return 1;

    size=$(
        stat -f"%z" "${tmpFile}" 2> /dev/null; # macOS `stat`
        stat -c"%s" "${tmpFile}" 2> /dev/null;  # GNU `stat`
    );

    local cmd="";
    if (( size < 52428800 )) && hash zopfli 2> /dev/null; then
        # the .tar file is smaller than 50 MB and Zopfli is available; use it
        cmd="zopfli";
    else
        if hash pigz 2> /dev/null; then
            cmd="pigz";
        else
            cmd="gzip";
        fi;
    fi;

    echo "Compressing .tar ($((size / 1000)) kB) using \`${cmd}\`…";
    "${cmd}" -v "${tmpFile}" || return 1;
    [ -f "${tmpFile}" ] && rm "${tmpFile}";

    zippedSize=$(
        stat -f"%z" "${tmpFile}.gz" 2> /dev/null; # macOS `stat`
        stat -c"%s" "${tmpFile}.gz" 2> /dev/null; # GNU `stat`
    );

    echo "${tmpFile}.gz ($((zippedSize / 1000)) kB) created successfully.";
}


# Start an HTTP server from a directory, optionally specifying the port
function server() {
    local port="${1:-8000}";
    # sleep 1 && open "http://localhost:${port}/" &
    # Set the default Content-Type to `text/plain` instead of `application/octet-stream`
    # And serve everything as UTF-8 (although not technically correct, this doesn’t break anything for binary files)
    python -c $'import SimpleHTTPServer;\nmap = SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map;\nmap[""] = "text/plain";\nfor key, value in map.items():\n\tmap[key] = value + ";charset=UTF-8";\nSimpleHTTPServer.test();' "$port";
}

# Syntax-highlight JSON strings or files,similar to json format
# Usage: `json '{"foo":42}'` or `echo '{"foo":42}' | json`
function json() {
    if [ -t 0 ]; then # argument
        python -mjson.tool <<< "$*" | pygmentize -l javascript;
    else # pipe
        python -mjson.tool | pygmentize -l javascript;
    fi;
}

# `v` with no arguments opens the current directory in Vim, otherwise opens the
# given location
function v() {
    if [ $# -eq 0 ]; then
        vim .;
    else
        vim "$@";
    fi;
}

# Find out my ip, http://ifconfig.me
alias wanip='dig +short myip.opendns.com @resolver1.opendns.com'
alias lanip="ifconfig | sed -n 's/.*inet addr:\([0-9.]\+\)\s.*/\1/p'"
alias whatsmyip="curl http://httpbin.org/ip"
alias myip='curl ifconfig.co'
alias myip2='curl cip.cc'
alias myip3='curl ip.gs'
alias myip4='curl http://checkip.amazonaws.com'
alias myip5='curl ip.cn'

# Kill process of retaining port
#sudo lsof -i :9000
#sudo kill -9 61342

# Nodejs
alias npmls="npm ls --depth=0 "$@" 2>/dev/null"

# display the colors
#alias colors='bash ~/.dotfiles/color.sh'
#alias color256='python ~/.dotfiles/checkColor.py'

# remove .DS_Store file
alias rmDSStore='find . -name ".DS_Store" -depth -exec rm {} \;'
alias rmDSStoreLocal='find . -name '.DS_Store' -type f -delete'
# remove vim cache files
alias rmswp='find . -name \*.swp -type f -delete'

# remove python pyc files
alias rmpyc='find . -name \*.pyc -type f -delete'

# echo "text" | rot13
alias rot13="tr '[A-Za-z]' '[N-ZA-Mn-za-m]'"

# Count files
alias countFiles='ls -1 | wc -l'

# download uses aria2
alias download='aria2c -s 10 '
alias downloadDirectory='wget -r -np '

# Rails
alias railsUP='rails s -b 0.0.0.0'

# local http servers use python
alias httphere='python -m SimpleHTTPServer 8080'
alias httphere3='python3 -m http.server 8080'
alias httphereWithUpload='python ~/.dotfiles/SimpleHTTPServerWithUpload.py 8080'

if [ "$(uname -s)" '==' "Darwin" ]; then
  alias ls='ls -F -G'
else
  alias ls='ls -F --color=auto'
fi

alias vi='vim'
alias javac="javac -J-Dfile.encoding=utf8"
alias grep="grep --color=auto"
alias -s html=vi  # open files in vim
alias -s rb=vi
alias -s py=vi
alias -s js=vi
alias -s c=vi
alias -s java=vi
alias -s txt=vi
alias -s gz='tar -xzvf'
alias -s tgz='tar -xzvf'
alias -s zip='unzip'
alias -s bz2='tar -xjvf'

alias cp='cp -i'
alias mv='mv -i'
alias rm='rm -i'
alias rm='rmtrash'
alias rmdir='rmdirtrash'
alias sudo='sudo '
alias grep='grep --color=auto'

## Source utils
# source ~/.utils/gitjump.sh

function gi() { curl -L -s https://www.gitignore.io/api/$@ ;}
if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi

# curl -L https://iterm2.com/misc/install_shell_integration.sh | bash
# This will set your window title, http://stackoverflow.com/a/38484310/2305243
export PROMPT_COMMAND='echo -ne "\033]0;${PWD##*/}\007"'

source ~/.iterm2_shell_integration.`basename $SHELL`

# This creates the var currentDir to use later on, \(user.currentDir) as badge
function iterm2_print_user_vars() {
  iterm2_set_user_var currentDir $(echo ${PWD##*/})
}

export NVM_DIR="$HOME/.nvm"
# [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
export NVM_DIR=~/.nvm
source $(brew --prefix nvm)/nvm.sh
# . "/usr/local/opt/nvm/nvm.sh"

function phone() {
 open "tel://$*"
}




function youtube-dl-best() {
  youtube-dl -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best' $@
}

# export JAVA_HOME="$(/usr/libexec/java_home -v 1.9)"
# export JAVA_HOME="$(/usr/libexec/java_home -v 9)"
# export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"
# /Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home

# echo $JAVA_HOME
# /Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home
alias enable3rdPartyApps="sudo spctl --master-disable"

alias jsonifyFile="python -mjson.tool "

# lbys = ls by size
alias lbys='ls -alhS'

# lbyt = ls by time
alias lbyt='ls -alht'

# cl = copy last output
alias cl='bash -c "$(fc -ln -1)" | pbcopy'

# copy last commandline
alias last='fc -ln -1 | pbcopy'

# Save paste to file
alias new='pbpaste | cat >'
alias save='pbpaste | cat >'

alias today='date +"%A, %B %-d, %Y"'
alias bzip2='bzip2 -v'
alias j=jobs
# cd
alias cd..="cd .."

#Use human-readable filesizes
alias df="df -h"
alias du="du -h"
alias du="ncdu --color dark -rr -x --exclude .git --exclude node_modules"

#Aliases for improved directory listings
#The --color=tty option shows items in different colors according to their type.
#For example, directories are blue, executable files are green, symlinks are cyan, etc.
#The -F option appends a symbol after entries to indicate their types.
#You might not like both options at the same time.
#alias ls='ls -F --color=tty' #regular ls
#alias l.='ls -dF .[a-zA-Z0-9]* --color=tty' #only show dotfiles
#alias ll='ls -lhF --color=tty' #long listing
alias lsl='ls -hal'
alias lsd='ls -d */'
#Automatically do an ls after each cd
#cd() {
#  if [ -n "$1" ]; then
#    builtin cd "$@" && ls
#  else
#    builtin cd ~ && ls
#  fi
#}

export SSH_AUTH_SOCK=$HOME/.yubiagent/sock
export PATH="/usr/local/opt/python/libexec/bin:$PATH"


# /Users/adong/.nvm/versions/node/v8.0.0/bin:/Users/adong/.rbenv/shims:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin
# export PATH="/usr/local/bin:$PATH"

# Fix Brew
# cd "$(brew --repo)" && git fetch && git reset --hard origin/master && brew update


# asdf
. $HOME/.asdf/asdf.sh
. $HOME/.asdf/completions/asdf.bash
asdf_update_java_home() {
  local current
  if current=$(asdf current java); then
    local version=$(echo $current | cut -d ' ' -f 1)
    export JAVA_HOME=$(asdf where java $version)
  else
    echo "No java version set. Type `asdf list-all java` for all versions."
  fi
}
asdf_update_java_home

# Add RVM to PATH for scripting. Make sure this is the last PATH variable change.
export PATH="$PATH:$HOME/.rvm/bin"
export PATH="/usr/local/opt/ncurses/bin:$PATH"


#THIS MUST BE AT THE END OF THE FILE FOR SDKMAN TO WORK!!!
export SDKMAN_DIR="/Users/adong/.sdkman"
[[ -s "/Users/adong/.sdkman/bin/sdkman-init.sh" ]] && source "/Users/adong/.sdkman/bin/sdkman-init.sh"


function hookProxy() {
  export http_proxy=http://127.0.0.1:1087;
  export https_proxy=http://127.0.0.1:1087;
  export all_proxy=socks5://127.0.0.1:1086
  echo 'Proxy is on'
}

function unhookProxy() {
  unset http_proxy
  unset https_proxy
  unset all_proxy
  echo 'Proxy is off'
}

function hookProxy1080() {
  export http_proxy=http://127.0.0.1:1081;
  export https_proxy=http://127.0.0.1:1081;
  export all_proxy=socks5://127.0.0.1:1080
  echo 'Proxy 1080 is on'
}

function unhookProxy1080() {
  unset http_proxy
  unset https_proxy
  unset all_proxy
  echo 'Proxy 1080 is off'
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment