# pyenv fish
set -gx PYENV_ROOT "$HOME/.pyenv"
set -x PATH $PATH "$PYENV_ROOT/bin"
status --is-interactive; and . (pyenv init - | psub)

# emacs alias
alias e="emacs -nw"

# peco
function peco_select_history
    if set -q $argv
        history | peco | read line; commandline $line
    else
        history | peco --query $argv | read line; commandline $line
    end
end

function fish_user_key_bindings
    bind \cr peco_select_history
end

# rmでゴミ箱へ移す
alias rm=trash

# git alias
alias g=git
alias ga='git add'
alias ga.='git add .'
alias gaA='git add -A'
alias gcm='git commit -m'
alias gcam='git commit -a -m'
alias gs='git status'
alias gp='git push'
alias gd='git diff'
alias gb='git branch'
alias gc='git checkout'
alias gl='git pull'
function gacp -d "gacp [file] 'commit message'"
    git add $argv[1]
    git commit -m $argv[2]
    git push
end

function gacp -d "gacp 'commit message' (file;optional)"
    if test count $argv > /dev/null -eq 2
        git add $argv[2]
    else
        git add -A
    end
    git commit -m $argv[1]
    git push
end

Fix gacp function with count command

# pyenv fish
set -gx PYENV_ROOT "$HOME/.pyenv"
set -x PATH $PATH "$PYENV_ROOT/bin"
status --is-interactive; and . (pyenv init - | psub)

# emacs alias
alias e="emacs -nw"

# peco
function peco_select_history
    if set -q $argv
        history | peco | read line; commandline $line
    else
        history | peco --query $argv | read line; commandline $line
    end
end

function fish_user_key_bindings
    bind \cr peco_select_history
end

# rmでゴミ箱へ移す
alias rm=trash

# git alias
alias g=git
alias ga='git add'
alias ga.='git add .'
alias gaA='git add -A'
alias gcm='git commit -m'
alias gcam='git commit -a -m'
alias gs='git status'
alias gp='git push'
alias gd='git diff'
alias gb='git branch'
alias gc='git checkout'
alias gl='git pull'
function gacp -d "gacp [file] 'commit message'"
    git add $argv[1]
    git commit -m $argv[2]
    git push
end

function gacp -d "gacp 'commit message' (file;optional)"
    if test (count $argv) -eq 2
        git add $argv[2]
    else
        git add -A
    end
    git commit -m $argv[1]
    git push
end


fish_vi_key_bindings

for word in "$HOME/"{bin,.local/bin,go/bin}
    if not contains $word $PATH
        set PATH $word $PATH
    end
end

set -x GOPATH "$HOME/go"

set fish_complete_path "$HOME/git/github.fish-pip-completion" $fish_complete_path

switch (uname)
    case Linux
        source /usr/share/autojump/autojump.fish
    case Darwin
        source /usr/local/share/autojump/autojump.fish
        for word in {"$HOME/Library/Python/2.7/bin",/usr/local/sbin}
            if not contains $word $PATH
                set PATH $word $PATH
            end
        end
end
source (pew shell_config)

Switch to Python 3.5 user bins

fish_vi_key_bindings

for word in "$HOME/"{bin,.local/bin,go/bin}
    if not contains $word $PATH
        set PATH $word $PATH
    end
end

set -x GOPATH "$HOME/go"

set fish_complete_path "$HOME/git/github.fish-pip-completion" $fish_complete_path

switch (uname)
    case Linux
        source /usr/share/autojump/autojump.fish
    case Darwin
        source /usr/local/share/autojump/autojump.fish
        for word in {"$HOME/Library/Python/3.5/bin",/usr/local/sbin}
            if not contains $word $PATH
                set PATH $word $PATH
            end
        end
end
source (pew shell_config)


function shorten_path
	if test -z $argv[2]
		echo $argv[1] | sed -e "s#$HOME#~#g" | sed -e 's#\\(\\.\\?[^/]\\{1\\}\\)[^/]*/#\\1/#g'
	else
		echo $argv[1] | sed -e "s#$argv[2]#$argv[3]#g" | sed -e 's#\\(\\.\\?[^/]\\{1\\}\\)[^/]*/#\\1/#g'
	end
end

Use count to check if enough arguments are given


# Turn off the default greeting
set fish_greeting

# Specify my preferred path dirs here (in reverse order) and ensure they get
# re-placed at the front of the current $PATH.
#
# Include Postgres.app here, before asdf inits, so asdf's shims end up first
# of all (allowing Postgres.app to be seen by asdf as the "system" postgres)
set -l extra_path_dirs /Applications/Postgres.app/Contents/Versions/latest/bin
for extra_dir in $extra_path_dirs
  set PATH $extra_dir (string match -v $extra_dir $PATH)
end

direnv hook fish | source

source /usr/local/opt/asdf/asdf.fish

source ~/.secrets.fish

set --export EDITOR "code"

set --export HOMEBREW_CASK_OPTS "--appdir=/Applications"

# Default extra options for asdf postgres installations
set --export POSTGRES_EXTRA_CONFIGURE_OPTIONS "--with-uuid=e2fs"

function fish_user_key_bindings
  # Thanks, https://github.com/fish-shell/fish-shell/issues/905#issuecomment-20559486
  bind \cc 'echo; commandline ""; commandline -f repaint'
end

Stop homebrew from auto updating

# Turn off the default greeting
set fish_greeting

# Specify my preferred path dirs here (in reverse order) and ensure they get
# re-placed at the front of the current $PATH.
#
# Include Postgres.app here, before asdf inits, so asdf's shims end up first
# of all (allowing Postgres.app to be seen by asdf as the "system" postgres)
set -l extra_path_dirs /Applications/Postgres.app/Contents/Versions/latest/bin
for extra_dir in $extra_path_dirs
  set PATH $extra_dir (string match -v $extra_dir $PATH)
end

direnv hook fish | source

source /usr/local/opt/asdf/asdf.fish

source ~/.secrets.fish

set --export EDITOR "code"

set --export HOMEBREW_CASK_OPTS "--appdir=/Applications"
set --export HOMEBREW_NO_AUTO_UPDATE "1"

# Default extra options for asdf postgres installations
set --export POSTGRES_EXTRA_CONFIGURE_OPTIONS "--with-uuid=e2fs"

function fish_user_key_bindings
  # Thanks, https://github.com/fish-shell/fish-shell/issues/905#issuecomment-20559486
  bind \cc 'echo; commandline ""; commandline -f repaint'
end


##
# onnimonni preferred aliases and functions
##

##
# Get current conf file directory
# This needs to resolve symlinks from rcm
##
function fish_config_dir
    switch (uname)
    case Darwin # OS-X
        echo ( dirname ( readlink    (status --current-filename) ) )
    case '*'
        echo ( dirname ( readlink -f (status --current-filename) ) )
    end
end

# Use files from this folder and from homebrew /usr/local/sbin
set PATH ~/.dotfiles/bin /usr/local/sbin $PATH

set FDIR (fish_config_dir)

source $FDIR/aliases.fish
source $FDIR/hacks.fish
source $FDIR/prompt.fish
source $FDIR/colors.fish

# Use remote hacks if connection is not local and local hacks otherwise
if test -d $SSH_CONNECTION
  source $FDIR/local.fish
  # Don't store secrets in git
  source ~/.secrets.fish
else
  source $FDIR/remote.fish
end

# Remove temporary variable afterwise
unset FDIR

Add npm packages to PATH

##
# onnimonni preferred aliases and functions
##

##
# Get current conf file directory
# This needs to resolve symlinks from rcm
##
function fish_config_dir
    switch (uname)
    case Darwin # OS-X
        echo ( dirname ( readlink    (status --current-filename) ) )
    case '*'
        echo ( dirname ( readlink -f (status --current-filename) ) )
    end
end

# Use files from this folder and from homebrew /usr/local/sbin
set PATH ~/.dotfiles/bin ~/.npm-packages/bin/ /usr/local/sbin $PATH

set FDIR (fish_config_dir)

source $FDIR/aliases.fish
source $FDIR/hacks.fish
source $FDIR/prompt.fish
source $FDIR/colors.fish

# Use remote hacks if connection is not local and local hacks otherwise
if test -d $SSH_CONNECTION
  source $FDIR/local.fish
  # Don't store secrets in git
  source ~/.secrets.fish
else
  source $FDIR/remote.fish
end

# Remove temporary variable afterwise
unset FDIR


# Installs and updates Xcode.
#
# Sequencing
# - After: rubygems (uses xcode-install)
function 📱__xcode
    echo "📱  Xcode"
    echo

    if test -z $XCODE_INSTALL_USER; and test -n (user.email)
        set --export --universal XCODE_INSTALL_USER (user.email)
    end

    # Update the list of available versions to install
    xcversion update

    # Install the CLI tools, if necessary
    if not test -e /Library/Developer/CommandLineTools/usr/lib/libxcrun.dylib
        xcversion install-cli-tools
    end

    echo "Available:"
    xcversion list
    set -l installed (xcversion list)
    set -l newest_version $installed[-1]
    if not string match "*(installed)" $newest_version
        xcversion install $newest_version
    end

    echo
    echo "Installed:"
    xclist
end

Print current Xcode version before doing anything else

# Installs and updates Xcode.
# https://developer.apple.com/downloads/
#
# Sequencing
# - After: rubygems (uses xcode-install)
function 📱__xcode
    echo "📱  Xcode"
    echo

    if test -z $XCODE_INSTALL_USER; and test -n (user.email)
        set --export --universal XCODE_INSTALL_USER (user.email)
    end

    # Currently selected version
    xcode-select --print-path

    # Update the list of available versions to install
    xcversion update

    # Install the CLI tools, if necessary
    if not test -e /Library/Developer/CommandLineTools/usr/lib/libxcrun.dylib
        # Manual way
        # xcode-select --install
        xcversion install-cli-tools
    end

    echo "Available:"
    xcversion list
    set -l installed (xcversion list)
    set -l newest_version $installed[-1]
    if not string match "*(installed)" $newest_version
        xcversion install $newest_version
    end

    echo
    echo "Installed:"
    xclist
end


Add function to find access keys for a user

function user-access-keys --argument user
    if empty "$user"
        usage user-access-keys '<user>'
        return (false)
    end

    aws iam list-access-keys --user-name "$user" | jq --raw-output .AccessKeyMetadata[].AccessKeyId
end


function shorten_path
  if test (count $argv) -lt 3
    echo $argv[1] | sed -e "s#$HOME#~#g" | sed -e 's#\\(\\.\\?[^/]\\{1\\}\\)[^/]*/#\\1/#g'
  else
    echo $argv[1] | sed -e "s#$argv[2]#$argv[3]#g" | sed -e 's#\\(\\.\\?[^/]\\{1\\}\\)[^/]*/#\\1/#g'
  end
end

Fix shorten path incorrectly shortening files in /home


abbr -a -- - 'cd -'
abbr -a axel 'axel -a'
abbr -a b 'brew'
abbr -a c 'nix-shell -p clojure --command "clojure -A:rebel -A:cheshire"'
abbr -a dl 'wget -r -l 1 -np -nd'
abbr -a fn 'find . -iname'

abbr -a g git
abbr -a ga git add
abbr -a gap git add --patch
abbr -a gb git branch
abbr -a gc git commit --verbose
abbr -a gco git checkout
abbr -a gd git diff
abbr -a gdc git diff --color-words
abbr -a gds git diff --staged
abbr -a gf git fetch
abbr -a gl git log --graph --decorate
abbr -a gl1 git log -1
abbr -a gll git log \'@\{u\}..\'
abbr -a glr git log \'..@\{u\}\'
abbr -a gr git remote
abbr -a gs git status -sb

abbr -a l 'ls -lahp'
abbr -a le 'less'
abbr -a lx 'less -X'
abbr -a ns 'nix-shell --command fish -p'
abbr -a np 'nix-shell -p'
abbr -a o 'open .'
abbr -a ql 'qlmanage -p'
abbr -a t 'tmux'
abbr -a ta 'type -a'
abbr -a v vim

Add `c3` abbreviation for `cal -3`

abbr -a -- - 'cd -'
abbr -a axel 'axel -a'
abbr -a b 'brew'
abbr -a c 'nix-shell -p clojure --command "clojure -A:rebel -A:cheshire"'
abbr -a c3 'cal -3'
abbr -a dl 'wget -r -l 1 -np -nd'
abbr -a fn 'find . -iname'

abbr -a g git
abbr -a ga git add
abbr -a gap git add --patch
abbr -a gb git branch
abbr -a gc git commit --verbose
abbr -a gco git checkout
abbr -a gd git diff
abbr -a gdc git diff --color-words
abbr -a gds git diff --staged
abbr -a gf git fetch
abbr -a gl git log --graph --decorate
abbr -a gl1 git log -1
abbr -a gll git log \'@\{u\}..\'
abbr -a glr git log \'..@\{u\}\'
abbr -a gr git remote
abbr -a gs git status -sb

abbr -a l 'ls -lahp'
abbr -a le 'less'
abbr -a lx 'less -X'
abbr -a ns 'nix-shell --command fish -p'
abbr -a np 'nix-shell -p'
abbr -a o 'open .'
abbr -a ql 'qlmanage -p'
abbr -a t 'tmux'
abbr -a ta 'type -a'
abbr -a v vim


function yolo
  # Early sudo because it's needed later.
  sudo echo "Updating the entire bloody universe."

  cd ~/.config/nixpkgs; git pull --rebase --autostash; cd -

  if ! set -q DOTFILES_GUEST
    sudo nix-channel --update
    sudo nixos-rebuild switch
  end

  nix-channel --update
  home-manager switch
  nix-env --delete-generations 14d

  if ! set -q DOTFILES_GUEST
    sudo nix-env --delete-generations 14d
    nix-store --gc
    sudo journalctl --vacuum-time=10d
  end

  ~/.config/nvim/sync.sh
end

Add --upgrade to rebuild switch

