#!/usr/bin/zsh
# vim: set fdm=marker fmr={{{,}}}:

stty -ixon

# Compinstall {{{
zstyle ':completion:*' completer _complete _ignored _correct _approximate
zstyle ':completion:*' matcher-list '' 'm:{[:lower:]}={[:upper:]} m:{[:lower:][:upper:]}={[:upper:][:lower:]} r:|[._- :]=** r:|=**' 'l:|=* r:|=*'
zstyle ':completion:*' max-errors 5
zstyle ':completion:*' use-cache yes
zstyle ':completion::complete:grunt::options:' expire 1
zstyle ':completion:*' prompt '%e errors'
zstyle :compinstall filename '~/.zshrc'
autoload -Uz compinit
compinit
# }}}

# Zsh-newuser-install {{{
HISTFILE=~/.histfile
HISTSIZE=1000
SAVEHIST=1000
setopt appendhistory autocd extendedglob notify autopushd
unsetopt beep nomatch
bindkey -v
# }}}

# Basic options {{{
set -o vi
umask 022
export VIRTUAL_ENV_DISABLE_PROMPT=1
# export PATH=~/.local/bin:~/.cabal/bin:$PATH:~/code/go/bin:~/bin:~/npm/bin:~/.gem/ruby/2.1.0/bin:~/.gem/ruby/2.0.0/bin:/home/smith/bin
# }}}

# Zsh highlight highlighters {{{
ZSH_HIGHLIGHT_HIGHLIGHTERS=(main brackets pattern root)
# }}}

# More basic options {{{
setopt no_hist_verify
setopt histignorespace
# }}}

# Utility Functions {{{

# Set the terminal's title bar.
function titlebar() {
echo -ne "\033]0;$*\007"
}

function quiet() {
"$@" >/dev/null
}

function quieter() {
"$@" >/dev/null 2>&1
}

# From http://stackoverflow.com/questions/370047/#370255
function path_remove() {
IFS=:
# convert it to an array
t=($PATH)
unset IFS
# perform any array operations to remove elements from the array
t=(${t[@]%%$1})
IFS=:
# output the new array
echo "${t[*]}"
}

# }}}

# Force screen to use zsh {{{
# }}}

# Environment {{{
# }}}

# Directory Stuff {{{

# Always use color output for `ls`

# Directory listing

# Easier navigation: .., ..., -

# File size

# Recursively delete `.DS_Store` files

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

# }}}

# MPD/MPC stuff {{{
function mp() {
# Test if drive is already mounted
if ! lsblk | grep /media/external >/dev/null; then
  if ! sudo mount /media/external; then
    echo "External drive not plugged in, or could not mount"
    return 1
  fi
fi
if (mpc >/dev/null 2>&1); then
  ncmpcpp
else
  mpd &&
    (pgrep mpdscribble || mpdscribble) &&
    ncmpcpp
fi
}

# kill mp
function kmp() {
killall ncmpcpp
mpd --kill

local files

if (files=$(lsof 2>&1 | grep -v docker | grep external)); then
  echo
  echo "==> Still processes using external drive:"
  echo
  echo $files
else
  sudo umount /media/external
fi
}


function mppal() {
mpc search album "$1" | mpc add &&
  mpc play;
}
# }}}

# Git stuff {{{
# function ga() { git add "${@:-.}"; } # Add all files by default
# Add non-whitespace changes
# function gc() { git checkout "${@:-master}"; } # Checkout master by default