function yolo
  # Early sudo because it's needed later.
  sudo echo "Updating the entire bloody universe."

  cd ~/.config/nixpkgs; git pull --rebase --autostash; cd -

  if ! set -q DOTFILES_GUEST
    sudo nix-channel --update
    sudo nixos-rebuild switch --upgrade
  end

  nix-channel --update
  home-manager switch
  nix-env --delete-generations 14d

  if ! set -q DOTFILES_GUEST
    sudo nix-env --delete-generations 14d
    nix-store --gc
    sudo journalctl --vacuum-time=10d
  end

  ~/.config/nvim/sync.sh
end


function fish_right_prompt
  if status --is-interactive
    set -l __paradox_date (command date +%I:%M:%S%P ^/dev/null)
    if type -q ruby
      # have to use the echo inline to prevent obnoxious spaces, i.e. (💎 2.3.0 )
      set __paradox_rb_version (echo -s "(💎  " (command ruby -e 'print RUBY_VERSION' ^/dev/null) ")")
    end

    echo -se (set_color blue) "$__paradox_rb_version" (set_color green) (__paradox_command_duration) (set_color normal) "[$__paradox_date]"
  end
end

Update timestamp to actually show meridian state

function fish_right_prompt
  if status --is-interactive
    set -l __paradox_date (command date +%I:%M:%S%p ^/dev/null)
    if type -q ruby
      # have to use the echo inline to prevent obnoxious spaces, i.e. (💎 2.3.0 )
      set __paradox_rb_version (echo -s "(💎  " (command ruby -e 'print RUBY_VERSION' ^/dev/null) ")")
    end

    echo -se (set_color blue) "$__paradox_rb_version" (set_color green) (__paradox_command_duration) (set_color normal) "[$__paradox_date]"
  end
end


# Manages python packages using pip (https://pip.pypa.io/en/stable/).
# Python Package Index (PyPI) https://pypi.python.org/pypi
#
# Installs Powerline for Vim
# https://powerline.readthedocs.io/en/latest/
#
# Sequencing
# - After: brew (installed with python)
function 🐍__pip
    echo "🐍  PIP"
    echo

    # Ensure PIP is installed.
    if not which -s pip3
        error "PIP is not installed."
        return 1
    end

    # # Verify the user owns the site-packages dir.
    # set -l site_packages /usr/local/lib/python2.7/site-packages
    # if test $USER != (fileowner $site_packages)
    #     if status is-login
    #         echo "You must be the owner of "$site_packages" to run this command."
    #     end
    #     return 2
    # end

    set -l global_packages \
        doc2dash \
        lizard \
        powerline-status \
        Pygments \
        # gitstatus segment fork for powerline-status
        'git+https://github.com/phatblat/powerline-gitstatus.git@segment-spacing'

    # Update pip
    pip3 install --upgrade pip setuptools wheel

    # TODO: Uninstall packages
    # TODO: Only install missing packages
    # Install packages
    pip3 install --ignore-installed --upgrade --upgrade-strategy eager $global_packages

    # List installed packages
    pip3 list
end

Change pip3 back to versionless pip

# Manages python packages using pip (https://pip.pypa.io/en/stable/).
# Python Package Index (PyPI) https://pypi.python.org/pypi
#
# Installs Powerline for Vim
# https://powerline.readthedocs.io/en/latest/
#
# Sequencing
# - After: brew (installed with python)
function 🐍__pip
    echo "🐍  PIP"
    echo

    # Ensure PIP is installed.
    if not which -s pip
        error "PIP is not installed."
        return 1
    end

    # # Verify the user owns the site-packages dir.
    # set -l site_packages /usr/local/lib/python2.7/site-packages
    # if test $USER != (fileowner $site_packages)
    #     if status is-login
    #         echo "You must be the owner of "$site_packages" to run this command."
    #     end
    #     return 2
    # end

    set -l global_packages \
        doc2dash \
        lizard \
        powerline-status \
        Pygments \
        # gitstatus segment fork for powerline-status
        'git+https://github.com/phatblat/powerline-gitstatus.git@segment-spacing'

    # Update pip
    pip install --upgrade pip setuptools wheel

    # TODO: Uninstall packages
    # TODO: Only install missing packages
    # Install packages
    pip install --ignore-installed --upgrade --upgrade-strategy eager $global_packages

    # List installed packages
    pip list
end


function fish_title

	set -l process $_
	set -l god ""
	set -l on_project ""
	set -l title ""

	if [ (whoami) = "root" -o $process = "sudo" ]
		set god "⚡ "
	end

	if set -q FISH_TITLE
		set title $FISH_TITLE
	else
		if [ $process = "fish" ]
			set title (prompt_pwd)
		else
			if test (git rev-parse --is-inside-work-tree ^/dev/null)
				set on_project " on "(basename (git rev-parse --show-toplevel))
			end

			if [ $process = "sudo" ]
				set process (echo $history[1] | sed -e 's/^ *//g' -e 's/^sudo *//g' -e 's/\(^[^ ]*\)\(.*\)/\1/g')
			end

			set title $process""$on_project
		end
	end

	echo "$god"(add_padding $title (math 12 - (echo $title | wc -c) ) )

end

Use git_is_repo instead from fisherman/git_util

function fish_title

	set -l process $_
	set -l god ""
	set -l on_project ""
	set -l title ""

	if [ (whoami) = "root" -o $process = "sudo" ]
		set god "⚡ "
	end

	if set -q FISH_TITLE
		set title $FISH_TITLE
	else
		if [ $process = "fish" ]
			set title (prompt_pwd)
		else
			if git_is_repo
				and test -n git_repository_root
				set on_project " on "(basename (git_repository_root))
			end

			if [ $process = "sudo" ]
				set process (echo $history[1] | sed -e 's/^ *//g' -e 's/^sudo *//g' -e 's/\(^[^ ]*\)\(.*\)/\1/g')
			end

			set title $process""$on_project
		end
	end

	echo "$god"(add_padding $title (math 12 - (echo $title | wc -c) ) )

end


function __fresco_remove_plugin
    set -l force_option false

    switch "$argv[1]"
        case ''
            __fresco_log 'ERROR: specify at least one plugin name'
            return 1
        case -f --force
            set force_option true
    end

    set -l plugins $argv[1..-1]
    if eval $force_option
        set plugins $argv[2..-1]
    end

    for plugin in $plugins
        if not contains -- $plugin $fresco_plugins
            __fresco_log "ERROR: `$plugin` is invalid plugin name"
            continue
        end

        for uninstall_fish in (__fresco_plugin_path $plugin)/{functions/,}uninstall.fish
            if test -f $uninstall_fish
                builtin source $uninstall_fish
            end
        end

        if eval $force_option
            if test -e (__fresco_plugin_path $plugin)
                command rm -rf (__fresco_plugin_path $plugin)
                __fresco_log 'Remove ' (__fresco_plugin_path $plugin)
            end
        end

        if command grep "^$plugin" $fresco_plugin_list_path >/dev/null
            string replace '/' '\\/' -- $plugin | read -l escaped_plugin
            set -l fresco_tmp_file /tmp/fresco-(random)
            command sed -e "/^$escaped_plugin\$/d" -- $fresco_plugin_list_path >$fresco_tmp_file
            command mv $fresco_tmp_file $fresco_plugin_list_path
            __fresco_log 'Disable ' $plugin
        end
    end

    __fresco_reload_plugins
end

Use `mktemp` comannd in creating temporary files

function __fresco_remove_plugin
    set -l force_option false

    switch "$argv[1]"
        case ''
            __fresco_log 'ERROR: specify at least one plugin name'
            return 1
        case -f --force
            set force_option true
    end

    set -l plugins $argv[1..-1]
    if eval $force_option
        set plugins $argv[2..-1]
    end

    for plugin in $plugins
        if not contains -- $plugin $fresco_plugins
            __fresco_log "ERROR: `$plugin` is invalid plugin name"
            continue
        end

        for uninstall_fish in (__fresco_plugin_path $plugin)/{functions/,}uninstall.fish
            if test -f $uninstall_fish
                builtin source $uninstall_fish
            end
        end

        if eval $force_option
            if test -e (__fresco_plugin_path $plugin)
                command rm -rf (__fresco_plugin_path $plugin)
                __fresco_log 'Remove ' (__fresco_plugin_path $plugin)
            end
        end

        if command grep "^$plugin" $fresco_plugin_list_path >/dev/null
            string replace '/' '\\/' -- $plugin | read -l escaped_plugin
            set -l fresco_tmp_file (mktemp)
            command sed -e "/^$escaped_plugin\$/d" -- $fresco_plugin_list_path >$fresco_tmp_file
            command mv $fresco_tmp_file $fresco_plugin_list_path
            __fresco_log 'Disable ' $plugin
        end
    end

    __fresco_reload_plugins
end


# Make fish the default shell
set -gx SHELL (which fish);

# Make vim the default editor
set -gx EDITOR "vim";

# Prefer US English and use UTF-8
set -gx LANG        "en_US.UTF-8";
set -gx LC_ALL      "en_US.UTF-8";
set -gx LC_NUMERIC  "es_ES.UTF-8";
set -gx LC_MONETARY "es_ES.UTF-8";
set -gx LC_DATE     "es_ES.UTF-8";

# Highlight section titles in manual pages
set -x LESS_TERMCAP_md (set color magenta);

# Disable history for less
set -x LESSHISTFILE /dev/null

# Don’t clear the screen after quitting a manual page
set -x MANPAGER "less -X";

Make neovim the default editor

# Make fish the default shell
set -gx SHELL (which fish);

# Make nvim the default editor
set -gx EDITOR "nvim";
set -gx VISUAL "nvim";

# Prefer US English and use UTF-8
set -gx LANG        "en_US.UTF-8";
set -gx LC_ALL      "en_US.UTF-8";
set -gx LC_NUMERIC  "es_ES.UTF-8";
set -gx LC_MONETARY "es_ES.UTF-8";
set -gx LC_DATE     "es_ES.UTF-8";

# Highlight section titles in manual pages
set -x LESS_TERMCAP_md (set color magenta);

# Disable history for less
set -x LESSHISTFILE /dev/null

# Don’t clear the screen after quitting a manual page
set -x MANPAGER "less -X";


function thefuck-command-line
  env THEFUCK_REQUIRE_CONFIRMATION=0 thefuck $history[1] ^ /dev/null | read fuck
  [ -z $fuck ]; and return
  commandline -r $fuck
end

Make stderr redirection compatible with Fish 3.0.

function thefuck-command-line
  env THEFUCK_REQUIRE_CONFIRMATION=0 thefuck $history[1] 2> /dev/null | read fuck
  [ -z $fuck ]; and return
  commandline -r $fuck
end


# This file contains aliases which are useful for all instances of fish

alias lsa 'ls -aBhsl'

Add `:q` as alias for `exit`.

# This file contains aliases which are useful for all instances of fish

alias lsa 'ls -aBhsl'

# it's happened enough times
alias :q exit


#!/usr/bin/env fish
# -*-  mode:fish; tab-width:4  -*-
set FLSYM_VFISH "\u2302"

function FLSEG_VFISH

	if set -q VIRTUAL_ENV
		FLINT_CLOSE $FLCLR_VFISH_BG $FLCLR_VFISH_FG
		printf $FLSYM_VFISH" "$VIRTUAL_ENV  | sed 's/\/.*\///; s/^/ /; s/$/ /'
	end

end

Fix VFISH segment printing a newline

#!/usr/bin/env fish
# -*-  mode:fish; tab-width:4  -*-
set FLSYM_VFISH "\u2302"

function FLSEG_VFISH

	if set -q VIRTUAL_ENV
		FLINT_CLOSE $FLCLR_VFISH_BG $FLCLR_VFISH_FG
		printf $FLSYM_VFISH" "(basename $VIRTUAL_ENV)
	end

end


set CLJ_SCRIPTS $HOME/clojure-scripts

mkdir -p ~/bin ~/npm/bin ~/.cargo/bin $CLJ_SCRIPTS/bin

set fish_greeting ""
set LANG en_GB.UTF-8
set PATH ~/bin ~/npm/bin ~/.cargo/bin $CLJ_SCRIPTS/bin $PATH
set BROWSER chromium
set EDITOR nvim
set VISUAL nvim

# Kill all running containers.
alias dockerkill='docker kill (docker ps -q)'

# Delete all docker images and containers.
alias dockernuke='docker rm (docker ps -a -q); docker rmi -f (docker images -q)'

# Other git aliases are in git config
alias g="git"

# Some software still uses vimdiff
alias vimdiff="nvim -d"

# Start an SSH agent if required, if not, connect to it.
initialise_ssh_agent

# Prevent funky output inside emacs terminals.
if test "$TERM" = "eterm-color"
  function fish_title; end
end

# Local config.
if [ -f ~/.local.fish ]
  source ~/.local.fish
end

Remove hints of clojure-scripts, just use the pkg

mkdir -p ~/bin ~/npm/bin ~/.cargo/bin

set fish_greeting ""
set LANG en_GB.UTF-8
set PATH ~/bin ~/npm/bin ~/.cargo/bin $PATH
set BROWSER chromium
set EDITOR nvim
set VISUAL nvim

# Kill all running containers.
alias dockerkill='docker kill (docker ps -q)'

# Delete all docker images and containers.
alias dockernuke='docker rm (docker ps -a -q); docker rmi -f (docker images -q)'

# Other git aliases are in git config
alias g="git"

# Some software still uses vimdiff
alias vimdiff="nvim -d"

# Start an SSH agent if required, if not, connect to it.
initialise_ssh_agent

# Prevent funky output inside emacs terminals.
if test "$TERM" = "eterm-color"
  function fish_title; end
end

# Local config.
if [ -f ~/.local.fish ]
  source ~/.local.fish
end


# GPG agent
function __refresh_gpg_agent_info -d "Reload ~/.gpg-agent-info into environment"
	cat ~/.gpg-agent-info | sed 's/=/ /' | while read key value
		set -e $key
		set -U -x $key "$value"
	end
end

if not set -q -x GPG_AGENT_INFO
	gpg-agent --daemon --write-env-file ~/.gpg-agent-info > /dev/null ^ /dev/null
end

if test -f ~/.gpg-agent-info
	__refresh_gpg_agent_info

	gpg-connect-agent /bye ^/dev/null
	if test $status -eq 1
		pkill -U $USER gpg-agent
		gpg-agent --daemon --write-env-file ~/.gpg-agent-info > /dev/null ^ /dev/null
		__refresh_gpg_agent_info
	end
end

# Use curses based Pinentry
set -x GPG_TTY (tty)

Check if GPG agent is installed.

# GPG agent
function __refresh_gpg_agent_info -d "Reload ~/.gpg-agent-info into environment"
	cat ~/.gpg-agent-info | sed 's/=/ /' | while read key value
		set -e $key
		set -U -x $key "$value"
	end
end

if command -s gpg-agent > /dev/null
	if not set -q -x GPG_AGENT_INFO
		gpg-agent --daemon --write-env-file ~/.gpg-agent-info > /dev/null ^ /dev/null
	end

	if test -f ~/.gpg-agent-info
		__refresh_gpg_agent_info

		gpg-connect-agent /bye ^/dev/null
		if test $status -eq 1
			pkill -U $USER gpg-agent
			gpg-agent --daemon --write-env-file ~/.gpg-agent-info > /dev/null ^ /dev/null
			__refresh_gpg_agent_info
		end
	end

	# Use curses based Pinentry
	set -x GPG_TTY (tty)
end


function yolo
  # Early sudo because it's needed later.
  sudo echo "Updating the entire bloody universe."

  cd ~/.config/nixpkgs; git pull --no-rebase; cd -

  if ! set -q DOTFILES_GUEST
    sudo nix-channel --update
    sudo nixos-rebuild switch
  end

  nix-channel --update
  home-manager switch

  if ! set -q DOTFILES_GUEST
    sudo nix-env --delete-generations 14d
    sudo nix-store --gc
  end

  ~/.config/nvim/sync.sh
end

Tweak my update script for pairing host

function yolo
  # Early sudo because it's needed later.
  sudo echo "Updating the entire bloody universe."

  cd ~/.config/nixpkgs; git pull --no-rebase; cd -

  if ! set -q DOTFILES_GUEST; and ! set -q DOTFILES_JUST_NIX
    sudo nix-channel --update
    sudo nixos-rebuild switch
  end

  nix-channel --update
  home-manager switch
  nix-env --delete-generations 14d

  if ! set -q DOTFILES_GUEST
    if ! set -q DOTFILES_JUST_NIX
      sudo nix-env --delete-generations 14d
    end

    nix-store --gc
  end

  ~/.config/nvim/sync.sh
end


function vcs.dirty
  command hg summary 2>/dev/null | command grep -q 'commit: (clean)' ^/dev/null
end

Make stderr redirection compatible with Fish 3.0.

function vcs.dirty
  command hg summary 2> /dev/null | command grep -q 'commit: (clean)' 2> /dev/null
end


alias gs='git status'
alias ga='git add'
alias gc='git commit'
alias push='git push'
alias pull='git pull'
alias gl='git log -10 --oneline'

Set GOPATH and update PATH for Go installation

alias gs='git status'
alias ga='git add'
alias gc='git commit'
alias push='git push'
alias pull='git pull'
alias gl='git log -10 --oneline'

set -gx GOPATH $HOME/dev/go
set -gx PATH $PATH $HOME/dev/go/bin


alias f 'find -L . -name'
alias p 'ps -ef'
alias pf 'ps -ef | grep'
alias disk-space 'df -h'
alias ipinfo 'curl ipinfo.io'

function find-string -d 'Find string in all files under current directory. http://explainshell.com/explain?cmd=grep+-rnw+.+-H+-e+%24argv '
  grep -rnw . -H -e $argv
end

function does-exist
  return (type $argv > /dev/null)
end

function last-of -d "Find the latest matching file"
  ls -tr | grep $argv | tail -1
end

function check-last -d "Run less on the latest matching file"
  set file (last-of $argv)
  log info 'Checking file:'$file
  less $file
end

function color-test -d 'Print 24-bit colors on the screen'
  curl -s https://raw.githubusercontent.com/gnachman/iTerm2/master/tests/24-bit-color.sh | bash
end

function e -d 'Start the vim with proper permission'
  if test -f $argv # Is a file?
    if test -w $argv # Is writable?
      vim $argv
    else
      sudo vim $argv
    end
  else
    vim $argv
  end
end

function v -d 'View the files'
  less -R $argv
end

Use case ignore for `find-string` utility

alias f 'find -L . -name'
alias p 'ps -ef'
alias pf 'ps -ef | grep'
alias disk-space 'df -h'
alias ipinfo 'curl ipinfo.io'

function find-string -d 'Find string in all files under current directory. http://explainshell.com/explain?cmd=grep+-rnw+.+-H+-e+%24argv '
  grep -rnwi . -H -e $argv
end

function does-exist
  return (type $argv > /dev/null)
end

function last-of -d "Find the latest matching file"
  ls -tr | grep $argv | tail -1
end

function check-last -d "Run less on the latest matching file"
  set file (last-of $argv)
  log info 'Checking file:'$file
  less $file
end

function color-test -d 'Print 24-bit colors on the screen'
  curl -s https://raw.githubusercontent.com/gnachman/iTerm2/master/tests/24-bit-color.sh | bash
end

function e -d 'Start the vim with proper permission'
  if test -f $argv # Is a file?
    if test -w $argv # Is writable?
      vim $argv
    else
      sudo vim $argv
    end
  else
    vim $argv
  end
end

function v -d 'View the files'
  less -R $argv
end


set -gx fish_greeting

env -i -- sh -c ". \"$HOME/.env\" && exec env -u _ -u PWD -u SHLVL" | sed -e 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=\(.*\)/set -gx \1 \2/' | source

switch (uname)
  case 'Darwin'
    set -q $HOMEBREW_PREFIX; and test -x /usr/local/bin/brew; and env SHELL=/bin/fish /usr/local/bin/brew shellenv | source
  case 'Linux'
    set -q $HOMEBREW_PREFIX; and test -x /home/linuxbrew/.linuxbrew/bin/brew; and env SHELL=/bin/fish /home/linuxbrew/.linuxbrew/bin/brew shellenv | source
    set -q $HOMEBREW_PREFIX; and test -x ~/.linuxbrew/bin/brew; and env SHELL=/bin/fish ~/.linuxbrew/bin/brew shellenv | source
end

Simplify sh to fish translation

set -gx fish_greeting

env -i -- sh -c ". \"$HOME/.env\" && exec env -u _ -u PWD -u SHLVL" | sed -e 's/^/set -gx /' -e 's/=/ /' | source

switch (uname)
  case 'Darwin'
    set -q $HOMEBREW_PREFIX; and test -x /usr/local/bin/brew; and env SHELL=/bin/fish /usr/local/bin/brew shellenv | source
  case 'Linux'
    set -q $HOMEBREW_PREFIX; and test -x /home/linuxbrew/.linuxbrew/bin/brew; and env SHELL=/bin/fish /home/linuxbrew/.linuxbrew/bin/brew shellenv | source
    set -q $HOMEBREW_PREFIX; and test -x ~/.linuxbrew/bin/brew; and env SHELL=/bin/fish ~/.linuxbrew/bin/brew shellenv | source
end


#!/usr/bin/env fish

set -l asdf_dir (dirname (status -f))

# we get an ugly warning when setting the path if shims does not exist
mkdir -p $asdf_dir/shims

if not contains $asdf_dir/{bin,shims} $PATH
and test -d $asdf/{bin,shims}
  set -gx PATH $asdf_dir/{bin,shims} $PATH
end

Fix issue with Fish shell shim loading script

#!/usr/bin/env fish

set -l asdf_dir (dirname (status -f))

# we get an ugly warning when setting the path if shims does not exist
mkdir -p $asdf_dir/shims

for x in $asdf_dir/{bin,shims}
  if not contains $x $PATH
  and test -d $x
    set -gx PATH $x $PATH
  end
end


set -g fish_greeting ''

set -x EDITOR (which vim)
set -x NODE_PATH /usr/local/lib/node_modules
set -x PATH /usr/local/bin $PATH
set -x PATH /usr/local/sbin $PATH
set -x PATH $HOME/bin $PATH

source ~/.iterm2_shell_integration.(basename $SHELL)
status --is-interactive; and source (rbenv init -|psub)

Add Postgres to the path.

set -g fish_greeting ''

set -x EDITOR (which vim)
set -x NODE_PATH /usr/local/lib/node_modules
set -x PATH /usr/local/bin $PATH
set -x PATH /usr/local/sbin $PATH
set -x PATH $HOME/bin $PATH
set -x PATH /Applications/Postgres.app/Contents/Versions/latest/bin $PATH

source ~/.iterm2_shell_integration.(basename $SHELL)
status --is-interactive; and source (rbenv init -|psub)


function create-instance --argument vpc name
    trace (status --current-filename) $argv

    if empty "$vpc" "$name"
        usage create-instance '<vpc>' '<name>'
        return (false)
    end

    set instance "vpcs/$vpc/instances/$name"

    if has $name vpcs/$vpc/instances
        for property in (get $instance | grep -vE '(tags|user-data)' )
            set options $options --$property (get $instance/$property)
        end

        if has user-data $instance
            set options $options --user-data file://$instance/user-data
        end

        aws ec2 run-instances $options | jq --raw-output .Instances[].InstanceId//empty
    else
        return 1
    end
end


set -g fish_color_user green --bold
set -g fish_color_host cyan --bold
set -g fish_color_cwd normal
#set -g fish_color_git_path yellow

function fish_prompt --description "Write out the prompt"
  set -l last_status $status

  # User
  if not test $last_status -eq 0
    set_color $fish_color_error
  end
  echo -n '┌'
  set_color $fish_color_user
  echo -n (whoami)
  set_color normal

  echo -n '@'

  # Host
  set_color $fish_color_host
  echo -n (hostname)
  set_color normal

  echo -n ':'

  # PWD
  __color_git_pwd
  __terlar_git_prompt
  echo

  if not test $last_status -eq 0
    set_color $fish_color_error
  end

  echo -n '└➤ '
  set_color normal
end

function fish_right_prompt --description "Write out the right prompt"
  date +"[%T]"
end

Add new color for Docker host or CONTAINER_NAME environment variable

set -g fish_color_user green --bold
set -g fish_color_host cyan --bold
set -g fish_color_container_name yellow --bold
set -g fish_color_cwd normal
#set -g fish_color_git_path yellow

function fish_prompt --description "Write out the prompt"
  set -l last_status $status

  # User
  if not test $last_status -eq 0
    set_color $fish_color_error
  end
  echo -n '┌'
  set_color $fish_color_user
  echo -n (whoami)
  set_color normal

  echo -n '@'

  # Host
  if [ -f /.dockerenv ]
    set_color $fish_color_container_name
  else
    set_color $fish_color_host
  end
  if set -qx CONTAINER_NAME
    echo -n $CONTAINER_NAME
  else
    echo -n (hostname)
  end
  set_color normal

  echo -n ':'

  # PWD
  __color_git_pwd
  __terlar_git_prompt
  echo

  if not test $last_status -eq 0
    set_color $fish_color_error
  end

  echo -n '└➤ '
  set_color normal
end

function fish_right_prompt --description "Write out the right prompt"
  date +"[%T]"
end