# open all changed files (that still actually exist) in the editor
function ged() {
local files=()
for f in $(git diff --name-only "$@"); do
  [[ -e "$f" ]] && files=("${files[@]}" "$f")
done
local n=${#files[@]}
echo "Opening $n $([[ "$@" ]] || echo "modified ")file$([[ $n != 1 ]] && \
  echo s)${@:+ modified in }$@"
q "${files[@]}"
}

# git find-replace
function gfr() {
if [[ "$#" == "0" ]]; then
  echo 'Usage:'
  echo ' gg_replace term replacement file_mask'
  echo
  echo 'Example:'
  echo ' gg_replace cappuchino cappuccino *.html'
  echo
else
  find=$1; shift
  replace=$1; shift

  ORIG_GLOBIGNORE=$GLOBIGNORE
  GLOBIGNORE=*.*
  if [[ "$#" = "0" ]]; then
    set -- ' ' $@
  fi

  while [[ "$#" -gt "0" ]]; do
    for file in `git grep -l $find -- $1`; do
      sed -e "s/$find/$replace/g" -i'' $file
    done
    shift
  done

  GLOBIGNORE=$ORIG_GLOBIGNORE
fi
}

function vconflicts() {
$EDITOR $(git status --porcelain | awk '/^UU/ { print $2 }')
}
# }}}

# fzf {{{
v() {
  local file
  file=$(fzf-tmux --query="$1" --select-1 --exit-0)
  [ -n "$file" ] && ${EDITOR:-vim} "$file"
}

c() {
  local dir
  dir=$(find ${1:-*} -path '*/\.*' -prune -o -type d -print 2> /dev/null | fzf +m) && cd "$dir"
}

co() {
  local branch
  branch=$(git branch -a | sed -s "s/\s*\**//g" | fzf --query="$1" --select-1 --exit-0) && git checkout "$branch"
}


# fh - repeat history
# h() {
#   eval $(([ -n "$ZSH_NAME" ] && fc -l 1 || history) | fzf +s | sed 's/ *[0-9]* *//')
# }

# fkill - kill process
fkill() {
  ps -ef | sed 1d | fzf-tmux -m | awk '{print $2}' | xargs kill -${1:-9}
}
# }}}

# Tmux utils {{{
kill_detached() {
  for sess in $(tmux ls | grep -v attached | sed -s "s/:.*$//"); do
    tmux kill-session -t $sess;
  done
}
# }}}

# Docker {{{


# dbp foo/bar .
function dbp () {
  docker build -t $1 ${@:2} && docker push $1
}

# }}}

# Twitter! {{{


# favelast <username>
function favelast() {
  t fave $(t tl -l $1 | head -n1 | first)
}

function rtlast() {
  t rt $(t tl -l $1 | head -n1 | first)
}

function tthread() {
  t reply $(t tl -l $TWITTER_WHOAMI | head -n1 | first) $@
}
# }}}

# Geeknote {{{
gnc() {
  gn create --title $1 --content '' &&
    gn find --count=1 "$1"
    gn edit 1
}
# }}}

# Misc aliases {{{

function fw() { # fix white
  local substitution
  local substitution='s/\x1b\[90m/\x1b[92m/g'
  $@ > >(perl -pe "$substitution") 2> >(perl -pe "$substitution" 1>&2)
}
# }}}

# Grep options {{{
unset GREP_OPTIONS
export GREP_OPTIONS=
# }}}


# Run docker containers {{{
    # -d \
    # -v $HOME/.pentadactyl:/home/firefox/.pentadactyl:rw \
    # -v $HOME/.pentadactylrc:/home/firefox/.pentadactylrc:rw \
    # -v $HOME/.mozilla:/home/firefox/.mozilla:rw \
    # -v $HOME/.config:/home/firefox/.config \
    # -v $HOME/Downloads:/home/firefox/Downloads:rw \
    # -v /etc/fonts:/etc/fonts \
    # -v /tmp/.X11-unix:/tmp/.X11-unix \
    # -v /dev/snd:/dev/snd \
    # --net=host \
    # -v $XDG_RUNTIME_DIR:$XDG_RUNTIME_DIR \
    # -e uid=$(id -u) \
    # -e gid=$(id -g) \
    # -e DISPLAY=$DISPLAY \
    # -e XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR \
    # --name firefox \
    # --rm -it \
    # glittershark/firefox
# }}}

# Change cursor shape on insert/normal mode {{{
# (https://unix.stackexchange.com/q/433273/64261)

KEYTIMEOUT=5

_fix_cursor() {
   echo -ne '\e[5 q'
}

precmd_functions+=(_fix_cursor)

function zle-keymap-select {
  if [[ ${KEYMAP} == vicmd ]] ||
       [[ $1 = 'block' ]]; then
  echo -ne '\e[1 q'

  elif [[ ${KEYMAP} == main ]] ||
         [[ ${KEYMAP} == viins ]] ||
         [[ ${KEYMAP} = '' ]] ||
         [[ $1 = 'beam' ]]; then
  echo -ne '\e[5 q'
  fi
}
zle -N zle-keymap-select

# }}}

[ -f ./.localrc ] && source ./.localrc