bind \e\[1\;5C forward-word
bind \e\[1\;5D backward-word

# aliases
alias ..='cd ..'
alias b='bundle'
alias bs='bundle exec rails server'
alias bake='bundle exec rake'
alias gs='git status'
alias gst='git stash'
alias gsa='git stash apply'
alias gd='git diff'

Add ~/bin to my fish PATH.

bind \e\[1\;5C forward-word
bind \e\[1\;5D backward-word

# aliases
alias ..='cd ..'
alias b='bundle'
alias bs='bundle exec rails server'
alias bake='bundle exec rake'
alias gs='git status'
alias gst='git stash'
alias gsa='git stash apply'
alias gd='git diff'

# path
set PATH ~/bin $PATH


# name: GitStatus
# Find latest version from: https://github.com/godfat/fish_prompt-gitstatus

function _git_branch_name
  echo (command git symbolic-ref HEAD ^/dev/null | sed -e 's|^refs/heads/||')
end

function _git_status_symbol
  set -l git_status (git status --porcelain ^/dev/null)
  if test -n "$git_status"
    # Is there anyway to preserve newlines so we can reuse $git_status?
    if git status --porcelain ^/dev/null | grep '^.[^ ]' >/dev/null
      echo '*' # dirty
    else
      echo '#' # all staged
    end
  else
    echo    '' # clean
  end
end

function _remote_hostname
  if test -n "$SSH_CONNECTION"
    echo (whoami)@(hostname)
  end
end

function fish_prompt
  set -l cyan (set_color cyan)
  set -l normal (set_color normal)

  set -l cwd (set_color $fish_color_cwd)(prompt_pwd)
  set -l git_status (_git_status_symbol)(_git_branch_name)

  if test -n "$git_status"
    set git_status " $git_status"
  end

  echo -n (_remote_hostname) $cwd$cyan$git_status$normal'> '
end

Make stderr redirection compatible with Fish 3.0.

# name: GitStatus
# Find latest version from: https://github.com/godfat/fish_prompt-gitstatus

function _git_branch_name
  echo (command git symbolic-ref HEAD 2> /dev/null | sed -e 's|^refs/heads/||')
end

function _git_status_symbol
  set -l git_status (git status --porcelain 2> /dev/null)
  if test -n "$git_status"
    # Is there anyway to preserve newlines so we can reuse $git_status?
    if git status --porcelain 2> /dev/null | grep '^.[^ ]' >/dev/null
      echo '*' # dirty
    else
      echo '#' # all staged
    end
  else
    echo    '' # clean
  end
end

function _remote_hostname
  if test -n "$SSH_CONNECTION"
    echo (whoami)@(hostname)
  end
end

function fish_prompt
  set -l cyan (set_color cyan)
  set -l normal (set_color normal)

  set -l cwd (set_color $fish_color_cwd)(prompt_pwd)
  set -l git_status (_git_status_symbol)(_git_branch_name)

  if test -n "$git_status"
    set git_status " $git_status"
  end

  echo -n (_remote_hostname) $cwd$cyan$git_status$normal'> '
end


function fish_title
  [ "$theme_title_display_process" = 'yes' ]; and echo $_ ' '
  [ "$theme_title_display_path" != 'no' ]; and pwd
end

Use a compact path in the title.

function fish_title
  [ "$theme_title_display_process" = 'yes' ]; and echo $_ ' '
  [ "$theme_title_display_path" != 'no' ]; and prompt_pwd
end


alias _r "exec fish"
if which pacaur >/dev/null ^/dev/null
	abbr p "pacaur"
else if which pacman >/dev/null ^/dev/null
	abbr p "pacman"
end

if which exa >/dev/null ^/dev/null
	abbr l "exa -F --group-directories-first"
	abbr ll "exa -lF --git --group-directories-first"
else
	abbr l "ls --group-directories-first"
	abbr ll "ls -l --group-directories-first"
end
abbr la "l -a"
abbr lla "ll -a"

abbr f "fd"
abbr r "ranger"
abbr rs "rsync"

abbr e "$EDITOR"
abbr ee "$VISUAL"
abbr em "emacs"
abbr ec "emacsclient"

abbr v "vim"
abbr n "nvim"

abbr m "ncmpcpp"

abbr o "xdg-open"

abbr λ "ghci"

abbr py "python"
abbr ipy "ipython"

alias clipCopy "xclip -sel clip"
alias clipPaste "xclip -o"
alias clipLength "clipPaste | wc"

abbr sc "systemctl"
abbr scu "systemctl  --user"

Stop using `--git` on exa

alias _r "exec fish"
if which pacaur >/dev/null ^/dev/null
	abbr p "pacaur"
else if which pacman >/dev/null ^/dev/null
	abbr p "pacman"
end

if which exa >/dev/null ^/dev/null
	abbr l "exa -F --group-directories-first"
	abbr ll "exa -lF --group-directories-first"
else
	abbr l "ls --group-directories-first"
	abbr ll "ls -l --group-directories-first"
end
abbr la "l -a"
abbr lla "ll -a"

abbr f "fd"
abbr r "ranger"
abbr rs "rsync"

abbr e "$EDITOR"
abbr ee "$VISUAL"
abbr em "emacs"
abbr ec "emacsclient"

abbr v "vim"
abbr n "nvim"

abbr m "ncmpcpp"

abbr o "xdg-open"

abbr λ "ghci"

abbr py "python"
abbr ipy "ipython"

alias clipCopy "xclip -sel clip"
alias clipPaste "xclip -o"
alias clipLength "clipPaste | wc"

abbr sc "systemctl"
abbr scu "systemctl  --user"


# Language
set -gx LANGUAGE en_US.UTF-8
set -gx LANG $LANGUAGE
set -gx LC_ALL $LANGUAGE
set -gx LC_CTYPE $LANGUAGE

# Editor
set -gx EDITOR vim
set -gx CVSEDITOR $EDITOR
set -gx SVN_EDITOR $EDITOR
set -gx GIT_EDITOR $EDITOR

# Pager
set -gx PAGER less

# XDG
set -gx XDG_CACHE_HOME $HOME/.cache
set -gx XDG_CONFIG_HOME $HOME/.config
set -gx XDG_DATA_HOME $HOME/.local/share

# Golang
set -gx GOPATH $HOME/work
set -gx PATH $PATH $GOPATH/bin

# fzf
set -gx FZF_DEFAULT_OPTS --reverse
set -gx FZF_LEGACY_KEYBINDINGS 1
set -gx FZF_TMUX 1

# ghq
set -gx GHQ_SELECTOR fzf

# nodebrew
set -gx PATH $HOME/.nodebrew/current/bin $PATH

# rbenv
rbenv init - | source

# pyenv
status --is-interactive; and source (pyenv init -|psub)

# direnv
eval (direnv hook fish)

# Aliases
alias be "bundle exec"
alias bi "bundle install"
alias bo "bundle open"
alias bu "bundle update"
alias du "du -h"
alias g git
alias r rails
alias vi vim

Remove unnecessary setting on fish

# Language
set -gx LANGUAGE en_US.UTF-8
set -gx LANG $LANGUAGE
set -gx LC_ALL $LANGUAGE
set -gx LC_CTYPE $LANGUAGE

# Editor
set -gx EDITOR vim
set -gx CVSEDITOR $EDITOR
set -gx SVN_EDITOR $EDITOR
set -gx GIT_EDITOR $EDITOR

# Pager
set -gx PAGER less

# XDG
set -gx XDG_CACHE_HOME $HOME/.cache
set -gx XDG_CONFIG_HOME $HOME/.config
set -gx XDG_DATA_HOME $HOME/.local/share

# Golang
set -gx GOPATH $HOME/work
set -gx PATH $PATH $GOPATH/bin

# fzf
set -gx FZF_DEFAULT_OPTS --reverse
set -gx FZF_LEGACY_KEYBINDINGS 1
set -gx FZF_TMUX 1

# ghq
set -gx GHQ_SELECTOR fzf

# nodebrew
set -gx PATH $HOME/.nodebrew/current/bin $PATH

# direnv
eval (direnv hook fish)

# Aliases
alias be "bundle exec"
alias bi "bundle install"
alias bo "bundle open"
alias bu "bundle update"
alias du "du -h"
alias g git
alias r rails
alias vi vim


function get_git_status -d "Gets the current git status"
  if command git rev-parse --is-inside-work-tree >/dev/null 2>&1
    set -l dirty (command git status -s --ignore-submodules=dirty | wc -l | sed -e 's/^ *//' -e 's/ *$//' 2> /dev/null)
    set -l ref (command git symbolic-ref --short HEAD 2> /dev/null ; or command git rev-parse --short HEAD 2> /dev/null)

    if [ "$dirty" != "0" ]
      set_color -b normal
      set_color red
      echo "$dirty changed file"
      if [ "$dirty" != "1" ]
        echo "s"
      end
      echo " "
      set_color -b red
      set_color white
    else
      set_color -b cyan
      set_color white
    end

    echo " $ref "
    set_color normal
   end
end

function fish_right_prompt -d "Prints right prompt"
  get_git_status
end

Add tag name in ref

function get_git_status -d "Gets the current git status"
  if command git rev-parse --is-inside-work-tree >/dev/null 2>&1
    set -l dirty (command git status -s --ignore-submodules=dirty | wc -l | sed -e 's/^ *//' -e 's/ *$//' 2> /dev/null)
    set -l ref (command git describe --tags --exact-match ^/dev/null ; or command git symbolic-ref --short HEAD 2> /dev/null ; or command git rev-parse --short HEAD 2> /dev/null)

    if [ "$dirty" != "0" ]
      set_color -b normal
      set_color red
      echo "$dirty changed file"
      if [ "$dirty" != "1" ]
        echo "s"
      end
      echo " "
      set_color -b red
      set_color white
    else
      set_color -b cyan
      set_color white
    end

    echo " $ref "
    set_color normal
   end
end

function fish_right_prompt -d "Prints right prompt"
  get_git_status
end


Add function to show char indexes in a string

function char-index -d "Prints character indexes of the given strings"
    set --local argc (count $argv)

    for arg_i in (seq $argc)
        set --local chars (string split '' $argv[$arg_i])
        for i in (seq (count $chars))
            echo $i: $chars[$i]
        end

        test $arg_i -lt $argc
        and echo
    end
end


function tmux::autostart
  if not command --search --quiet "tmux"
    return
  end

  if test -n "$SSH_TTY" -o -n "$TMUX" -o -n "$EMACS" -o -n "$VIM"
    return
  end

  set name $argv[1]

  tmux start-server
  if not tmux has-session ^ /dev/null
    tmux new-session -d -s $name
    tmux set-option -t $name destroy-unattached off > /dev/null ^ /dev/null
  end

  exec tmux attach-session
end


Add script to ease switch between Vagrant projects

#!/usr/bin/fish
function vhup -d "Halts current vagrant, ups another"
    if test (count $argv) -lt 1
        echo "Syntax: vhup <project>"
        echo "Must specify project name to switch to."
    else
        set -l project ~/dev/$argv[1]
        if test -f $project/Vagrantfile
            vagrant halt; and cd $project; and vagrant up
        else
            echo "Could not find Vagrant project $project"
        end
    end
end


function fish_right_prompt
  if status --is-interactive
    set -l __paradox_date (command date +%I:%M:%S%P ^/dev/null)
    if type ruby >/dev/null ^/dev/null
      # have to use the echo inline to prevent obnoxious spaces, i.e. (💎2.3.0 )
      set __paradox_rb_version (echo -s "(💎  " (command ruby -e 'print RUBY_VERSION' ^/dev/null) ")")
    end

    # The \e[1A code below is to move the prompt up a line, so it aligns with the first line of the lprompt.
    # The \e[1B code resets to the previous line, so everything renders properly
    echo -se "\e[1A" (set_color blue) "$__paradox_rb_version" (set_color green) (__paradox_command_duration) (set_color normal) "[$__paradox_date]"  "\e[1B"
  end
end

Remove cursor control characters from right prompt

function fish_right_prompt
  if status --is-interactive
    set -l __paradox_date (command date +%I:%M:%S%P ^/dev/null)
    if type ruby >/dev/null ^/dev/null
      # have to use the echo inline to prevent obnoxious spaces, i.e. (💎 2.3.0 )
      set __paradox_rb_version (echo -s "(💎  " (command ruby -e 'print RUBY_VERSION' ^/dev/null) ")")
    end

    echo -se (set_color blue) "$__paradox_rb_version" (set_color green) (__paradox_command_duration) (set_color normal) "[$__paradox_date]"
  end
end


set -l repo_path $HOME/github.com/gh_user/gh_repo

function setup -S
  mkdir -p $repo_path
end

function teardown -S
  rm -rf (dirname $repo_path)
end

test "navigates to existing directory when given user repo"
  (
    gh gh_user gh_repo
    pwd
  ) = "$HOME/github.com/gh_user/gh_repo"
end

test "navigates to existing directory when given user/repo"
  (
    gh gh_user/gh_repo
    pwd
  ) = "$HOME/github.com/gh_user/gh_repo"
end

test "navigates to existing directory when given user"
  (
    gh gh_user
    pwd
  ) = "$HOME/github.com/gh_user"
end

Swap expected and actual in tests

set -l repo_path $HOME/github.com/gh_user/gh_repo

function setup -S
  mkdir -p $repo_path
end

function teardown -S
  rm -rf (dirname $repo_path)
end

test "navigates to existing directory when given user repo"
  "$HOME/github.com/gh_user/gh_repo" = (
    gh gh_user gh_repo
    pwd
  )
end

test "navigates to existing directory when given user/repo"
  "$HOME/github.com/gh_user/gh_repo" = (
    gh gh_user/gh_repo
    pwd
  )
end

test "navigates to existing directory when given user"
  "$HOME/github.com/gh_user" = (
    gh gh_user
    pwd
  )
end


# fish theme : deference

function __prompt_git_branch
    command git symbolic-ref --short HEAD ^/dev/null
end

function prompt_git
    set -l branch (__prompt_git_branch)
    if [ -z $branch ]
        return
    end

    echo '['$branch']'
end

function prompt_rbenv
    if not type -q 'rbenv'
        return
    end

    set -l rbenv_version (rbenv version-name)

    if type -q 'rbenv-gemset'
        set -l rbenv_gemset (rbenv gemset active ^/dev/null | sed 's| global||')
        if [ -n $rbenv_gemset ]
            set rbenv_version $rbenv_version'/'$rbenv_gemset
        end
    end

    echo '('$rbenv_version')'
end

function fish_prompt
    set_color brblack
    echo (prompt_pwd) (prompt_git) (prompt_rbenv)
    echo -n '$ '
    set_color normal
end


function _prompt_dir_component
  _prompt_wrap_text (prompt_pwd) brblue
end

function _prompt_err_component --argument-names {error_code}
  if [ $error_code -ne 0 ]
    _prompt_wrap_text $error_code brred
  end
end

function _prompt_git_component
  if __fish_is_git_repository
    set --local sha (git rev-parse HEAD)
    set --local ref (git show-ref --tags --heads | grep $sha)

    set --local parts ''
    if set -q ref
      set parts (string split / -- $ref)
    else
      set parts null detached $sha
    end

    switch $parts[2]
    case heads
      _prompt_wrap_text $parts[3] green
    case tags
      _prompt_wrap_text $parts[3] yellow
    case detached
      _prompt_wrap_text (git rev-parse --short $sha) brred
    end
  end
end

function _prompt_wrap_text --argument-names {text,color}
  set_color normal
  echo -n "["
  set_color --bold $color
  echo -n $text
  set_color normal
  echo -n "]"
end

function fish_prompt
  set --local error_code $status
  set --local err (_prompt_err_component $error_code)
  set --local git (_prompt_git_component)
  set --local dir (_prompt_dir_component)
  echo "$git$dir$err "
end

Fix case when on a new branch with no additional changes

function _prompt_dir_component
  _prompt_wrap_text (prompt_pwd) brblue
end

function _prompt_err_component --argument-names {error_code}
  if [ $error_code -ne 0 ]
    _prompt_wrap_text $error_code brred
  end
end

function _prompt_git_component
  if __fish_is_git_repository
    set --local sha (git rev-parse HEAD)
    set --local branch (git rev-parse --abbrev-ref HEAD)

    set --local info ''
    if [ $branch = HEAD ]
      set --local ref (git show-ref --tags | grep $sha)

      if set -q ref
        set --local parts (string split / -- $ref)
        set info tag $parts[3]
      else
        set info detached $sha
      end
    else
      set info branch $branch
    end

    switch $info[1]
    case branch
      _prompt_wrap_text $info[2] green
    case tag
      _prompt_wrap_text $info[2] yellow
    case detached
      _prompt_wrap_text (git rev-parse --short $sha) brred
    end
  end
end

function _prompt_wrap_text --argument-names {text,color}
  set_color normal
  echo -n "["
  set_color --bold $color
  echo -n $text
  set_color normal
  echo -n "]"
end

function fish_prompt
  set --local error_code $status
  set --local err (_prompt_err_component $error_code)
  set --local git (_prompt_git_component)
  set --local dir (_prompt_dir_component)
  echo "$git$dir$err "
end


# You can override some default title options in your config.fish:
#     set -g theme_date_format "+%a %H:%M"

function fish_right_prompt -d 'bobthefish is all about the right prompt'
  set_color $fish_color_autosuggestion[1]
  set -q theme_date_format; or set -l theme_date_format "+%c"
  date $theme_date_format
  set_color normal
end

Add last command duration to the right prompt.

# You can override some default right prompt options in your config.fish:
#     set -g theme_date_format "+%a %H:%M"

function __bobthefish_cmd_duration -S -d 'Show command duration'
  [ "$CMD_DURATION" -lt 100 ]; and return

  if [ "$CMD_DURATION" -lt 5000 ]
    echo -ns $CMD_DURATION 'ms '
  else if [ "$CMD_DURATION" -lt 60000 ]
    echo -ns (echo "scale=1;$CMD_DURATION/1000" | bc | sed 's/.0//') 's '
  else if [ "$CMD_DURATION" -lt 3600000 ]
    set_color $fish_color_error
    echo -ns (echo "scale=1;$CMD_DURATION/60000" | bc | sed 's/.0//') 'm '
  else
    set_color $fish_color_error
    echo -ns (echo "scale=1;$CMD_DURATION/3600000" | bc | sed 's/.0//') 'h '
  end

  set_color $fish_color_autosuggestion[1]
  echo -n $__bobthefish_left_arrow_glyph
end

function __bobthefish_timestamp -S -d 'Show the current timestamp'
  set -q theme_date_format; or set -l theme_date_format "+%c"
  echo -n ' '
  date $theme_date_format
end

function fish_right_prompt -d 'bobthefish is all about the right prompt'
  set -l __bobthefish_left_arrow_glyph \uE0B3

  set_color $fish_color_autosuggestion[1]

  __bobthefish_cmd_duration
  __bobthefish_timestamp
end


########## env ##########

##### xdg #####
set -q XDG_CONFIG_HOME
or set -l XDG_CONFIG_HOME ~/.config

##### locale #####
set -gx LANG en_US.UTF-8

##### term #####
set -gx TERM xterm-256color

##### path #####
set -l local_paths /usr/local/{sbin,bin} /usr/{sbin,bin} /{sbin,bin}

# go
set -gx GOPATH $HOME/dev
set local_paths $GOPATH/bin $local_paths

# rust
set local_paths ~/.cargo/bin $local_paths

# pyenv
set local_paths ~/.pyenv/{bin,shims} $local_paths

# rbenv
set local_paths ~/.rbenv/{bin,shims} $local_paths

# update PATH via fish_user_paths
set -g fish_user_paths $local_paths

##### misc #####
set -gx GHQ_ROOT $GOPATH/src
set -gx TMUX_PLUGIN_MANAGER_PATH $XDG_CONFIG_HOME/tmux/plugins/

########## alias ##########

alias e 'emacsclient -nw -a ""'
alias ekill 'emacsclient -e "(kill-emacs)"'
alias g 'git'
alias fzf 'fzf-tmux'

########## plugins ##########

if not functions -q fisher
    curl https://git.io/fisher --create-dirs -sLo $XDG_CONFIG_HOME/fish/functions/fisher.fish
    fish -c fisher
end

Integrate `local` and `term` settings into `mics`

########## env ##########

##### xdg #####
set -q XDG_CONFIG_HOME
or set -l XDG_CONFIG_HOME ~/.config

##### path #####
set -l local_paths /usr/local/{sbin,bin} /usr/{sbin,bin} /{sbin,bin}

# go
set -gx GOPATH $HOME/dev
set local_paths $GOPATH/bin $local_paths

# rust
set local_paths ~/.cargo/bin $local_paths

# pyenv
set local_paths ~/.pyenv/{bin,shims} $local_paths

# rbenv
set local_paths ~/.rbenv/{bin,shims} $local_paths

# update PATH via fish_user_paths
set -g fish_user_paths $local_paths

##### misc #####
set -gx LANG en_US.UTF-8
set -gx TERM xterm-256color
set -gx GHQ_ROOT $GOPATH/src
set -gx TMUX_PLUGIN_MANAGER_PATH $XDG_CONFIG_HOME/tmux/plugins/

########## alias ##########

alias e 'emacsclient -nw -a ""'
alias ekill 'emacsclient -e "(kill-emacs)"'
alias g 'git'
alias fzf 'fzf-tmux'

########## plugins ##########

if not functions -q fisher
    curl https://git.io/fisher --create-dirs -sLo $XDG_CONFIG_HOME/fish/functions/fisher.fish
    fish -c fisher
end


# Aliases
alias ll="exa -lg --group-directories-first"
alias csvcol="column -s, -t"
alias open-rust-doc="open /usr/share/doc/rust/html/index.html"

abbr --add g git
abbr --add v nvim
abbr --add tree "ll --tree"

set -gx VIRTUAL_ENV_DISABLE_PROMPT 1

set -p PATH ~/.cargo/bin
set -a PATH ~/.local/bin
set -a PATH ~/.emacs.d/bin
set -a PATH ~/.ghcup/bin
set -a PATH ~/.cabal/bin
set -a PATH ~/Documents/go/bin
set -a PATH ~/.local/share/npm/bin

set -x GOPATH "$HOME/Documents/go"

set -x VISUAL /usr/bin/nvim
set -x EDITOR /usr/bin/nvim

set -x OSTYPE linux

eval (direnv hook fish)

Set tmux pane title on ssh

# Aliases
alias ll="exa -lg --group-directories-first"
alias csvcol="column -s, -t"
alias open-rust-doc="open /usr/share/doc/rust/html/index.html"

abbr --add g git
abbr --add v nvim
abbr --add tree "ll --tree"

set -gx VIRTUAL_ENV_DISABLE_PROMPT 1

set -p PATH ~/.cargo/bin
set -a PATH ~/.local/bin
set -a PATH ~/.emacs.d/bin
set -a PATH ~/.ghcup/bin
set -a PATH ~/.cabal/bin
set -a PATH ~/Documents/go/bin
set -a PATH ~/.local/share/npm/bin

set -x GOPATH "$HOME/Documents/go"

set -x VISUAL /usr/bin/nvim
set -x EDITOR /usr/bin/nvim

set -x OSTYPE linux

eval (direnv hook fish)

function tmux-set-pane-title
    if test -n $TMUX
        printf "\033]2;%s\033\ \n" "$argv"
    end
end

function ssh
  tmux-set-pane-title "$argv"
  command ssh $argv
  tmux-set-pane-title (hostname)
end


set -x PATH $PATH $HOME/.dotfiles/scripts

# aliases
alias vim 'nvim'
alias tmux-reload 'tmux source-file ~/.tmux.conf'
alias git 'hub'
alias bnode 'babel-node'
alias em 'emacs'
alias psp 'psc-package'

# settings
set -x EDITOR nvim
set -x TERM xterm-256color
set -e fish_greeting
set -x LESS '-R'

# path
set -x PATH /usr/local/bin $PATH
set -x PATH $HOME/.pyenv/shims $PATH
set -x PATH $PATH $HOME/bin
set -x PATH $PATH $HOME/.local/bin
set -x PATH $PATH $HOME/.stack/programs/x86_64-osx/ghc-8.0.1/bin
set -x PATH $PATH ./node_modules/.bin

# fnm
status --is-interactive; and fnm 6

# lang
set -x LC_ALL en_US.UTF-8
set -x LC_CTYPE en_US.UTF-8

# tmux
function tm
  tmux-status
  if test $status -eq 0
    exec tmux
  end
end

Use 'tmux' instead of 'exec tmux'

set -x PATH $PATH $HOME/.dotfiles/scripts

# aliases
alias vim 'nvim'
alias tmux-reload 'tmux source-file ~/.tmux.conf'
alias git 'hub'
alias bnode 'babel-node'
alias em 'emacs'
alias psp 'psc-package'

# settings
set -x EDITOR nvim
set -x TERM xterm-256color
set -e fish_greeting
set -x LESS '-R'

# path
set -x PATH /usr/local/bin $PATH
set -x PATH $HOME/.pyenv/shims $PATH
set -x PATH $PATH $HOME/bin
set -x PATH $PATH $HOME/.local/bin
set -x PATH $PATH $HOME/.stack/programs/x86_64-osx/ghc-8.0.1/bin
set -x PATH $PATH ./node_modules/.bin

# fnm
status --is-interactive; and fnm 6

# lang
set -x LC_ALL en_US.UTF-8
set -x LC_CTYPE en_US.UTF-8

# tmux
function tm
  tmux-status
  if test $status -eq 0
    tmux
  end
end


# enhancd
set -x ENHANCD_DISABLE_DOT 1
set -x ENHANCD_DISABLE_HYPHEN 1

# Git
set -x GIT_EDITOR 'vim'
# This can be overridden on a per-project basis using direnv
set -x GIT_PRIMARY_BRANCH 'master'
set -x SCMPUFF_GIT_CMD (which hub)

# GPG
# https://unix.stackexchange.com/questions/217737/pinentry-fails-with-gpg-agent-and-ssh
set -x GPG_TTY '/usr/bin/tty'
set -x SSH_AUTH_SOCK "$HOME/.gnupg/S.gpg-agent.ssh"

# Micro editor
set -x MICRO_TRUECOLOR 1

# SND
set -x SND "$HOME/Music/0-sounds-0"
set -x SNDS "$HOME/Music/0-sounds-0/-- samples --"
set -x SNDBACKUPS "$HOME/Music/0-sounds-0/--- backup ---"

# nvm
set -x NODE_VERSIONS ~/.nvm/versions/node/
set -x NODE_VERSION_PREFIX 'v'

Use emacs as git editor in terminal

# enhancd
set -x ENHANCD_DISABLE_DOT 1
set -x ENHANCD_DISABLE_HYPHEN 1

# Git
set -x GIT_EDITOR 'emacs -nw'
# This can be overridden on a per-project basis using direnv
set -x GIT_PRIMARY_BRANCH 'master'
set -x SCMPUFF_GIT_CMD (which hub)

# GPG
# https://unix.stackexchange.com/questions/217737/pinentry-fails-with-gpg-agent-and-ssh
set -x GPG_TTY '/usr/bin/tty'
set -x SSH_AUTH_SOCK "$HOME/.gnupg/S.gpg-agent.ssh"

# Micro editor
set -x MICRO_TRUECOLOR 1

# SND
set -x SND "$HOME/Music/0-sounds-0"
set -x SNDS "$HOME/Music/0-sounds-0/-- samples --"
set -x SNDBACKUPS "$HOME/Music/0-sounds-0/--- backup ---"

# nvm
set -x NODE_VERSIONS ~/.nvm/versions/node/
set -x NODE_VERSION_PREFIX 'v'


# Here is the configuration for the fish shell

source ~/deoxys314_dotfiles/fish/aliases.fish

source ~/deoxys314_dotfiles/fish/functions.fish

mkdir -pv ~/bin

set PATH $PATH ~/bin

# important environmental variables
# set -g -x TERM screen-256color-bce

set -gx VISUAL vi
set -gx EDITOR vi

Remove old comments and junk code.

# Here is the configuration for the fish shell

source ~/deoxys314_dotfiles/fish/aliases.fish

source ~/deoxys314_dotfiles/fish/functions.fish

mkdir -pv ~/bin

set PATH $PATH ~/bin

set -gx VISUAL vi
set -gx EDITOR vi


#
# omf/bobthefish
#

set -g theme_nerd_fonts yes
set -g theme_display_user yes
set -g fish_prompt_pwd_dir_length 0
set -g theme_color_scheme zenburn
set -g theme_newline_cursor yes

Disable displaying date in prompt

#
# tsub/theme-bobthefish forked by omf/bobthefish
#

set -g theme_nerd_fonts yes
set -g theme_display_user yes
set -g fish_prompt_pwd_dir_length 0
set -g theme_color_scheme zenburn
set -g theme_newline_cursor yes
set -g theme_display_date no


# Copy SSH public key to general pasteboard.
function sshcopypub --description "Copy SSH public key to general pasteboard."
    pbcopy < ~/.ssh/id_rsa.pub
end

Use xsel on linux to copy

function sshcopypub \
        --description "Copy SSH public key to general pasteboard."
    if is_mac
        pbcopy < ~/.ssh/id_rsa.pub
    else if is_linux
        xsel --clipboard < ~/.ssh/id_rsa.pub
    end
end


function __fish_kdb_complete --description 'Print a list of kdb subcommands'
    kdb list-commands -v | awk '{if(NR>1)print}'
end

complete --command kdb --exclusive --arguments '(__fish_kdb_complete)'

Use short options in Fish completions

function __fish_kdb_complete -d 'Print a list of kdb subcommands'
    kdb list-commands -v | awk '{if(NR>1)print}'
end

complete -c kdb -x -a '(__fish_kdb_complete)'


# Path to Oh My Fish install.
set -gx OMF_PATH "/home/e4r7hbug/.local/share/omf"

# Customize Oh My Fish configuration path.
#set -gx OMF_CONFIG "/home/e4r7hbug/.config/omf"

# Load oh-my-fish configuration.
source $OMF_PATH/init.fish

fish_vi_mode

set PATH \
    "$HOME/bin" \
    "$HOME/.local/bin" \
    "$HOME/Library/Python/2.7/bin" \
    "$HOME/go/bin" \
        $PATH

if test -d "$HOME/go"
    set -x GOPATH "$HOME/go"
end

source /usr/share/autojump/autojump.fish

Set GOPATH, go will create if missing

# Path to Oh My Fish install.
set -gx OMF_PATH "/home/e4r7hbug/.local/share/omf"

# Customize Oh My Fish configuration path.
#set -gx OMF_CONFIG "/home/e4r7hbug/.config/omf"

# Load oh-my-fish configuration.
source $OMF_PATH/init.fish

fish_vi_mode

set PATH \
    "$HOME/bin" \
    "$HOME/.local/bin" \
    "$HOME/Library/Python/2.7/bin" \
    "$HOME/go/bin" \
        $PATH

set -x GOPATH "$HOME/go"

source /usr/share/autojump/autojump.fish


alias gs 'git status -s'
alias gp 'git pull'
alias gb 'git branch --color --all -vv'
alias gr 'git remote -vv'
alias gc 'git checkout'
alias gd 'git diff'
alias gdd 'git diff --cached'
alias gf 'git fetch'
alias gclean 'git clean -df; and git checkout -- .'

function git-list-unstaged-files
  git ls-files --others --exclude-standard
end

function gl -d 'Git show log'
	git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
end

alias current-branch 'git rev-parse --abbrev-ref HEAD'
alias all-branches 'git branch | cut -c 3-'

function git-delete-remote-branch -d 'Delete a remote branch'
  git push $argv[1] --delete $argv[2]
end

Add `gll` to show detailed logs

alias gs 'git status -s'
alias gp 'git pull'
alias gb 'git branch --color --all -vv'
alias gr 'git remote -vv'
alias gc 'git checkout'
alias gd 'git diff'
alias gdd 'git diff --cached'
alias gf 'git fetch'
alias gclean 'git clean -df; and git checkout -- .'

function git-list-unstaged-files
  git ls-files --others --exclude-standard
end

function gl -d 'Git show log'
	git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
end

function gll -d 'Git show more log'
	git log --reverse --pretty='# %s%n%b'
end

alias current-branch 'git rev-parse --abbrev-ref HEAD'
alias all-branches 'git branch | cut -c 3-'

function git-delete-remote-branch -d 'Delete a remote branch'
  git push $argv[1] --delete $argv[2]
end


fish_vi_mode
set fish_bind_mode insert
set fish_key_bindings fish_user_key_bindings

set -x FZF_DEFAULT_COMMAND /google/data/ro/users/lu/lutzky/fzf
set -x FZF_CTRL_T_COMMAND "$FZF_DEFAULT_COMMAND"
set -x EDITOR vim
set -x P4DIFF "vimdiff -R"
set -x P4MERGE vimdiff
set -x PATH \
    $HOME/.linuxbrew/bin \
    $HOME/bin \
    $PATH
set -x MANPATH $HOME/.linuxbrew/share/man $MANPATH
set -x INFOPATH $HOME/.linuxbrew/share/info $INFOPATH

# Load fishmarks (http://github.com/techwizrd/fishmarks)
. ~/.fishmarks/marks.fish
source "$HOME/.homesick/repos/homeshick/completions/homeshick.fish"

Fix homeshick sourcing in fish

fish_vi_mode
set fish_bind_mode insert
set fish_key_bindings fish_user_key_bindings

set -x FZF_DEFAULT_COMMAND /google/data/ro/users/lu/lutzky/fzf
set -x FZF_CTRL_T_COMMAND "$FZF_DEFAULT_COMMAND"
set -x EDITOR vim
set -x P4DIFF "vimdiff -R"
set -x P4MERGE vimdiff
set -x PATH \
    $HOME/.linuxbrew/bin \
    $HOME/bin \
    $PATH
set -x MANPATH $HOME/.linuxbrew/share/man $MANPATH
set -x INFOPATH $HOME/.linuxbrew/share/info $INFOPATH

# Load fishmarks (http://github.com/techwizrd/fishmarks)
source ~/.fishmarks/marks.fish

source "$HOME/.homesick/repos/homeshick/homeshick.fish"


function uninstall --on-event uninstall_proxy
  # Unset proxy variables
  set -l envars http_proxy HTTP_PROXY \
  https_proxy HTTPS_PROXY \
  ftp_proxy FTP_PROXY \
  all_proxy ALL_PROXY
  for envar in $envars
    set -e $envar
  end

  # Erase proxy functions
  functions -e noproxy proxy __proxy.set
end

Uninstall immediately, rather than waiting for an event.


set -x LANGUAGE "en_US.UTF-8"
set -x LC_ALL "en_US.UTF-8"

# set the default editor to vim
set -x EDITOR 'vim'

# use fdfind as the file list for fzf
set -x FZF_DEFAULT_COMMAND "fdfind --type file"

# Go
set -x GOPRIVATE bitbucket.org/advance52
set -x GOPATH $HOME/.go
fish_add_path --path --move /home/moonglum/.go/bin

# direnv
eval (direnv hook fish)

# Ruby
set -x RBENV_SHELL fish
set -x GEM_HOME /home/moonglum/.gems
fish_add_path --path --move /home/moonglum/.rbenv/shims

# aliases
alias s="start"
alias j="jump"
alias l="ls -al"
alias electric-monk="each-project gitkeeper"
alias gsed="git ls-files | xargs sed"

Add Python executables to path

set -x LANGUAGE "en_US.UTF-8"
set -x LC_ALL "en_US.UTF-8"

# set the default editor to vim
set -x EDITOR 'vim'

# use fdfind as the file list for fzf
set -x FZF_DEFAULT_COMMAND "fdfind --type file"

# Go
set -x GOPRIVATE bitbucket.org/advance52
set -x GOPATH $HOME/.go
fish_add_path --path --move /home/moonglum/.go/bin

# direnv
eval (direnv hook fish)

# Ruby
set -x RBENV_SHELL fish
set -x GEM_HOME /home/moonglum/.gems
fish_add_path --path --move /home/moonglum/.rbenv/shims

# Python
fish_add_path --path --move /home/moonglum/.local/bin

# aliases
alias s="start"
alias j="jump"
alias l="ls -al"
alias electric-monk="each-project gitkeeper"
alias gsed="git ls-files | xargs sed"


abbr -a -- - 'cd -'
abbr -a axel 'axel -a'
abbr -a b 'brew'
abbr -a c 'nix-shell -p clojure --command "clojure -A:rebel -A:cheshire"'
abbr -a dl 'wget -r -l 1 -np -nd'
abbr -a fn 'find . -iname'

abbr -a g git
abbr -a ga git add
abbr -a gap git add --patch
abbr -a gb git branch
abbr -a gc git commit --verbose
abbr -a gco git checkout
abbr -a gd git diff
abbr -a gdc git diff --color-words
abbr -a gds git diff --staged
abbr -a gf git fetch
abbr -a gl git log --graph --decorate
abbr -a gl1 git log -1
abbr -a gll git log \'@\{u\}..\'
abbr -a glr git log \'..@\{u\}\'
abbr -a gr git remote
abbr -a gs git status -sb

abbr -a l 'ls -lahp'
abbr -a lx 'less -X'
abbr -a ns 'nix-shell --command fish -p'
abbr -a np 'nix-shell -p'
abbr -a o 'open .'
abbr -a q exit
abbr -a ql 'qlmanage -p'
abbr -a t 'tmux'
abbr -a ta 'type -a'
abbr -a v vim

Remove 'q' as an abbreviation for `exit`

abbr -a -- - 'cd -'
abbr -a axel 'axel -a'
abbr -a b 'brew'
abbr -a c 'nix-shell -p clojure --command "clojure -A:rebel -A:cheshire"'
abbr -a dl 'wget -r -l 1 -np -nd'
abbr -a fn 'find . -iname'

abbr -a g git
abbr -a ga git add
abbr -a gap git add --patch
abbr -a gb git branch
abbr -a gc git commit --verbose
abbr -a gco git checkout
abbr -a gd git diff
abbr -a gdc git diff --color-words
abbr -a gds git diff --staged
abbr -a gf git fetch
abbr -a gl git log --graph --decorate
abbr -a gl1 git log -1
abbr -a gll git log \'@\{u\}..\'
abbr -a glr git log \'..@\{u\}\'
abbr -a gr git remote
abbr -a gs git status -sb

abbr -a l 'ls -lahp'
abbr -a lx 'less -X'
abbr -a ns 'nix-shell --command fish -p'
abbr -a np 'nix-shell -p'
abbr -a o 'open .'
abbr -a ql 'qlmanage -p'
abbr -a t 'tmux'
abbr -a ta 'type -a'
abbr -a v vim


function init -a path --on-event init_vundle
  if [ ! -e ~/.vim/bundle/Vundle.vim/.git ]
    echo \n\t "Vundle.vim is not installed."
    echo \n\t "Read about vim configuration for vundle at https://github.com/VundleVim/Vundle.Vim" \n
  end
end

Initialize immediately, rather than waiting for an event.


function _fishtape_uninstall --on-event fishtape_uninstall
    set --names |
        string replace --filter --regex "^fishtape_" -- "set --erase fishtape_" |
        source
    functions --erase (functions --all | string match --entire --regex -- "^_fishtape_")
    complete --erase --command fishtape
end


# Cargo (Rust)
if test -d $HOME/.cargo/bin
  set PATH $HOME/.cargo/bin $PATH
end

# Postgres.app
if test -d /Applications/Postgres.app
  set PATH /Applications/Postgres.app/Contents/Versions/latest/bin $PATH
end

# TeX
if test -d /Library/TeX/texbin
  set PATH /Library/TeX/texbin $PATH
end

# rbenv
command --search rbenv > /dev/null; and rbenv init - | source

# pyenv
command --search pyenv > /dev/null; and pyenv init - | source

# use exa in place of ls: https://github.com/ogham/exa
if command --search exa > /dev/null
  function ls
    exa --group-directories-first $argv
  end

  # tree view shortcuts
  function l;   ls --all --tree --long --level 1 $argv; end
  function ll;  ls --all --tree --long --level 2 $argv; end
  function lll; ls --all --tree --long --level 3 $argv; end
end

# docker-compose shortcut
function dc
  docker-compose $argv
end

# gitup shortcut
function gu
  pushd $argv[1]; and gitup
  popd
end

# iterm2
test -e {$HOME}/.iterm2_shell_integration.fish ; and source {$HOME}/.iterm2_shell_integration.fish

# direnv
eval (direnv hook fish)

Set VSCode as default editor

# Set VSCode as default editor
set -x EDITOR code

# Cargo (Rust)
if test -d $HOME/.cargo/bin
  set PATH $HOME/.cargo/bin $PATH
end

# Postgres.app
if test -d /Applications/Postgres.app
  set PATH /Applications/Postgres.app/Contents/Versions/latest/bin $PATH
end

# TeX
if test -d /Library/TeX/texbin
  set PATH /Library/TeX/texbin $PATH
end

# rbenv
command --search rbenv > /dev/null; and rbenv init - | source

# pyenv
command --search pyenv > /dev/null; and pyenv init - | source

# use exa in place of ls: https://github.com/ogham/exa
if command --search exa > /dev/null
  function ls
    exa --group-directories-first $argv
  end

  # tree view shortcuts
  function l;   ls --all --tree --long --level 1 $argv; end
  function ll;  ls --all --tree --long --level 2 $argv; end
  function lll; ls --all --tree --long --level 3 $argv; end
end

# docker-compose shortcut
function dc
  docker-compose $argv
end

# gitup shortcut
function gu
  pushd $argv[1]; and gitup
  popd
end

# iterm2
test -e {$HOME}/.iterm2_shell_integration.fish ; and source {$HOME}/.iterm2_shell_integration.fish

# direnv
eval (direnv hook fish)


# Disable fish greeting
set fish_greeting ""

# Aliases
alias vim="nvim"

# Set environment variables
set -x NVIM_TUI_ENABLE_TRUE_COLOR 1

set -x GAE_SDK /usr/local/Cellar/app-engine-python/1.9.27/share/google-app-engine
set -gx PATH /usr/local/bin /usr/texbin $PATH

set -x DOCKER_HOST tcp://192.168.59.103:2376
set -x DOCKER_CERT_PATH /Users/kevinchen/.boot2docker/certs/boot2docker-vm
set -x DOCKER_TLS_VERIFY 1

eval "bash ~/.config/fish/base16-eighties.dark.sh"

#switch $TERM
#    case '*screen*'
#    case '*'
#        tmux attach -t tmux; or tmux new -s tmux
#end

test -e {$HOME}/.iterm2_shell_integration.fish ; and source {$HOME}/.iterm2_shell_integration.fish

Add keybinding for clearing screen in vi insert mode

# Disable fish greeting
set fish_greeting ""

function my_vi_key_bindings
    fish_vi_key_bindings
    bind -M insert \cl 'clear; commandline -f repaint'
end

fish_vi_mode

set -g fish_key_bindings my_vi_key_bindings

# Aliases
alias vim="nvim"

# Set environment variables
set -x NVIM_TUI_ENABLE_TRUE_COLOR 1

set -x GAE_SDK /usr/local/Cellar/app-engine-python/1.9.27/share/google-app-engine
set -gx PATH /usr/local/bin /usr/texbin $PATH

set -x DOCKER_HOST tcp://192.168.59.103:2376
set -x DOCKER_CERT_PATH /Users/kevinchen/.boot2docker/certs/boot2docker-vm
set -x DOCKER_TLS_VERIFY 1

eval "bash ~/.config/fish/base16-eighties.dark.sh"

#switch $TERM
#    case '*screen*'
#    case '*'
#        tmux attach -t tmux; or tmux new -s tmux
#end

test -e {$HOME}/.iterm2_shell_integration.fish ; and source {$HOME}/.iterm2_shell_integration.fish


function randomstring -d "Generate random string"
  dd if=/dev/urandom bs=1 count=128 ^/dev/null | gmd5sum -b | awk '{ print $1 }'
end

Switch to base64 encoding for more bits

function randomstring -d "Generate random base64 string"
  # https://en.wikipedia.org/wiki/Birthday_problem#Probability_table
  dd if=/dev/urandom bs=1 count=128 ^/dev/null | base64 | cut -b -12
end


umask 077 # WSL: Default umask is not applied (github:Microsoft/WSL/issues/352)

set -x PATH $PATH ~/.bin
set -x SHELL (which fish)

# github:danhper/fish-ssh-agent
if test -z "$SSH_ENV"
    set -xg SSH_ENV $HOME/.ssh/environment
end

if not __ssh_agent_is_started
    __ssh_agent_start
end

# Base16 Shell
if status --is-interactive
    set BASE16_SHELL "$HOME/.config/base16-shell/"
    source "$BASE16_SHELL/profile_helper.fish"
end

# THEME PURE #
set fish_function_path /home/nannangar/.config/fish/functions/theme-pure/functions/ $fish_function_path
source /home/nannangar/.config/fish/functions/theme-pure/conf.d/pure.fish

Replace fish-ssh-agent with a simple call (refactor)

umask 077 # WSL: Default umask is not applied (github:Microsoft/WSL/issues/352)

set -x PATH $PATH ~/.bin
set -x SHELL (which fish)

# https://wiki.archlinux.org/index.php/Fish#Evaluate_ssh-agent
eval (ssh-agent -c)

# Base16 Shell
if status --is-interactive
    set BASE16_SHELL "$HOME/.config/base16-shell/"
    source "$BASE16_SHELL/profile_helper.fish"
end

# THEME PURE #
set fish_function_path /home/nannangar/.config/fish/functions/theme-pure/functions/ $fish_function_path
source /home/nannangar/.config/fish/functions/theme-pure/conf.d/pure.fish


function coffitivity --description "Loop sounds from a coffee shop and run in the background"
  mplayer -really-quiet -loop 0 -volume 70 ~/Music/coffitivity.mp3 </dev/null ^/dev/null &
end

Improve my fake cafe experience

function coffitivity --description "Loop sounds from a coffee shop and run in the background. Plays at half volume by default."
  if test (count $argv) = 1
    set volume $argv[1]
  else
    set volume 50
  end
  mplayer -really-quiet -loop 0 -volume $volume ~/Music/coffitivity.mp3 </dev/null ^/dev/null &
end


function delete-user --argument user
    if empty "$user"
        usage delete-user '<user>'
        return (false)
    end

    if contains "$user" (actual-users)
        for group in (user-in-groups "$user")
            delete-from-group "$group" "$user"
        end

        revoke-access-keys "$user"
        unset-password "$user"
        deactivate-mfa "$user"
        aws iam delete-user --user-name "$user"
    end
end


Add sway helper script to focus TV workspace

function sway_focus_tv
    set tv_outputname (swaymsg -t get_outputs | jq --raw-output '.. | objects | select(.model == "LG TV") | .name')
    swaymsg focus output "$tv_outputname"
end


mkdir -p ~/bin ~/npm/bin ~/.cargo/bin ~/.gem/ruby/2.5.0/bin

set -gx fish_greeting ""
set -gx LANG en_GB.UTF-8
set -gx PATH ~/bin ~/npm/bin ~/.cargo/bin ~/.gem/ruby/2.5.0/bin $PATH
set -gx BROWSER firefox
set -gx EDITOR nvim
set -gx VISUAL nvim

# Kill all running containers.
alias dockerkill='docker kill (docker ps -q)'

# Delete all docker images and containers.
alias dockernuke='docker rm (docker ps -a -q); docker rmi -f (docker images -q)'

# Other git aliases are in git config
alias g="git"

# Some software still uses vimdiff
alias vimdiff="nvim -d"

# Start an SSH agent if required, if not, connect to it.
initialise_ssh_agent

# Prevent funky output inside emacs terminals.
if test "$TERM" = "eterm-color"
  function fish_title; end
end

# Local config.
if [ -f ~/.local.fish ]
  source ~/.local.fish
end

Put path first because it's important

mkdir -p ~/bin ~/npm/bin ~/.cargo/bin ~/.gem/ruby/2.5.0/bin
set -gx PATH ~/bin ~/npm/bin ~/.cargo/bin ~/.gem/ruby/2.5.0/bin $PATH

set -gx fish_greeting ""
set -gx LANG en_GB.UTF-8
set -gx BROWSER firefox
set -gx EDITOR nvim
set -gx VISUAL nvim

# Kill all running containers.
alias dockerkill='docker kill (docker ps -q)'

# Delete all docker images and containers.
alias dockernuke='docker rm (docker ps -a -q); docker rmi -f (docker images -q)'

# Other git aliases are in git config
alias g="git"

# Some software still uses vimdiff
alias vimdiff="nvim -d"

# Start an SSH agent if required, if not, connect to it.
initialise_ssh_agent

# Prevent funky output inside emacs terminals.
if test "$TERM" = "eterm-color"
  function fish_title; end
end

# Local config.
if [ -f ~/.local.fish ]
  source ~/.local.fish
end


function __fish_history
  if test -e ~/.config/fish/fish_history
    tac ~/.config/fish/fish_history | grep "^\- cmd: " | sed 's/\- cmd: //'
  else if test -e ~/.local/share/fish/fish_history
    tac ~/.local/share/fish/fish_history | grep "^\- cmd: " | sed 's/\- cmd: //'
  else
    history
  end
end

Check if tac exists, if not use tail -r

function __fish_history
  set -l QUERY_CMD
  if type -q tac
    set QUERY_CMD "tac"
  else
    set QUERY_CMD "tail -r"
  end

  if test -e ~/.config/fish/fish_history
    eval $QUERY_CMD ~/.config/fish/fish_history | grep "^\- cmd: " | sed 's/\- cmd: //'
  else if test -e ~/.local/share/fish/fish_history
    eval $QUERY_CMD ~/.local/share/fish/fish_history | grep "^\- cmd: " | sed 's/\- cmd: //'
  else
    history
  end
end


Add function to update instance profiles

function update-instance-profiles
    trace (status --current-filename) $argv

    for profile in (get instance-profiles)
        create-instance-profile $profile

        for role in (get instance-profiles/$profile/roles)
            aws iam add-role-to-instance-profile --instance-profile-name $profile --role-name $role
        end
    end
end


fzf_key_bindings

Add fish user key bindings for fzf

function fish_user_key_bindings
    ### fzf ###
    bind \ct '__fzf_ctrl_t'
    bind \cr '__fzf_ctrl_r'
    bind \cx '__fzf_ctrl_x'
    bind \ec '__fzf_alt_c'
    if bind -M insert > /dev/null ^ /dev/null
        bind -M insert \ct '__fzf_ctrl_t'
        bind -M insert \cr '__fzf_ctrl_r'
        bind -M insert \cx '__fzf_ctrl_x'
        bind -M insert \ec '__fzf_alt_c'
    end
    ### fzf ###
    ### fzf ###
    bind \ct '__fzf_ctrl_t'
    bind \cr '__fzf_ctrl_r'
    bind \cx '__fzf_ctrl_x'
    bind \ec '__fzf_alt_c'
    if bind -M insert > /dev/null ^ /dev/null
        bind -M insert \ct '__fzf_ctrl_t'
        bind -M insert \cr '__fzf_ctrl_r'
        bind -M insert \cx '__fzf_ctrl_x'
        bind -M insert \ec '__fzf_alt_c'
    end
    ### fzf ###
    ### fzf ###
    bind \ct '__fzf_ctrl_t'
    bind \cr '__fzf_ctrl_r'
    bind \cx '__fzf_ctrl_x'
    bind \ec '__fzf_alt_c'
    if bind -M insert > /dev/null ^ /dev/null
        bind -M insert \ct '__fzf_ctrl_t'
        bind -M insert \cr '__fzf_ctrl_r'
        bind -M insert \cx '__fzf_ctrl_x'
        bind -M insert \ec '__fzf_alt_c'
    end
    ### fzf ###
    ### fzf ###
    bind \ct '__fzf_ctrl_t'
    bind \cr '__fzf_ctrl_r'
    bind \cx '__fzf_ctrl_x'
    bind \ec '__fzf_alt_c'
    if bind -M insert > /dev/null ^ /dev/null
        bind -M insert \ct '__fzf_ctrl_t'
        bind -M insert \cr '__fzf_ctrl_r'
        bind -M insert \cx '__fzf_ctrl_x'
        bind -M insert \ec '__fzf_alt_c'
    end
    ### fzf ###
end

fzf_key_bindings


# Load env variables
if test -f ~/.env.fish
    source ~/.env.fish
end

# Hide greeting
function fish_greeting
end

# Better titles
function fish_title
  test (count $argv) -gt 0
    and echo $argv[1]
    or prompt_pwd
end

set -gx EDITOR code -w
set -gx FILTER fzf
set -gx LESS RS

# Set the terminal window to use a dark GTK theme.
if begin; type -q xprop; and set -q WINDOWID; end
    xprop -f _GTK_THEME_VARIANT 8u -set _GTK_THEME_VARIANT "dark" -id $WINDOWID
end

Set EDITOR only if not already set

# Hide greeting
function fish_greeting
end

# Better titles
function fish_title
  test (count $argv) -gt 0
    and echo $argv[1]
    or prompt_pwd
end

set -q EDITOR
  or set -gx EDITOR code -w
set -gx FILTER fzf
set -gx LESS RS


function switchaudio --description 'Switch between audio outputs'
    set -l sinks (pactl list short sinks)
    for sink in $sinks
       set sink_info (string split \t $sink)
       if test RUNNING = $sink_info[5]
           set active_sink $sink_info[1]
       else if test SUSPENDED = $sink_info[5]
           set inactive_sink $sink_info[1]
       end
    end

    echo $active_sink
    echo $inactive_sink

    set -l inputs (string split \t (pactl list short sink-inputs))
end

Add sink move logic (code is now working)

function switchaudio --description 'Switch between audio outputs (assuming there are only 2)'
    set -l sinks (pactl list short sinks)
    for sink in $sinks
       set sink_info (string split \t $sink)
       if test RUNNING = $sink_info[5]
           set active_sink $sink_info[1]
       else if test SUSPENDED = $sink_info[5]
           set inactive_sink $sink_info[1]
       else if test IDLE = $sink_info[5]
           set inactive_sink $sink_info[1]
       end
    end

    set -l inputs (pactl list short sink-inputs)
    for input in $inputs
        set input_id (string split \t $input)[1]
        pactl move-sink-input $input_id $inactive_sink
    end
end


# See → fishshell.com/docs/current/commands.html#complete

function __fish_mix_needs_command
  set cmd (commandline -opc)
  if [ (count $cmd) -eq 1 -a $cmd[1] = 'mix' ]
    return 0
  end
  return 1
end

# fish completion for mix
function __fish_mix_tasks
    mix help ^/dev/null | awk '{
        if ($1 == "mix") {
            if ($3 == "#") {
                print $2"\t"substr($0, index($0, $4))
            } else {
                print $1"\t"substr($0, index($0, $3))
            }
        }
    }'
end

complete -c mix -n '__fish_mix_needs_command' -f -a '(__fish_mix_tasks)'

Replace disabled stderr redirection char ^ with 2>

# See → fishshell.com/docs/current/commands.html#complete

function __fish_mix_needs_command
  set cmd (commandline -opc)
  if [ (count $cmd) -eq 1 -a $cmd[1] = 'mix' ]
    return 0
  end
  return 1
end

# fish completion for mix
function __fish_mix_tasks
    mix help 2>/dev/null | awk '{
        if ($1 == "mix") {
            if ($3 == "#") {
                print $2"\t"substr($0, index($0, $4))
            } else {
                print $1"\t"substr($0, index($0, $3))
            }
        }
    }'
end

complete -c mix -n '__fish_mix_needs_command' -f -a '(__fish_mix_tasks)'


function expand:choose-next
  # If a filter is specified and more than one replacement is available, use it to filter through the available
  # replacements.
  if begin; set -q __expand_replacements[2]; and set -q __expand_filter; end
    for line in $__expand_replacements
      echo $line
    end | eval $__expand_filter | read -a replacement

    # Interactive filters will cause Fish to need a repaint.
    commandline -f repaint

  # Otherwise, use basic tab cycling.
  else
    # Select the top replacement.
    set replacement "$__expand_replacements[1]"
  end

  # If a replacement was chosen, use it.
  if test -n "$replacement"
    # Enquote replacements with spaces.
    if echo "$replacement" | grep -q ' '
      commandline -t -r "\"$replacement\""
    else
      commandline -t -r "$replacement"
    end
  end

  # If there are at least two replacements, cycle the replacement queue order.
  set -q __expand_replacements[2]
    and set -g __expand_replacements $__expand_replacements[2..-1] $__expand_replacements[1]
end

Fix goofy behavior with canceled completion attempts

function expand:choose-next
  # Since we can't conditionally switch key bind modes, we need to pass through command completion requests again even
  # though we are already in expand mode.
  if not set -q __expand_replacements[1]
    commandline -f complete
    return
  end

  # If a filter is specified and more than one replacement is available, use it to filter through the available
  # replacements.
  if begin; set -q __expand_replacements[2]; and set -q __expand_filter; end
    for line in $__expand_replacements
      echo $line
    end | eval $__expand_filter | read -a replacement

    # Interactive filters will cause Fish to need a repaint.
    commandline -f repaint

  # Otherwise, use basic tab cycling.
  else
    # Select the top replacement.
    set replacement "$__expand_replacements[1]"
  end

  # If a replacement was chosen, use it.
  if test -n "$replacement"
    # Enquote replacements with spaces.
    if echo "$replacement" | grep -q ' '
      commandline -t -r "\"$replacement\""
    else
      commandline -t -r "$replacement"
    end
  end

  # If there are at least two replacements, cycle the replacement queue order.
  set -q __expand_replacements[2]
    and set -g __expand_replacements $__expand_replacements[2..-1] $__expand_replacements[1]
end


function init -a path --on-event init_git-flow
  for prefix in /usr /usr/local /opt/local
    if test -f $prefix/share/fish/completions/git.fish
      source $prefix/share/fish/completions/git.fish
      break
    end
  end

  if not type -q __fish_git_branches
    echo "Error: git completion not found!" >&2; return 1
  end
end

Initialize immediately, rather than waiting for an event.

for prefix in /usr /usr/local /opt/local
  if test -f $prefix/share/fish/completions/git.fish
    source $prefix/share/fish/completions/git.fish
    break
  end
end

if not type -q __fish_git_branches
  echo "Error: git completion not found!" >&2
end


# SYNOPSIS
#   refresh
#
# OVERVIEW
#   Refresh (reload) the current fish session.

function refresh -d "refresh the fish session"
  set -q CI; or exec fish < /dev/tty
end

Save history before replacing shell process

# SYNOPSIS
#   refresh
#
# OVERVIEW
#   Refresh (reload) the current fish session.

function refresh -d "Refresh fish session by replacing current process"
  if not set -q CI
    history --save
    exec fish < /dev/tty
  end
end


function __fish_pyenv
  pyenv commands
end

complete -f -c pyenv -a '(__fish_pyenv)'

Implement sub-command completion for fish shell

function __fish_pyenv_needs_command
  set cmd (commandline -opc)
  if [ (count $cmd) -eq 1 -a $cmd[1] = 'pyenv' ]
    return 0
  end
  return 1
end

function __fish_pyenv_using_command
  set cmd (commandline -opc)
  if [ (count $cmd) -gt 1 ]
    if [ $argv[1] = $cmd[2] ]
      return 0
    end
  end
  return 1
end

complete -f -c pyenv -n '__fish_pyenv_needs_command' -a '(pyenv commands)'
for cmd in (pyenv commands)
  complete -f -c pyenv -n "__fish_pyenv_using_command $cmd" -a "(pyenv completions $cmd)"
end


function init --on-event init_bundler
  set -l execs annotate      \
               cap           \
               capify        \
               cucumber      \
               dashing       \
               guard         \
               kitchen       \
               middleman     \
               nanoc         \
               puma          \
               rackup        \
               rainbows      \
               rake          \
               rspec         \
               rubocop       \
               ruby          \
               shotgun       \
               sidekiq       \
               spec          \
               spinach       \
               spork         \
               thin          \
               thor          \
               unicorn       \
               unicorn_rails

  if set -q bundler_plugin_execs
    set execs $execs $bundler_plugin_execs
  end

  # Fish 2.1.1+ has support for --inherit-variable
  set -l do_eval (echo $FISH_VERSION | grep 2.1.1-)

  for executable in $execs
    if test -z "$do_eval"
      eval "function $executable; __execute_as_bundler $executable \$argv; end"
    else
      function $executable --inherit-variable executable
        __execute_as_bundler $executable $argv
      end
    end
  end
end

Initialize immediately, rather than waiting for an event.


-record(fa, {?ELEMENT_BASE(element_fa),
        text=""                 :: text(),
        body=" "                 :: body,
		fa 						:: text()		% Font awsume icon
		}).

Add ifndef/endif pairs around include file

-ifndef(nitrogen_fa_include).
-define(nitrogen_fa_include, 1).

-record(fa, {?ELEMENT_BASE(element_fa),
        text=""                 :: text(),
        body=" "                 :: body,
		fa 						:: text()		% Font awsume icon
		}).

-endif.


%% See LICENSE for licensing information.
%% -*- coding: utf-8 -*-
-module(fn_string_tests).

-include_lib("eunit/include/eunit.hrl").

%% API tests.

b_abs_test() ->
  ?assertMatch({where, _,
                [{fn, "base", [{b_param,"b"}], 46}]},
               s("58 where fun base.b = 46 end")).

n_abs_test() ->
  ?assertMatch({where, _,
                [{fn, "named", [{n_param,"N"}], 46}]},
               s("58 where fun named N = 46 end")).

v_abs_test() ->
  ?assertMatch({where, _,
                [{fn, "value", [{v_param,"v"}], 46}]},
               s("58 where fun value!v = 46 end")).

%% Internals

s(S) ->
  {ok, T} = tea:string(S),
  T.

%% End of Module.

Test function declaration more extensively

%% See LICENSE for licensing information.
%% -*- coding: utf-8 -*-
-module(fn_string_tests).

-include_lib("eunit/include/eunit.hrl").

%% API tests.

b_abs_test_() ->
  [?_assertMatch({where, _,
                  [{fn, "base", [{b_param,"b"}], 46}]},
                 s("58 where fun base.b = 46 end")),
   ?_assertMatch({where, _,
                  [{fn, "base", [{b_param,"b1"},
                                 {b_param,"b2"}], 46}]},
                 s("58 where fun base.b1.b2 = 46 end")) ].

n_abs_test_() ->
  [?_assertMatch({where, _,
                  [{fn, "named", [{n_param,"N"}], 46}]},
                 s("58 where fun named N = 46 end")),
   ?_assertMatch({where, _,
                  [{fn, "named", [{n_param,"N1"},
                                  {n_param,"N2"}], 46}]},
                 s("58 where fun named N1 N2 = 46 end"))].

v_abs_test_() ->
  [?_assertMatch({where, _,
                  [{fn, "value", [{v_param,"v"}], 46}]},
                 s("58 where fun value!v = 46 end")),
   ?_assertMatch({where, _,
                  [{fn, "value", [{v_param,"v1"},
                                  {v_param,"v2"}], 46}]},
                 s("58 where fun value!v1 !v2 = 46 end"))].

misc_abs_test() ->
  ?assertMatch({where, _,
                [{fn, "f", [{b_param,"b"},
                            {n_param,"N"},
                            {v_param,"v"}], 46}]},
               s("58 where fun f .b N !v = 46 end")).

%% Internals

s(S) ->
  {ok, T} = tea:string(S),
  T.

%% End of Module.


-module(mzb_api_metrics).

-export([get_metrics/5,
         extract_metric_names/1]).

get_metrics(UserName, DirNode, Host, RemoteScriptPath, RemoteEnvPath) ->
    [Res] = mzb_subprocess:remote_cmd(
              UserName,
              [Host],
              io_lib:format("~s/mzbench/bin/metric_names.escript", [mzb_api_paths:node_deployment_path()]),
              [DirNode, RemoteScriptPath, RemoteEnvPath], mzb_api_app:default_logger(), []),
    try
        jiffy:decode(Res, [return_maps])
    catch
        C:E ->
            ST = erlang:get_stacktrace(),
            lager:error("Failed to parse metrics names cause of ~p~nOutput: ~p~nStacktrace: ~p", [E, Res, ST]),
            erlang:raise(C,E,ST)
    end.

extract_metric_names(#{<<"groups">>:= Groups} = _Metrics) ->
    [Name || #{<<"graphs">>:= Graphs} <- Groups, #{<<"metrics">>:= Metrics} <- Graphs, #{<<"name">>:= Name} <- Metrics].

Fix function_clause on handling of empty list of metrics

-module(mzb_api_metrics).

-export([get_metrics/5,
         extract_metric_names/1]).

get_metrics(UserName, DirNode, Host, RemoteScriptPath, RemoteEnvPath) ->
    [Res] = mzb_subprocess:remote_cmd(
              UserName,
              [Host],
              io_lib:format("~s/mzbench/bin/metric_names.escript", [mzb_api_paths:node_deployment_path()]),
              [DirNode, RemoteScriptPath, RemoteEnvPath], mzb_api_app:default_logger(), []),
    try
        jiffy:decode(Res, [return_maps])
    catch
        C:E ->
            ST = erlang:get_stacktrace(),
            lager:error("Failed to parse metrics names cause of ~p~nOutput: ~p~nStacktrace: ~p", [E, Res, ST]),
            erlang:raise(C,E,ST)
    end.

extract_metric_names(#{<<"groups">>:= Groups} = _Metrics) ->
    [Name || #{<<"graphs">>:= Graphs} <- Groups, #{<<"metrics">>:= Metrics} <- Graphs, #{<<"name">>:= Name} <- Metrics];
extract_metric_names(#{}) ->
    [].


-module(privatepaste_home).

-behavior(cowboy_http_handler).

-export([init/3]).
-export([handle/2]).
-export([terminate/3]).

init(_Type, Req, _Opts) ->
    {ok, Req, undefined_state}.

handle(Req, State) ->
    {ok, Body} = index_dtl:render([]),
    Headers = [{<<"Content-Type">>, <<"text/html">>}],
    {ok, Req2} = cowboy_req:reply(200, Headers, Body, Req),
    {ok, Req2, State}.

terminate(_Reason, _Req, _State) ->
    ok.

Update home to use base_dtl for now

-module(privatepaste_home).

-behavior(cowboy_http_handler).

-export([init/3]).
-export([handle/2]).
-export([terminate/3]).

init(_Type, Req, _Opts) ->
    {ok, Req, undefined_state}.

handle(Req, State) ->
    {ok, Body} = base_dtl:render([]),
    Headers = [{<<"Content-Type">>, <<"text/html">>}],
    {ok, Req2} = cowboy_req:reply(200, Headers, Body, Req),
    {ok, Req2, State}.

terminate(_Reason, _Req, _State) ->
    ok.


%% Feel free to use, reuse and abuse the code in this file.

%% @private
-module(blank_page_app).
-behaviour(application).

%% API.
-export([start/2]).
-export([stop/1]).

%% API.

start(_Type, _Args) ->
	Dispatch = cowboy_router:compile([
		{'_', [
			{"/", toppage_handler, []}
		]}
	]),
	{ok, _} = cowboy:start_http(http, 100, [{port, 80},{max_connections, infinity}], [
		{env, [{dispatch, Dispatch}]}
	]),
	blank_page_sup:start_link().

stop(_State) ->
	ok.

Make all path route to blank response

%% Feel free to use, reuse and abuse the code in this file.

%% @private
-module(blank_page_app).
-behaviour(application).

%% API.
-export([start/2]).
-export([stop/1]).

%% API.

start(_Type, _Args) ->
	Dispatch = cowboy_router:compile([
		{'_', [
			{"/[...]", toppage_handler, []}
		]}
	]),
	{ok, _} = cowboy:start_http(http, 100, [{port, 80},{max_connections, infinity}], [
		{env, [{dispatch, Dispatch}]}
	]),
	blank_page_sup:start_link().

stop(_State) ->
	ok.


%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1996-2011. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at http://www.erlang.org/.
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%

-ifdef(line_trace).
-line_trace(true).
-define(line,
	io:format(lists:concat([?MODULE,",",integer_to_list(?LINE),": ~p"]),
		  [erlang:now()]),).
-else.
-define(line,).
-endif.
-define(t,test_server).
-define(config,test_server:lookup_config).

Replace usage of erlang:now() in line-tracing

%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 1996-2011. All Rights Reserved.
%%
%% The contents of this file are subject to the Erlang Public License,
%% Version 1.1, (the "License"); you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at http://www.erlang.org/.
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%

-ifdef(line_trace).
-line_trace(true).
-define(line,
	io:format(lists:concat([?MODULE,",",integer_to_list(?LINE),": ~p"]),
		  [erlang:monotonic_time()-erlang:system_info(start_time)]),).
-else.
-define(line,).
-endif.
-define(t,test_server).
-define(config,test_server:lookup_config).


-module(boss_cache_adapter_memcached_bin).
-behaviour(boss_cache_adapter).

-export([init/1, start/0, start/1, stop/1]).
-export([get/3, set/5, delete/3]).

start() ->
    start([]).

start(_Options) ->
    {ok, undefined}.

stop(_Conn) ->
    erlmc:quit().

init(Options) ->
    CacheServers = proplists:get_value(cache_servers, Options, [{"localhost", 11211, 1}]),
    ok = erlmc:start(CacheServers),
    ok.

get(_Conn, Prefix, Key) ->
    case erlmc:get(term_to_key(Prefix, Key)) of
        <<>> ->
            undefined;
        Bin ->
            binary_to_term(Bin)
    end.

set(_Conn, Prefix, Key, Val, TTL) ->
    erlmc:set(term_to_key(Prefix, Key), term_to_binary(Val), TTL).

delete(_Conn, Prefix, Key) ->
    erlmc:delete(term_to_key(Prefix, Key)).

% internal
term_to_key(Prefix, Term) ->
    lists:concat([Prefix, ":", mochihex:to_hex(erlang:md5(term_to_binary(Term)))]).

Return {ok, undefined} from Memcache adapter

-module(boss_cache_adapter_memcached_bin).
-behaviour(boss_cache_adapter).

-export([init/1, start/0, start/1, stop/1]).
-export([get/3, set/5, delete/3]).

start() ->
    start([]).

start(_Options) ->
    {ok, undefined}.

stop(_Conn) ->
    erlmc:quit().

init(Options) ->
    CacheServers = proplists:get_value(cache_servers, Options, [{"localhost", 11211, 1}]),
    ok = erlmc:start(CacheServers),
    {ok, undefined}.

get(_Conn, Prefix, Key) ->
    case erlmc:get(term_to_key(Prefix, Key)) of
        <<>> ->
            undefined;
        Bin ->
            binary_to_term(Bin)
    end.

set(_Conn, Prefix, Key, Val, TTL) ->
    erlmc:set(term_to_key(Prefix, Key), term_to_binary(Val), TTL).

delete(_Conn, Prefix, Key) ->
    erlmc:delete(term_to_key(Prefix, Key)).

% internal
term_to_key(Prefix, Term) ->
    lists:concat([Prefix, ":", mochihex:to_hex(erlang:md5(term_to_binary(Term)))]).


-module( largest_series_product_tests ).
-include_lib("eunit/include/eunit.hrl").

three_test() -> ?assert( 504 =:= largest_series_product:from_string("0123456789", 3) ).

five_test() -> ?assert( 15120 =:= largest_series_product:from_string("0123456789", 5) ).

six_test() -> ?assert( 23520 =:= largest_series_product:from_string("73167176531330624919225119674426574742355349194934", 6) ).

all_zeroes_test() -> ?assert( 0 =:= largest_series_product:from_string("0000", 2) ).

all_contain_zeroes_test() -> ?assert( 0 =:= largest_series_product:from_string("99099", 3) ).

Add tests with empty products

-module( largest_series_product_tests ).
-include_lib("eunit/include/eunit.hrl").

three_test() -> ?assert( 504 =:= largest_series_product:from_string("0123456789", 3) ).

five_test() -> ?assert( 15120 =:= largest_series_product:from_string("0123456789", 5) ).

six_test() -> ?assert( 23520 =:= largest_series_product:from_string("73167176531330624919225119674426574742355349194934", 6) ).

all_zeroes_test() -> ?assert( 0 =:= largest_series_product:from_string("0000", 2) ).

all_contain_zeroes_test() -> ?assert( 0 =:= largest_series_product:from_string("99099", 3) ).

empty_product_test() -> ?assert( 1 =:= largest_series_product:from_string("", 0) ).

nonempty_string_empty_product_test() -> ?assert( 1 =:= largest_series_product:from_string("123", 0) ).