#
# __bh_check_bashhub_installation.fish
# Should only be sourced once following installation.
#

# Small function to check our Bashhub installation.
function __bh_check_bashhub_installation
    set -l ret 0
    set -l config_path "$BH_HOME_DIRECTORY/config"
    if [ -n "$FISH_VERSION" ] && [ -n "$__bh_enable_subshells" ] && [ "(trap)" -ne *"__bh_preexec_invoke_exec"* ]
        echo "Bashhub's preexec hook is being overriden and is not saving commands. Please resolve what may be holding the DEBUG trap."
        set ret 1
    else if [ -f "$config_path" ]
        echo "Missing Bashhub config file. Please run 'bashhub setup' to generate one."
        set ret 2
    else if not grep -Fq "access_token" "$config_path"
        echo "Missing Bashhub access token. Please run 'bashhub setup' to re-login."
        set ret 3
    else if not grep -Fq "system_name" "$config_path"
        echo "Missing system name. Please run 'bashhub setup' to re-login."
        set ret 4
    else if grep -Fq "save_commands = False" "$config_path"
        echo "Bashhub is currently disabled. Run 'bashhub on' to re-enable."
        set ret 5
    end

    return $ret
end

__bh_check_bashhub_installation

Test if config file is missing

#
# __bh_check_bashhub_installation.fish
# Should only be sourced once following installation.
#

# Small function to check our Bashhub installation.
function __bh_check_bashhub_installation
    set -l ret 0
    set -l config_path "$BH_HOME_DIRECTORY/config"
    if [ -n "$FISH_VERSION" ] && [ -n "$__bh_enable_subshells" ] && [ "(trap)" -ne *"__bh_preexec_invoke_exec"* ]
        echo "Bashhub's preexec hook is being overriden and is not saving commands. Please resolve what may be holding the DEBUG trap."
        set ret 1
    else if not [ -f "$config_path" ]
        echo "Missing Bashhub config file. Please run 'bashhub setup' to generate one."
        set ret 2
    else if not grep -Fq "access_token" "$config_path"
        echo "Missing Bashhub access token. Please run 'bashhub setup' to re-login."
        set ret 3
    else if not grep -Fq "system_name" "$config_path"
        echo "Missing system name. Please run 'bashhub setup' to re-login."
        set ret 4
    else if grep -Fq "save_commands = False" "$config_path"
        echo "Bashhub is currently disabled. Run 'bashhub on' to re-enable."
        set ret 5
    end

    return $ret
end

__bh_check_bashhub_installation


Add a session mangement script for my password manager

set SESSION_FILE ~/.bws-session

function bws
  if test -e $SESSION_FILE
    set -x BW_SESSION (cat $SESSION_FILE)
  end

  if ! bw status | grep unlocked > /dev/null
    set -x BW_SESSION (bw unlock --raw)
    if test $status -ne 0
      echo "bw unlock failed"
      return $status
    else
      echo $BW_SESSION > $SESSION_FILE
    end
  end

  bw $argv
end


function fish_prompt
  # Start ohmyfish-batman theme default prompt
  test $status -ne 0;
    and set -l colors 600 900 c00
    or set -l colors 333 666 aaa

  set -l pwd (prompt_pwd)
  set -l base (basename "$pwd")

  set -l expr "s|~|"(fst)"^^"(off)"|g; \
               s|/|"(snd)"/"(off)"|g;  \
               s|"$base"|"(fst)$base(off)" |g"

  echo -n (echo "$pwd" | sed -e $expr)(off)

  for color in $colors
    echo -n (set_color $color)">"
  end

  echo -n " "
  # End ohmyfish-batman theme default prompt

  if set -q VIRTUAL_ENV
    echo -n -s (set_color -b blue white) "(" (basename "$VIRTUAL_ENV") ")" (set_color normal) " "
  end
end

Use long options, move helper functions from fish_greeting

function fish_prompt
  # Start ohmyfish-batman theme default prompt
  test $status -ne 0;
    and set --local colors 600 900 c00
    or set --local colors 333 666 aaa

  set --local pwd (prompt_pwd)
  set --local base (basename "$pwd")

  set --local expr "s|~|"(fst)"^^"(off)"|g; \
                   s|/|"(snd)"/"(off)"|g;  \
                   s|"$base"|"(fst)$base(off)" |g"

  echo -n (echo "$pwd" | sed --expression $expr)(off)

  for color in $colors
    echo -n (set_color $color)">"
  end

  echo -n " "
  # End ohmyfish-batman theme default prompt

  if set --query VIRTUAL_ENV
    echo -n -s (set_color --background blue white) "(" (basename "$VIRTUAL_ENV") ")" (set_color normal) " "
  end
  end
end


function fish_title

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

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

	if set -q FISH_TITLE
		set title $FISH_TITLE
	else
		if [ $_ = "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 $process instead of $_ to make it easier to read

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


set -x TERM screen-256color
set -x EDITOR nano

set PATH $HOME/.rbenv/shims $PATH
rbenv rehash >/dev/null ^&1

set PATH /usr/local/share/npm/bin $PATH

alias p project

set fish_greeting

Configure fish to export explicit PATH

set -x TERM screen-256color
set -x EDITOR nano

set -x PATH $HOME/.rbenv/shims /usr/local/share/npm/bin /usr/local/bin /usr/local/sbin /usr/bin /usr/sbin /bin /sbin

rbenv rehash >/dev/null ^&1

alias p project

set fish_greeting


Add fish function to terminate a stuck terminating k8s namespace

function terminateNS --argument-names ns --description "Delete a stuck k8s terminating namespace"
    set NAMESPACE $ns
    kubectl proxy &
    kubectl get namespace $NAMESPACE -o json |jq '.spec = {"finalizers":[]}' >temp.json
    curl -k -H "Content-Type: application/json" -X PUT --data-binary @temp.json 127.0.0.1:8001/api/v1/namespaces/$NAMESPACE/finalize
end


function expand-word -d 'Define a word expansion'
  set -l help "Define a word expansion.

Usage
  expand-word -p PATTERN -e EXPANSION
  expand-word -c CONDITION -e EXPANSION

Options
  -c, --condition Function whose return value determines when the expansion should be run
  -e, --expander  Function or string to expand the matching word with
  -h, --help      Show this help message
  -p, --pattern   A regular expression condition the word must match
"

  if not set -q argv[1]
    echo "$help"
    return 0
  end

  argu h help p: pattern: c: condition: e: expander: -- $argv | while read -l option value
    switch $option
      case -h --help
        echo "$help"
        return 0

      case -c --condition
        set condition "$value"

      case -p --pattern
        set condition "expand:match '$value'"

      case -e --expander
        set expander "$value"

      case _
        echo "Unexpected argument: $value" >&2
        return 1
    end
  end

  if not set -q condition
    echo "Expansions must have a condition" >&2
    return 1
  end

  if not set -q expander
    echo "You must specify an expander" >&2
    return 1
  end

  set -g __word_expansions $__word_expansions "$condition
$expander"
end

function expand:match-pattern -a pattern token
  commandline -t | grep -q $pattern
end

Remove tricksy test code that slipped in somehow...


set PATH ~/bin $PATH

# http://www.martinklepsch.org/posts/git-prompt-for-fish-shell.html
set __fish_git_prompt_showdirtystate 'yes'
set __fish_git_prompt_char_dirtystate '⚡'

### Prompt

function fish_prompt
  set_color red
  echo -n "❯"
  set_color yellow
  echo -n "❯"
  set_color green
  echo -n "❯ "
end

function fish_right_prompt
  set_color blue
  echo -n (prompt_pwd)
  set_color green
  echo -n (__fish_git_prompt)
  set_color normal
end

### fasd support

function -e fish_preexec _run_fasd
  fasd --proc (fasd --sanitize "$argv") > "/dev/null" 2>&1
end

function j
  cd (fasd -d -e 'printf %s' "$argv")
end

Bring over PATH changes to fish

set PATH (brew --prefix coreutils)/libexec/gnubin $PATH
set PATH ~/bin $PATH
set PATH $PATH ~/.cask/bin

# http://www.martinklepsch.org/posts/git-prompt-for-fish-shell.html
set __fish_git_prompt_showdirtystate 'yes'
set __fish_git_prompt_char_dirtystate '⚡'

### Prompt

function fish_prompt
  set_color red
  echo -n "❯"
  set_color yellow
  echo -n "❯"
  set_color green
  echo -n "❯ "
end

function fish_right_prompt
  set_color blue
  echo -n (prompt_pwd)
  set_color green
  echo -n (__fish_git_prompt)
  set_color normal
end

### fasd support

function -e fish_preexec _run_fasd
  fasd --proc (fasd --sanitize "$argv") > "/dev/null" 2>&1
end

function j
  cd (fasd -d -e 'printf %s' "$argv")
end


function __cdgitroot_usage
    echo 'Usage: cd-gitroot [PATH]'
    echo 'Jump to git repository\'s root directory.'
    echo 'If PATH is specified, it\'s recognized as relative path'
    echo 'from repository\'s root directory. And jump to it.'
end

Add error check to detect in-work-tree

function __cdgitroot_usage
    echo 'Usage: cd-gitroot [PATH]'
    echo 'Jump to git repository\'s root directory.'
    echo 'If PATH is specified, it\'s recognized as relative path'
    echo 'from repository\'s root directory. And jump to it.'
end

function cd-gitroot -d 'Jump to git repo\'s root'
    if not command git rev-parse --git-dir > /dev/null ^ /dev/null
        echo 'It\'s out of working tree!' 1>&2
        return 1
    end

end


function __cdgitroot_usage
    echo 'Usage: cd-gitroot [PATH]'
    echo 'Jump to git repository\'s root directory.'
    echo 'If PATH is specified, it\'s recognized as relative path'
    echo 'from repository\'s root directory. And jump to it.'
end

function cd-gitroot -d 'Jump to git repo\'s root'
    if not command git rev-parse --git-dir > /dev/null ^ /dev/null
        echo 'It\'s out of working tree!' 1>&2
        return 1
    end

    set root_path (git rev-parse --show-toplevel)
    set argc (count $argv)

    if test (count $argv) -eq 0
        cd $root_path
    else if test (count $argv) -eq 1; and test -n $relative_path
        set relative_path $argv
        cd "$root_path/$relative_path"
    else
        __cdgitroot_usage
    end
end

function __cdgitroot_complete
    set directories
    set root_path (git rev-parse --show-toplevel)
    set dirs \
        (find $root_path -type d -name '.git' -prune -o -type d -print | \
                sed "s#$root_path/##g" | sed "s#$root_path##g")
    complete -c cd-gitroot --no-files -d 'path' -a "$dirs"
end
__cdgitroot_complete

Add error bundle in completion function

function __cdgitroot_usage
    echo 'Usage: cd-gitroot [PATH]'
    echo 'Jump to git repository\'s root directory.'
    echo 'If PATH is specified, it\'s recognized as relative path'
    echo 'from repository\'s root directory. And jump to it.'
end

function cd-gitroot -d 'Jump to git repo\'s root'
    if not command git rev-parse --git-dir > /dev/null ^ /dev/null
        echo 'It\'s out of working tree!' 1>&2
        return 1
    end

    set root_path (git rev-parse --show-toplevel)
    set argc (count $argv)

    if test (count $argv) -eq 0
        cd $root_path
    else if test (count $argv) -eq 1; and test -n $relative_path
        set relative_path $argv
        cd "$root_path/$relative_path"
    else
        __cdgitroot_usage
    end
end

function __cdgitroot_complete
    set directories
    set root_path (git rev-parse --show-toplevel)
    if test $status -ne 0
        return 1
    end

    set dirs \
        (find $root_path -type d -name '.git' -prune -o -type d -print | \
                sed "s#$root_path/##g" | sed "s#$root_path##g")
    complete -c cd-gitroot --no-files -d 'path' -a "$dirs"
end
__cdgitroot_complete


function __fuzzy_package_json_script
  if test -e "package.json"
    jq '.scripts | keys[]' package.json | tr -d '"' | __fuzzy_find | read tempvar

    if [ $tempvar ]
      commandline -i $tempvar
    end
  end
end


# set editor
set -xg EDITOR vim

# set no greeting
set fish_greeting

# Abbreviations
abbr -a c clear

# Git
abbr -a ga git add
abbr -a gap git add --patch
abbr -a gc git commit -v
abbr -a gco git checkout
abbr -a gd git diff
abbr -a gf git fetch
abbr -a gl git l
abbr -a gll git ll
abbr -a gpl git pull
abbr -a gp git push
abbr -a gpo git push origin
abbr -a gr git rebase
abbr -a grc git rebase --continue
abbr -a gs git status -s

# rake
abbr -a rdm rake db:migrate
abbr -a rdr rake db:rollback
abbr -a rdtp rake db:test:prepare

# rails
abbr -a rc rails console
abbr -a bers bundle exec rails server -b 0.0.0.0

# Path to Oh My Fish install.
set -q XDG_DATA_HOME
  and set -gx OMF_PATH "$XDG_DATA_HOME/omf"
  or set -gx OMF_PATH "$HOME/.local/share/omf"

# Load Oh My Fish configuration.
source $OMF_PATH/init.fish

# source each plugin file
for file in ~/.config/fish/conf.d/*.fish
  source $file
end

Fix bottom of command promt error

# set no greeting
set fish_greeting

# Abbreviations
abbr -a c clear

# Git
abbr -a ga git add
abbr -a gap git add --patch
abbr -a gc git commit -v
abbr -a gco git checkout
abbr -a gd git diff
abbr -a gf git fetch
abbr -a gl git l
abbr -a gll git ll
abbr -a gpl git pull
abbr -a gp git push
abbr -a gpo git push origin
abbr -a gr git rebase
abbr -a grc git rebase --continue
abbr -a gs git status -s

# rake
abbr -a rdm rake db:migrate
abbr -a rdr rake db:rollback
abbr -a rdtp rake db:test:prepare

# rails
abbr -a rc rails console
abbr -a bers bundle exec rails server -b 0.0.0.0

# source each plugin file
for file in ~/.config/fish/conf.d/*.fish
  source $file
end


Add initial fish function for retrieving password frm bitwarden

function bwPassword --description "Lookup password in bitwarden based on username and search term"

    set -l options (fish_opt -s h -l help)
    set options $options (fish_opt --short s --long search --required-val)
    set options $options (fish_opt --short u --long username --required-val)

    argparse $options -- $argv
    or return # exit if argparse failed because it found an option it didn't recognize - it will print an error

    # If -h or --help is given, we print a little help text and return
    if set -q _flag_help
        help
        return 0
    end

    # If -s or --search is given, get the search term from one or the other
    # otherwise return with non-zero exit code as this is required
    if set -q _flag_search
        set searchTerm $_flag_search
    else if set -q _flag_s
        set searchTerm $_flag_s
    else
        echo "Search term is required"
        help
        return 1
    end

    echo Searching for term: $searchTerm

    # If -u or --username is given, get the username from one or the other
    # otherwise return with non-zero exit code as this is required.
    if set -q _flag_username
        set user $_flag_username
    else if set -q _flag_u
        set user $_flag_u
    else
        echo "Username is required"
        help
        return 1
    end

    echo "Searching for user: $user"

    bw list items --search $searchTerm |  jq --raw-output ". | map(select(.login.username     == \"$user\")) | .[0] | .login.password"
end

function help
    echo "Usage:"
    echo "bwPassword (-s/--search SEARCH_TERM) (-u/--username USER_NAME)"
end


fish_vi_key_bindings

for word in "$HOME/"{bin,.local/bin,go/bin,node_modules/.bin,.gem/ruby/*/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)

Use home copy of golang

fish_vi_key_bindings

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

set -x GOROOT "$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)


if not status --is-interactive
    exit 0
end

set -l config_home "$XDG_CONFIG_HOME"
set -l data_home "$XDG_DATA_HOME"

# install fisher
if not type fisher >/dev/null 2>&1
    curl -Lo "$config_home/fish/functions/fisher.fish" --create-dirs git.io/fisher
    cat "$config_home/fish/fishfile" | fisher install
end

# vim bindings
fish_vi_key_bindings

# aliases
source "$config_home/fish/aliases.fish"

# fzf
if test -d "$data_home/fzf"
    set -gx PATH "$data_home/fzf/bin" $PATH
    set -gx FZF_LEGACY_KEYBINDINGS 0
end

# z
set -gx Z_CMD "j"
set -gx Z_DATA "$data_home/z"

# base16 colour scheme
if test ! -d "$data_home/base16-shell"
    git clone https://github.com/chriskempson/base16-shell.git "$data_home/base16-shell"
end

eval sh "$data_home/base16-shell/scripts/base16-oceanicnext.sh"

Fix fish interactive shell on macOS

if not status --is-interactive
    exit 0
end

set -l config_home "$XDG_CONFIG_HOME"
set -l data_home "$XDG_DATA_HOME"

# install fisher
if not type fisher >/dev/null 2>&1
    curl -Lo "$config_home/fish/functions/fisher.fish" --create-dirs git.io/fisher
    cat "$config_home/fish/fishfile" | fisher install
end

# vim bindings
fish_vi_key_bindings

# aliases
source "$config_home/fish/aliases.fish"

# fzf
if test -d "$data_home/fzf"
    set -gx PATH "$data_home/fzf/bin" $PATH
    set -gx FZF_LEGACY_KEYBINDINGS 0
end

# z
set -gx Z_CMD "j"
set -gx Z_DATA "$data_home/z"

# base16 colour scheme
if test ! -d "$data_home/base16-shell"
    git clone https://github.com/chriskempson/base16-shell.git "$data_home/base16-shell"
end

eval sh "$data_home/base16-shell/scripts/base16-oceanicnext.sh"

if [ (uname) = "Darwin" ]
    bass source "$HOME/.profile"
    set -gx GPG_TTY (tty)
end


# 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 'commit message' (file;optional)"
    if argv[2]
        git add $argv[2]
    else
        git add -A
    end
    git commit -m $argv[1]
    git push
end

Fix gacp function with test 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 'commit message' (file;optional)"
    if test argv[2]
        git add $argv[2]
    else
        git add -A
    end
    git commit -m $argv[1]
    git push
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

set FDIR (fish_config_dir)

set PATH ~/.dotfiles/bin $PATH

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
else
  source $FDIR/remote.fish
end

# Remove temporary variable afterwise
unset FDIR

Fix some PATH and allow using .secrets.fish file

##
# 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


# Virtual Environment
#Initialise Python, Ruby, Perl and Java environment if installed
if command -v pyenv > /dev/null; status --is-interactive; and . (pyenv init -|psub); end
if command -v pyenv-virtualenv-init > /dev/null; status --is-interactive; and . (pyenv virtualenv-init -|psub); end
if command -v rbenv > /dev/null; status --is-interactive; and . (rbenv init -|psub); end
if command -v nodenv > /dev/null; status --is-interactive; and . (nodenv init -|psub); end
if command -v plenv > /dev/null; status --is-interactive; and . (plenv init -|psub); end
#if command -v jenv > /dev/null; status --is-interactive; and . (jenv init -|psub); end	#not working
if command -v jenv > /dev/null; fenv 'eval "$(jenv init -)"'; end

#$HOME/.nvm/versions/node/v5.0.0/bin
#set -x WORKON_HOME=$HOME/.virtualenvs
#set -x PROJECT_HOME=$HOME/Projects
#source /usr/local/bin/virtualenvwrapper.sh

Replace . with source to avoid an error

# Virtual Environment
#Initialise Python, Ruby, Perl and Java environment if installed
if command -v pyenv > /dev/null; status --is-interactive; and source (pyenv init -|psub); end
if command -v pyenv-virtualenv-init > /dev/null; status --is-interactive; and source (pyenv virtualenv-init -|psub); end
if command -v rbenv > /dev/null; status --is-interactive; and source (rbenv init -|psub); end
if command -v nodenv > /dev/null; status --is-interactive; and source (nodenv init -|psub); end
# if command -v plenv > /dev/null; status --is-interactive; and source (plenv init -|psub); end
# if command -v jenv > /dev/null; status --is-interactive; and source (jenv init -|psub); end	#not working
if command -v jenv > /dev/null; fenv 'eval "$(jenv init -)"'; end

#$HOME/.nvm/versions/node/v5.0.0/bin
#set -x WORKON_HOME=$HOME/.virtualenvs
#set -x PROJECT_HOME=$HOME/Projects
#source /usr/local/bin/virtualenvwrapper.sh


#!/usr/bin/env fish

# mysql
set -g fish_user_paths "/usr/local/opt/mysql@5.6/bin" $fish_user_paths

Add helm path for jobteaser/fish

#!/usr/bin/env fish

# mysql
set -g fish_user_paths "/usr/local/opt/mysql@5.6/bin" $fish_user_paths

# helm
set -g fish_user_paths "/usr/local/opt/helm@2/bin" $fish_user_paths


function pewpew
	for env in {2,3,alpha}
        for task in {wheel,install}
            pew in $env pip $task -r ~/.requirements.txt
        end
    end
end

Update to Python beta environment

function pewpew
	for env in {2,3,beta}
        for task in {wheel,install}
            pew in $env pip $task -r ~/.requirements.txt
        end
    end
end


# name: nai
# Display the following bits on the left:
# * Current directory name
# * Git branch and dirty state (if inside a git repo)

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

function _git_dirty
  echo (command git status -s --ignore-submodules=dirty ^/dev/null)
end

function fish_prompt
  set -l yellow (set_color yellow)
  set -l green (set_color green)
  set -l normal (set_color normal)

  set -l cwd (basename (prompt_pwd))

  echo -e ""

  echo -n -s ' ' $cwd $normal

  if [ (_git_branch_name) ]
    set -l git_branch (_git_branch_name)

    if [ (_git_dirty) ]
      set git_info $yellow $git_branch
    else
      set git_info $green $git_branch
    end
    echo -n -s ' ' $git_info $normal
  end

  echo -n -s ' ' $normal

end

Make stderr redirection compatible with Fish 3.0.

# name: nai
# Display the following bits on the left:
# * Current directory name
# * Git branch and dirty state (if inside a git repo)

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

function _git_dirty
  echo (command git status -s --ignore-submodules=dirty 2> /dev/null)
end

function fish_prompt
  set -l yellow (set_color yellow)
  set -l green (set_color green)
  set -l normal (set_color normal)

  set -l cwd (basename (prompt_pwd))

  echo -e ""

  echo -n -s ' ' $cwd $normal

  if [ (_git_branch_name) ]
    set -l git_branch (_git_branch_name)

    if [ (_git_dirty) ]
      set git_info $yellow $git_branch
    else
      set git_info $green $git_branch
    end
    echo -n -s ' ' $git_info $normal
  end

  echo -n -s ' ' $normal

end


function tab.xfce4_terminal -a cdto
  xfce4-terminal --tab --working-directory "$cdto"
end

Include cmd execution for xfce4-terminal

function tab.xfce4_terminal -a cdto cmd
  xfce4-terminal --tab --working-directory "$cdto" -e "fish -c '$cmd; exec fish'"
end


for file in (ls ./src/components/ | grep -v 'reactUtil' | grep -v 'todo' | grep -v "BaseDialog" | grep -v "Util")
  echo "Generate $name"
  set name (echo $file | cut -d '.' -f1 )
  node ./scripts/react-docgen.js ./src/components/$file > docs/$name.json
end

Clean "docs" directory before generating

rm ./docs/*.json

for file in (ls ./src/components/ | grep -v 'reactUtil' | grep -v 'todo' | grep -v "BaseDialog" | grep -v "Util")
  echo "Generate $name"
  set name (echo $file | cut -d '.' -f1 )
  node ./scripts/react-docgen.js ./src/components/$file > docs/$name.json
end


function __z_complete -d "add completions"
  set -l __z_marks (awk '
    BEGIN { FS="|"}
    /1/ {print $1}
    ' < $Z_DATA)

  complete -c $Z_CMD -a "$__z_marks" -f
  complete -c $ZO_CMD -a "$__z_marks" -f
end

Add support for paths with single/double quotes

function __z_complete -d "add completions"
  set -l __z_marks (string replace -r '\|.*' '' <$Z_DATA | string escape)

  complete -c $Z_CMD -a "$__z_marks" -f
  complete -c $ZO_CMD -a "$__z_marks" -f
end


function gityaw -d "Replace Git HTTPS remote by SSH"
  if not git status >/dev/null ^&1
    echo "This doesn't look to be a git repository"
    return 1
  end

  if not set remote (command git remote show)
    echo "No remote available"
    return 1
  end

  set https (command git remote get-url $remote)

  if echo $https | grep -q '.*@.*:.*'
    echo "Git remote looks to be already a valid SSH remote"
    return 1
  end

  set regex 's/https:\/\/\(.*\)\/\(.*\)\/\(.*\)\(.git\)*/git@\1:\2\/\3.git/'

  echo $https | sed -e "$regex" | read -l ssh

  command git remote set-url "$remote" "$ssh"

  echo "Replaced '$https' by '$ssh'"
end

Allow processing of multiple remotes, can specify them as arguments too

function gityaw -d "Replace Git HTTPS remote by SSH"
  if not git status >/dev/null ^&1
    echo "This doesn't look to be a git repository"
    return 1
  end

  if test (count $argv) -gt 0
    set remotes $argv
  else
    if not set remotes (command git remote show)
      echo "No remote available"
      return 1
    end
  end

  for remote in $remotes
    echo "Processing remote $remote..."
    set https (command git remote get-url $remote)

    if echo $https | grep -q '.*@.*:.*'
      echo "Git remote looks to be already a valid SSH remote"
    else
      set regex 's/https:\/\/\(.*\)\/\(.*\)\/\(.*\)\(.git\)*/git@\1:\2\/\3.git/'
      echo $https | sed -e "$regex" | sed -e 's/\.git\.git$/\.git/' | read -l ssh
      command git remote set-url "$remote" "$ssh"
      echo "Replaced '$https' by '$ssh'"
    end
  end
end


# Shortcuts
alias reload! "source ~/.config/fish/config.fish"
alias ... "cd ../.."
alias dl "cd ~/Downloads"
alias dt "cd ~/Desktop"
alias c "cd ~/code"
alias storm="open -a (mdfind -name 'kMDItemFSName==\"*.app\"' -onlyin /Applications/ | grep 'WebStorm.')"
alias pubkey="pbcopy < ~/.ssh/id_ed25519.pub | echo '=> Public key copied to pasteboard.'"

# Show/hide hidden files in Finder
alias show="defaults write com.apple.finder AppleShowAllFiles -bool true && killall Finder"
alias hide="defaults write com.apple.finder AppleShowAllFiles -bool false && killall Finder"

Use `lsd` instead of `ls`

# Apps… but better
alias ls lsd

# Shortcuts
alias reload! "source ~/.config/fish/config.fish"
alias ... "cd ../.."
alias dl "cd ~/Downloads"
alias dt "cd ~/Desktop"
alias c "cd ~/code"
alias storm="open -a (mdfind -name 'kMDItemFSName==\"*.app\"' -onlyin /Applications/ | grep 'WebStorm.')"
alias pubkey="pbcopy < ~/.ssh/id_ed25519.pub | echo '=> Public key copied to pasteboard.'"

# Show/hide hidden files in Finder
alias show="defaults write com.apple.finder AppleShowAllFiles -bool true && killall Finder"
alias hide="defaults write com.apple.finder AppleShowAllFiles -bool false && killall Finder"


# 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 'commit message' (file;optional)"
    if test argv[2]
        git add $argv[2]
    else
        git add -A
    end
    git commit -m $argv[1]
    git push
end

Fix gacp function with test 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 -n '$argv[2]'
#         git add $argv[2]
#     else
#         git add -A
#     end
#     git commit -m $argv[1]
#     git push
# end


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

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

    set --local subnet vpcs/$vpc/subnets/$name
    set --local zone (get $subnet/availability-zone)
    set --local cidr (get $subnet/cidr-block)

    if empty "$zone"
        if test (printf $zone | wc -c) = 1
            if has region vpcs/$vpc
                set zone (get vpcs/$vpc/region)$zone
            else
                print-status error "Shorthand zone $zone requires an explicit region for the VPC."
                return 2
            end
        end

        if not contains $zone (availability-zones)
            print-status error "$zone is not a valid availability zone for this account or region."
            return 2
        end
    end
end


function peco_select_ghq_repository
  set -l query (commandline)

  if test -n $query
    set peco_flags --query "$query"
  end

  ghq list | peco $peco_flags | read line

  if [ $line ]
    ghq root | read dir
    cd $dir/$line
    commandline -f repaint
  end
end

Modify cd to ghq look

function peco_select_ghq_repository
  set -l query (commandline)

  if test -n $query
    set peco_flags --query "$query"
  end

  ghq list | peco $peco_flags | read line

  if [ $line ]
    ghq look $line
    commandline -f repaint
  end
end


Add fish function to fuzzy run npm scripts

#!/usr/bin/env fish

function n,

  if ! test -x /usr/local/bin/jq
    echo "jq not installed"
    return 2
  end

  if ! test -x /usr/local/bin/fzy
    echo "fzy not installed"
    return 2
  end

  argparse -n 'n,' 'n' -- $argv
  set cmd (cat package.json | jq .scripts | awk 'NR>2 {print last} {last=$0}' | fzy)

  if [ ! $cmd ]
    return 1
  end

  npm run (echo $cmd | awk -F '":' '{print $1}' | sed 's/"//g' | sed 's/^[  ]*//')
end


rvm use default > /dev/null

Check for existence of rvm function and install if not

if not functions --query rvm
    curl --create-dirs -o ~/.config/fish/functions/rvm.fish https://raw.github.com/lunks/fish-nuggets/master/functions/rvm.fish
end

rvm use default > /dev/null


# urdh prompt theme, by Simon Sigurdhsson <http://github.com/urdh/>
function fish_greeting --description 'Print the shell greeting'
    set -l c_n (set_color normal)
    set -l c_w (set_color cyan)

    set -l location (printf "%sWelcome to %s%s%s" $c_n $c_w (hostname) $c_n)
    set -l system (printf "%sRunning %s%s%s on %s%s%s" $c_n $c_w (uname -mrs) $c_n $c_w (tty | sed -e 's/.*tty\(.*\)/\1/') $c_n)
    set -l datetime (printf "%sIt is %s%s%s (%s) on %s%s%s" $c_n $c_w (date +%T) $c_n (date +%Z) $c_w (date +%F) $c_n)

    printf "\n  %s\n  %s\n  %s\n\n" $location $system $datetime
end

Update the greeting to have colors that better match the rest of the theme

# urdh prompt theme, by Simon Sigurdhsson <http://github.com/urdh/>
function fish_greeting --description 'Print the shell greeting'
    set -l c_n (set_color af0087)
    set -l c_w (set_color green)

    set -l location (printf "%sWelcome to %s%s%s" $c_n $c_w (hostname) $c_n)
    set -l system (printf "%sRunning %s%s%s on %s%s%s" $c_n $c_w (uname -mrs) $c_n $c_w (tty | sed -e 's/.*tty\(.*\)/\1/') $c_n)
    set -l datetime (printf "%sIt is %s%s%s (%s) on %s%s%s" $c_n $c_w (date +%T) $c_n (date +%Z) $c_w (date +%F) $c_n)

    printf "\n  %s\n  %s\n  %s\n\n" $location $system $datetime
end


Add function to create a subnet in a VPC

function vpc-create-subnet --argument vpc cidr availability_zone
    trace (status --current-filename) $argv

    if empty "$vpc" "$cidr"
        usage vpc-create-subnet '<vpc>' '<cidr>' '[availability-zone]'
        return (false)
    end

    aws ec2 create-subnet --vpc-id $vpc --cidr-block $cidr --availability-zone $availability_zone
end


function __fisher_path_update -a path
    pushd $path

    set -l branch

    if not set branch (sed "s|.*/||" < .git/HEAD)
        return 1
    end

    if test "$branch" != master
        git stash --quiet ^ /dev/null
        git checkout master --quiet ^ /dev/null
    end

    if not git pull --rebase origin master --quiet ^ /dev/null
        git rebase --abort --quiet
        git fetch origin master --quiet
        git reset --hard FETCH_HEAD --quiet
        git clean -d --force --quiet
    end

    if test "$branch" != master
        git checkout "$branch" --quiet
        git stash apply --quiet ^ /dev/null
    end

    popd
end

Fix regression causing update to fail in some plugins.

function __fisher_path_update -a path
    pushd $path

    set -l branch

    if not set branch (sed "s|.*/||" < .git/HEAD)
        return 1
    end

    git stash --quiet ^ /dev/null
    git checkout master --quiet ^ /dev/null

    if not git pull --rebase origin master --quiet
        git rebase --abort --quiet
        git fetch origin master --quiet
        git reset --hard FETCH_HEAD --quiet
        git clean -d --force --quiet
    end ^ /dev/null

    if test ! -z "$branch"
        git checkout "$branch" --quiet
    end

    git stash apply --quiet ^ /dev/null

    popd
end


set fish_greeting ""
set LANG en_GB.UTF-8
set PATH ~/bin $PATH
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

# Hook up node and ruby version managers.
if [ -d ~/.nvm ]
  nvm use default --silent
end

if [ -d ~/.rvm ]
  rvm default
end

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

Disable nvm and rvm for now

set fish_greeting ""
set LANG en_GB.UTF-8
set PATH ~/bin $PATH
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

# Hook up node and ruby version managers.
# if [ -d ~/.nvm ]
#   nvm use default --silent
# end

# if [ -d ~/.rvm ]
#   rvm default
# end

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


function cdf --description="If on OSX, `cd` to the directory the front Finder window is open to."
	set --local target (osascript -e 'tell application "Finder" to if (count of Finder windows) > 0 then get POSIX path of (target of front Finder window as text)')
	if test -n target
		echo "Changing directory to: $target"
		cd $target
	else
		echo "No Finder window found." >&2
		return 1
	end
end

Add a check for operating system.

function cdf --description="If on OSX, `cd` to the directory the front Finder window is open to."
	# first we check if we're on OSX
	if not test (uname -s) = "Darwin"
		echo "We are not on OSX." >&2
		return 3
	end
	set --local target (osascript -e 'tell application "Finder" to if (count of Finder windows) > 0 then get POSIX path of (target of front Finder window as text)')
	if test -n target
		echo "Changing directory to: $target"
		cd $target
	else
		echo "No Finder window found." >&2
		return 1
	end
end


function git_cleanup
  for branch in (git branch -vv | grep ' gone' | cut -d' ' -f1-3 | sed -e 's/^[ \t]*//')
    if user_prompt "Remove deleted branch $branch?"
      git branch -D $branch
    end
  end
end

Use POSIX space char class instead

function git_cleanup
  for branch in (git branch -vv | grep ' gone' | cut -d' ' -f1-3 | sed -e 's/^[[:space:]]*//')
    if user_prompt "Remove deleted branch $branch?"
      git branch -D $branch
    end
  end
end


append-to-path ~/projects/git-toolbelt

set -gx WORKON_HOME ~/.virtualenvs
set -gx PYTHONPATH ~/.local/bin

append-to-path ~/.local/bin
append-to-path /Applications/Postgres.app/Contents/Versions/9.4/bin

Upgrade Postgres version to 9.5

append-to-path ~/projects/git-toolbelt

set -gx WORKON_HOME ~/.virtualenvs
set -gx PYTHONPATH ~/.local/bin

append-to-path ~/.local/bin
append-to-path /Applications/Postgres.app/Contents/Versions/9.5/bin


function fish_prompt --description 'Write out the prompt'
  # Set custom color variables
  set -l username_color fdd8aa
  set -l prompt_color 8cd6ff

  set -l last_status $status

  # PWD
  set_color $fish_color_cwd
  echo -n (pwd | sed -e "s|$HOME|~|")
  set_color normal

  __fish_git_prompt
  echo

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

  echo -n '∫ '
  set_color normal
end

Add number of suspended jobs to prompt

function fish_prompt --description 'Write out the prompt'
	# Set custom color variables
	set -l username_color fdd8aa
	set -l prompt_color 8cd6ff

	set -l last_status $status

	# PWD
	set_color $fish_color_cwd
	echo -n (pwd | sed -e "s|$HOME|~|")
	set_color normal

	__fish_git_prompt

	set jobs_count (jobs | wc -l | xargs)
	if test $jobs_count != '0'
		printf ' (↩ %s)' $jobs_count
	end

	echo

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

	echo -n '∫ '
	set_color normal
end


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

# Customize Oh My Fish configuration path.
#set -gx OMF_CONFIG "$HOME/.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"

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

source /usr/share/autojump/autojump.fish
source /usr/local/share/autojump/autojump.fish
source (pew shell_config)

Add to $PATH only if missing in fish

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

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

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

fish_vi_mode

for word in "$HOME/"{bin,.local/bin,Library/Python/2.7/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

source /usr/share/autojump/autojump.fish
source /usr/local/share/autojump/autojump.fish
source (pew shell_config)


# Disable fish greeting
set fish_greeting ""

# Aliases
alias vim="nvim"

# Set environment variables
#set -x NVIM_TUI_ENABLE_TRUE_COLOR 1

Remove neovim alias while vimrc issues are being fixed

# Disable fish greeting
set fish_greeting ""

# Aliases
#alias vim="nvim"

# Set environment variables
#set -x NVIM_TUI_ENABLE_TRUE_COLOR 1


# List only directories
alias lsd='ls -l | grep "^d"'

alias tree 'tree --dirsfirst -ChFQ'
function tree1; tree -L 1 $argv; end
function tree2; tree -L 2 $argv; end
function tree3; tree -L 3 $argv; end
function tree4; tree -L 4 $argv; end
function tree5; tree -L 5 $argv; end
function tree6; tree -L 6 $argv; end

alias treea "tree -a -I '.git|.stack-work' --dirsfirst -ChFQ"
function treea;  tree $argv; end
function treea1; tree -L 1 $argv; end
function treea2; tree -L 2 $argv; end
function treea3; tree -L 3 $argv; end
function treea4; tree -L 4 $argv; end
function treea5; tree -L 5 $argv; end
function treea6; tree -L 6 $argv; end

function bigdirs; du -h --max-depth=1 $argv | sort -h; end

# Stack
alias ghc 'stack exec -- ghc'
alias ghci 'stack exec -- ghci'

# Old Habits
alias :q exit

alias gpg gpg2

# git
alias gst 'git status'

Remove duplicate function for treea

# List only directories
alias lsd='ls -l | grep "^d"'

alias tree 'tree --dirsfirst -ChFQ'
function tree1; tree -L 1 $argv; end
function tree2; tree -L 2 $argv; end
function tree3; tree -L 3 $argv; end
function tree4; tree -L 4 $argv; end
function tree5; tree -L 5 $argv; end
function tree6; tree -L 6 $argv; end

alias treea "tree -a -I '.git|.stack-work' --dirsfirst -ChFQ"
function treea1; tree -L 1 $argv; end
function treea2; tree -L 2 $argv; end
function treea3; tree -L 3 $argv; end
function treea4; tree -L 4 $argv; end
function treea5; tree -L 5 $argv; end
function treea6; tree -L 6 $argv; end

function bigdirs; du -h --max-depth=1 $argv | sort -h; end

# Stack
alias ghc 'stack exec -- ghc'
alias ghci 'stack exec -- ghci'

# Old Habits
alias :q exit

alias gpg gpg2

# git
alias gst 'git status'


function __gabbr_expand

    # expand abbreviations
    if test 0 = (count (commandline -poc))
        for abbr in $fish_user_abbreviations
            echo $abbr | read word phrase
            if test "$word" = (commandline -t)
                commandline -t $phrase
            end
        end
    end

    # expand global abbreviations
    for abbr in $global_abbreviations
        echo $abbr | read word phrase

        if string match -q "*.$word" (commandline -t)
            if string match -q -- '-x *' $phrase
                set -l file (commandline -t)
                if test 0 = (count (commandline -poc)) -a -f "$file" -a ! -x "$file"
                    set -l cmd (string sub -s 4 -- $phrase)
                    commandline -t "$cmd $file"
                end
            end
        else if test "$word" = (commandline -t)
            if string match -q -- '-f *' $phrase
                # --function option
                set -l cmd (string sub -s 4 -- $phrase)
                eval $cmd ^/dev/null | string join ' ' | read -l buf
                and commandline -t $buf
            else
                commandline -t $phrase
            end
        end
    end

end

Fix __gabbr_expad: add -- to string match

function __gabbr_expand

    # expand abbreviations
    if test 0 = (count (commandline -poc))
        for abbr in $fish_user_abbreviations
            echo $abbr | read word phrase
            if test "$word" = (commandline -t)
                commandline -t $phrase
            end
        end
    end

    # expand global abbreviations
    for abbr in $global_abbreviations
        echo $abbr | read word phrase

        if string match -q -- "*.$word" (commandline -t)
            if string match -q -- '-x *' $phrase
                set -l file (commandline -t)
                if test 0 = (count (commandline -poc)) -a -f "$file" -a ! -x "$file"
                    set -l cmd (string sub -s 4 -- $phrase)
                    commandline -t "$cmd $file"
                end
            end
        else if test "$word" = (commandline -t)
            if string match -q -- '-f *' $phrase
                # --function option
                set -l cmd (string sub -s 4 -- $phrase)
                eval $cmd ^/dev/null | string join ' ' | read -l buf
                and commandline -t $buf
            else
                commandline -t $phrase
            end
        end
    end

end


. helper.fish

function subject
  fry-rubies | col
end

it 'contains system'; begin
  if contains '*32m system' (subject)
    pass
  else
    fail
  end
end

it 'contains rubies'; begin
  if contains '30mBm  dummy-1' (subject)
    pass
  else
    fail
  end
end

it 'highlights current'; begin
  stub fry-current dummy-1

  if contains '30mBm*32m dummy-1' (subject)
    pass
  else
    fail
  end
end

Make test unaware of color codes

. helper.fish

function subject
  fry-rubies
end

it 'contains system'; begin
  function result
    echo -n '*'
    set_color green
    echo -n ' system'
  end

  if contains (result) (subject)
    pass
  else
    fail
  end
end

it 'contains rubies'; begin
  function result
    set_color normal
    echo -n '  dummy-1'
  end

  if contains (result) (subject)
    pass
  else
    fail
  end
end

it 'highlights current'; begin
  function result
    set_color normal
    echo -n '*'
    set_color green
    echo -n ' dummy-1'
  end

  stub fry-current dummy-1

  if contains (result) (subject)
    pass
  else
    fail
  end
end


# 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

fish_add_path /opt/homebrew/bin

direnv hook fish | source

source /opt/homebrew/opt/asdf/asdf.fish

source ~/.secrets.fish

set --export EDITOR "code"

# Required for postgres to build, see https://github.com/smashedtoatoms/asdf-postgres/issues/52
set --export HOMEBREW_PREFIX "/opt/homebrew"

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

Remove hack for inserting paths

# Turn off the default greeting
set fish_greeting

fish_add_path /opt/homebrew/bin

direnv hook fish | source

source /opt/homebrew/opt/asdf/asdf.fish

source ~/.secrets.fish

set --export EDITOR "code"

# Required for postgres to build, see https://github.com/smashedtoatoms/asdf-postgres/issues/52
set --export HOMEBREW_PREFIX "/opt/homebrew"

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


function fish_right_prompt

    set -l last_status $status
    set -l duration (__fish_prompt_timing)
    switch $last_status
        case 0
            set last_status ''
        case '*'
            set last_status (set_color red) ' (' $last_status ')' (set_color normal)
    end

    echo -s -n $duration $last_status (__fish_git_prompt)
end

Switch duration & status code (prompt)

function fish_right_prompt

    set -l last_status $status
    set -l duration (__fish_prompt_timing)
    switch $last_status
        case 0
            set last_status ''
        case '*'
            set last_status (set_color red) '(' $last_status ') ' (set_color normal)
    end

    echo -s -n $last_status $duration (__fish_git_prompt)
end


# Generates a new private RSA SSH key at ~/.ssh/id_rsa with an optional comment.
# Comment defaults to USER@hostname.
function sshnewkey --argument-names comment
    if test -z $comment
        set comment "$USER@"(hostname)
    end

    set -l keyfile ~/.ssh/id_rsa

    ssh-keygen \
        -t rsa \
        -C $comment \
        -f $keyfile
end

Switch SSH key generation to use ed25519

function sshnewkey \
    --description 'Generates a new private SSH key at ~/.ssh/id_ed25519 with an optional comment. Comment defaults to USER@hostname'
    --argument-names comment

    if test -z $comment
        set comment "$USER@"(hostname)
    end

    set -l keyfile ~/.ssh/id_ed25519

    ssh-keygen \
        -t ed25519 \
        -C $comment \
        -f $keyfile
end


set LS_COLORS dxfxcxdxbxegedabagacad

alias ls 'command ls -FG'
alias l ls
alias ll 'ls -la'
alias rm 'rm -i'
alias mv 'mv -i'
alias mkdir 'mkdir -p'
alias du 'du -kh'
alias df 'df -kh'

# Colorized cat (will guess file type based on contents)
alias ccat 'pygmentize -g'

alias pm 'python manage.py'
alias pmm 'python manage.py migrate'
alias pmmm 'python manage.py makemigrations'
alias pms 'python manage.py shell'
alias pmsp 'python manage.py shell_plus'
alias pmr 'python manage.py runserver'
alias ipn 'ipython notebook'
alias pmsm 'python manage.py showmigrations'
alias pmspnb 'python manage.py shell_plus --notebook'
alias pmmmn 'python manage.py makemigrations --name'
alias pmmmen 'python manage.py makemigrations --empty --name'

alias git hub
alias top 'glances'

alias pkill-emacs 'pkill -SIGUSR2 Emacs'

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

alias psql pgcli
alias mysql mycli

alias cat 'bat --theme=TwoDark'

Comment out my python pm alias

set LS_COLORS dxfxcxdxbxegedabagacad

alias ls 'command ls -FG'
alias l ls
alias ll 'ls -la'
alias rm 'rm -i'
alias mv 'mv -i'
alias mkdir 'mkdir -p'
alias du 'du -kh'
alias df 'df -kh'

# Colorized cat (will guess file type based on contents)
alias ccat 'pygmentize -g'

# alias pm 'python manage.py'
alias pmm 'python manage.py migrate'
alias pmmm 'python manage.py makemigrations'
alias pms 'python manage.py shell'
alias pmsp 'python manage.py shell_plus'
alias pmr 'python manage.py runserver'
alias ipn 'ipython notebook'
alias pmsm 'python manage.py showmigrations'
alias pmspnb 'python manage.py shell_plus --notebook'
alias pmmmn 'python manage.py makemigrations --name'
alias pmmmen 'python manage.py makemigrations --empty --name'

alias git hub
alias top 'glances'

alias pkill-emacs 'pkill -SIGUSR2 Emacs'

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

alias psql pgcli
alias mysql mycli

alias cat 'bat --theme=TwoDark'


# Open config in vim
function vcf
  vim ~/.config/fish/config.fish
end

# Open config in atom
function acf
  atom ~/.config/fish
end

# Reload config
function recon
  source ~/.config/fish/config.fish
end

# Open config in atom
function ccf
  code ~/.config/fish
end

# Pull latest config from github
function cpull
  set curr_dir $PWD
  git pull
  cd ~/.config/fish
  cd $curr_dir
end

# Push latest config to github
function cfp
  set curr_dir $PWD
  cd ~/.config/fish
  git commit -am $argv
  git push origin
  cd $curr_dir
end

Add `conf` shortcut to get to the config folder

# Open config in vim
function vcf
  vim ~/.config/fish/config.fish
end

function conf
  cd ~/.config/fish
end

# Open config in atom
function acf
  atom ~/.config/fish
end

# Reload config
function recon
  source ~/.config/fish/config.fish
end

# Open config in atom
function ccf
  code ~/.config/fish
end

# Pull latest config from github
function cpull
  set curr_dir $PWD
  git pull
  cd ~/.config/fish
  cd $curr_dir
end

# Push latest config to github
function cfp
  set curr_dir $PWD
  cd ~/.config/fish
  git commit -am $argv
  git push origin
  cd $curr_dir
end


function fish_prompt
  echo

  set_color -b 333 d91161
  echo -n $USER

  set_color -b 333 666
  echo -n "@"

  set_color cyan
  echo -n (hostname)

  set_color 666
  echo -n ":"

  set_color green
  echo -n $PWD

  set_color white
  echo -n ""

  set_color -b normal normal
  echo " "
  echo -n '» '

end

Make the default prompt include date and time

function fish_prompt
  echo

  set_color -b 222 d91161
  echo -n $USER

  set_color 666
  echo -n "@"

  set_color cyan
  echo -n (hostname)

  set_color 666
  echo -n ":"

  set_color green
  echo -n $PWD

  set_color -b normal 444
  echo -n "     "
  echo -n -s (date +%H:%M) " "
  set_color -b normal 222
  echo -n -s (date +%b | tr '[:upper:]' '[:lower:]' ) " " (date +%d)

  set_color -b normal yellow
  echo ""
  echo -n '» '
  set_color normal

end


# Tab completion for docker-compose (https://github.com/docker/compose).
# Version: 1.9.0

complete -e -c docker-compose

for line in (docker-compose --help | \
             string match -r '^\s+\w+\s+[^\n]+' | \
             string trim)
  set -l doc (string split -m 1 ' ' -- $line)
  complete -c docker-compose -n '__fish_use_subcommand' -xa $doc[1] --description $doc[2]
end

complete -c docker-compose -s f -l file -r                -d 'Specify an alternate compose file'
complete -c docker-compose -s p -l project-name -x        -d 'Specify an alternate project name'
complete -c docker-compose -l verbose                     -d 'Show more output'
complete -c docker-compose -s H -l host -x                -d 'Daemon socket to connect to'
complete -c docker-compose -l tls                         -d 'Use TLS; implied by --tlsverify'
complete -c docker-compose -l tlscacert -r                -d 'Trust certs signed only by this CA'
complete -c docker-compose -l tlscert -r                  -d 'Path to TLS certificate file'
complete -c docker-compose -l tlskey -r                   -d 'Path to TLS key file'
complete -c docker-compose -l tlsverify                   -d 'Use TLS and verify the remote'
complete -c docker-compose -l skip-hostname-check         -d "Don't check the daemon's hostname against the name specified in the client certificate (for example if your docker host is an IP address)"
complete -c docker-compose -s h -l help                   -d 'Print usage'
complete -c docker-compose -s v -l version                -d 'Print version and exit'


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 -rni * -e $argv
end

function does-exist
  return (type -q $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-insentive search for `less`

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 -rni * -e $argv
end

function does-exist
  return (type -q $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 -Ri $argv
end


# Use python2 if found, otherwise fallback to python.
function _python
  if available python2
    python2 $argv
  else
    python $argv
  end
end

Replace `available` usage with `type -q`

# Use python2 if found, otherwise fallback to python.
function _python
  if type -q python2
    python2 $argv
  else
    python $argv
  end
end


# Installs and updates npm modules.
function 🕸__npm
    echo "🕸  NPM"
    echo

    set -l global_packages fast-cli n ralio

    echo "Updating NPM"
    npm install npm@latest -g

    npm install --global $global_packages

    npm doctor
end

Use update instead of reinstalling packages

# Installs and updates npm modules.
# https://docs.npmjs.com/cli
function 🕸__npm
    echo "🕸  NPM"
    echo

    set -l global_packages fast-cli n ralio

    set -l installed_packages (npm list -g --depth=0)
    # Example output:
    # /usr/local/lib
    # ├── fast-cli@0.2.1
    # ├── n@2.1.7
    # ├── npm@4.5.0
    # └── ralio@0.6.1
    # Manual installation check
    # string match "*ralio*" $installed_packages[5]

    echo "Updating NPM"
    npm install npm@latest -g

    # TODO: Add package uninstall

    # Update
    npm update -g

    # TODO: Refactor to only install missing packages
    #npm install --global $global_packages

    npm doctor
end


Add a function to view the contents of a directory using the exa command

function ll $argv
    exa \
    --long \
    --colour=auto \
    --all \
    --group-directories-first \
    --sort name \
    --group \
    --time modified \
    --no-filesize \
    $argv
end


# LANG
# http://curiousabt.blog27.fc2.com/blog-entry-65.html
set -x LANG ja_JP.UTF-8
set -x LESSCHARSET utf-8

# Editor
set -x EDITOR nvim

# Path
set -U fish_user_paths $HOME/.asdf/shims
set -U fish_user_paths $HOME/dotfiles/bin
set -U fish_user_paths $HOME/.bin
set -U fish_user_paths $HOME/.local/bin
set -U fish_user_paths ./bin
set -U fish_user_paths $HOME/.ghq/github.com/apple/sourcekit-lsp/.build/release
set -U fish_user_paths (yarn global bin)
set -U fish_user_paths /usr/local/bin
set -U fish_user_paths /usr/local/sbin
set -U fish_user_paths /sbin
set -x MANPATH $MANPATH /opt/local/man /usr/local/share/man

# homebrew
set -x HOMEBREW_NO_ANALYTICS 1
set -x HOMEBREW_GITHUB_API_TOKEN (security find-generic-password -a 'homebrew-github-token' -w)

# cocoapods
set -x COCOAPODS_DISABLE_STATS true
set bundler_plugin_execs pod fastlane thor

Add path for arm mac

# LANG
# http://curiousabt.blog27.fc2.com/blog-entry-65.html
set -x LANG ja_JP.UTF-8
set -x LESSCHARSET utf-8

# Editor
set -x EDITOR nvim

# Path
set -x PATH /usr/local/bin $PATH
set -x PATH $HOME/.asdf/shims $PATH
set -x PATH $HOME/dotfiles/bin $PATH
set -x PATH $HOME/.bin $PATH
set -x PATH $HOME/.local/bin $PATH
set -x PATH ./bin $PATH
set -x PATH $HOME/ghq/github.com/apple/sourcekit-lsp/.build/releasea $PATH
if test (uname -m) = "arm64"
  set -x PATH /opt/homebrew/bin $PATH
end
set -x PATH /usr/local/bin $PATH
set -x PATH (yarn global bin) $PATH
set -x PATH /usr/local/sbin $PATH
set -x PATH /sbin $PATH
set -x MANPATH $MANPATH /opt/local/man /usr/local/share/man

# homebrew
set -x HOMEBREW_NO_ANALYTICS 1
set -x HOMEBREW_GITHUB_API_TOKEN (security find-generic-password -a "$USER" -s 'homebrew-github-token' -w)

# cocoapods
set -x COCOAPODS_DISABLE_STATS true
set bundler_plugin_execs pod fastlane thor


# Set path
set -x PATH /usr/local/share/npm/bin /usr/local/share/python /usr/local/bin /usr/local/sbin $HOME/bin $PATH

# Initialise rbenv
set PATH $HOME/.rbenv/bin $PATH
set PATH $HOME/.rbenv/shims $PATH
rbenv rehash >/dev/null ^&1

# Include aliases
. $HOME/.files/aliases

# Set default pager and options for less
# (copied from zsh, makes it scroll faster for some reason)
set -x PAGER less
set -x LESS '-F -g -i -M -R -S -w -X -z-4'

# Set colors
set fish_color_command 89adff
set fish_color_cwd ffffa4
set fish_color_host 8cd6ff
set fish_color_user fdd8aa

set GREP_COLOR '' # use default grep color

Remove /usr/local/share/python from PATH since homebrew no longer needs it

# Set path
set -x PATH /usr/local/share/npm/bin /usr/local/bin /usr/local/sbin $HOME/bin $PATH

# Initialise rbenv
set PATH $HOME/.rbenv/bin $PATH
set PATH $HOME/.rbenv/shims $PATH
rbenv rehash >/dev/null ^&1

# Include aliases
. $HOME/.files/aliases

# Set default pager and options for less
# (copied from zsh, makes it scroll faster for some reason)
set -x PAGER less
set -x LESS '-F -g -i -M -R -S -w -X -z-4'

# Set colors
set fish_color_command 89adff
set fish_color_cwd ffffa4
set fish_color_host 8cd6ff
set fish_color_user fdd8aa

set GREP_COLOR '' # use default grep color


# Turn off the default greeting
set fish_greeting

# Add Postgres.app tools to path, but before asdf inits, so asdf's shims end up first
set -gx PATH /Applications/Postgres.app/Contents/Versions/latest/bin $PATH

status --is-interactive; and source /usr/local/opt/asdf/asdf.fish

set __fish_git_prompt_showdirtystate 'yes'
set __fish_git_prompt_showcolorhints 'yes'

set --export EDITOR "code"

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

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

Fix PATH handling for asdf/postgres

# Turn off the default greeting
set fish_greeting

# Add Postgres.app's bin to path, but before asdf inits, so asdf's shims end up first
set PATH /Applications/Postgres.app/Contents/Versions/latest/bin $PATH

status --is-interactive; and source /usr/local/opt/asdf/asdf.fish

set __fish_git_prompt_showdirtystate 'yes'
set __fish_git_prompt_showcolorhints 'yes'

set --export EDITOR "code"

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

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


function oiw --description 'Find a folder in your workspace and cd into it'
	set where ~
    set level 1
    set query "/workspace*$argv"
    set res (find -L $where -mindepth $level -maxdepth (math $level+1) -type d -iwholename "*$query*" -print)
    set shortest (echo $res | sed -e 's/\s\+/\n/g'| awk '{ print length($0) " " $0; }' | sort -n | cut -d ' ' -f 2- | head -1)
    cd $shortest
end

Change OIWs maxdepth to 3

function oiw --description 'Find a folder in your workspace and cd into it'
	set where ~

    set level 1
    set query "/workspace*$argv"
    set res (find -L $where -mindepth $level -maxdepth (math $level+2) -type d -iwholename "*$query*" -print)
    set shortest (echo $res | sed -e 's/\s\+/\n/g'| awk '{ print length($0) " " $0; }' | sort -n | cut -d ' ' -f 2- | head -1)
    cd $shortest
end


function fish_prompt
  set -l tomita_vi_mode "$TOMITA_VI"
	echo

	set_color $fish_color_cwd
  printf '%s' (prompt_pwd)

  set_color normal
  printf '%s ' (__fish_git_prompt)

  if test -z (string match -ri '^no|false|0$' $TOMITA_VI)
    printf '['
    switch $fish_bind_mode
      case default
        set_color --bold red
        printf 'n'
      case insert
        set_color --bold green
        printf 'i'
      case visual
        set_color --bold magenta
        printf 'v'
    end
    set_color normal
    printf '] '
  end

  set_color -o yellow
  printf '⋊> '
  set_color normal
end

Hide VI indicator with env var

function fish_prompt
  set -l tomita_vi_mode "$TOMITA_VI"
	echo

	set_color $fish_color_cwd
  printf '%s' (prompt_pwd)

  set_color normal
  printf '%s ' (__fish_git_prompt)

  if test -z (string match -ri '^no|false|0$' $tomita_vi_mode)
    printf '['
    switch $fish_bind_mode
      case default
        set_color --bold red
        printf 'n'
      case insert
        set_color --bold green
        printf 'i'
      case visual
        set_color --bold magenta
        printf 'v'
    end
    set_color normal
    printf '] '
  end

  set_color -o yellow
  printf '⋊> '
  set_color normal
end


fish_vi_key_bindings

set fish_user_paths "$HOME/"{.local/bin,.local/go/bin,go/bin,node_modules/.bin,.gem/ruby/*/bin}

set -x GOPATH "$HOME/go"
set -x GOROOT "$HOME/.local/go"
set -x GPG_TTY (tty)

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)

Use default Go environment variables

fish_vi_key_bindings

set fish_user_paths "$HOME/"{.local/bin,.local/go/bin,go/bin,node_modules/.bin,.gem/ruby/*/bin}

set -x GPG_TTY (tty)

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 rvm --description='Ruby enVironment Manager'
  # run RVM and capture the resulting environment
  set --local env_file (mktemp -t rvm.fish.XXXXXXXXXX)
  bash -c 'source ~/.rvm/scripts/rvm; rvm "$@"; status=$?; env > "$0"; exit $status' $env_file $argv

  # apply rvm_* and *PATH variables from the captured environment
  and eval (grep '^rvm\|^[^=]*PATH\|^GEM_HOME' $env_file | grep -v '_clr=' | sed '/^[^=]*PATH/s/:/" "/g; s/^/set -xg /; s/=/ "/; s/$/" ;/; s/(//; s/)//')
  # needed under fish >= 2.2.0
  and set -xg GEM_PATH (echo $GEM_PATH | sed 's/ /:/g')

  # clean up
  rm -f $env_file
end

function __handle_rvmrc_stuff --on-variable PWD
  # Source a .rvmrc file in a directory after changing to it, if it exists.
  # To disable this fature, set rvm_project_rvmrc=0 in $HOME/.rvmrc
  if test "$rvm_project_rvmrc" != 0
    set -l cwd $PWD
    while true
      if contains $cwd "" $HOME "/"
        if test "$rvm_project_rvmrc_default" = 1
          rvm default 1>/dev/null 2>&1
        end
        break
      else
        if test -e .rvmrc -o -e .ruby-version -o -e .ruby-gemset
          eval "rvm reload" > /dev/null
          eval "rvm rvmrc load" >/dev/null
          break
        else
          set cwd (dirname "$cwd")
        end
      end
    end

    set -e cwd
  end
end


# A workaround for Fish re-reading config for non-interactive execution:
# https://git.io/yj4KoA
if not status --is-interactive
  exit
end

# fundle
fundle plugin 'edc/bass'
fundle plugin 'brgmnn/fish-docker-compose'
fundle init

# rbenv
if which rbenv > /dev/null
  source (rbenv init -|psub)
end

# pyenv
if which pyenv > /dev/null
  source (pyenv init -|psub)
end

# Default editor
set --export EDITOR "code --wait"

# Go
if which go
  set --export GOPATH ~/code/go
  set PATH ~/code/go/bin $PATH
end

Add ImageMagick and personal scripts to PATH

# A workaround for Fish re-reading config for non-interactive execution:
# https://git.io/yj4KoA
if not status --is-interactive
  exit
end

# fundle
fundle plugin 'edc/bass'
fundle plugin 'brgmnn/fish-docker-compose'
fundle init

# rbenv
if which rbenv > /dev/null
  source (rbenv init -|psub)
end

# pyenv
if which pyenv > /dev/null
  source (pyenv init -|psub)
end

# Default editor
set --export EDITOR "code --wait"

# Go
if which go
  set --export GOPATH ~/code/go
  set PATH $PATH ~/code/go/bin
end

# ImageMagick
if test -d /usr/local/opt/imagemagick@6
  set PATH $PATH "/usr/local/opt/imagemagick@6/bin"
end

# Personal bin scripts
if test -d $HOME/bin
  set PATH $PATH $HOME/bin
end


function __fish_kdb_no_subcommand -d 'Check if the current commandline buffer does not contain a subcommand'
    set subcommands (__fish_kdb_print_subcommands)
    for input in (commandline -opc)
        if contains -- $input $subcommands
            return 1
        end
    end
    return 0
end

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

complete -c kdb -n '__fish_kdb_no_subcommand' -x -a '(__fish_kdb_print_subcommands -v)'

Use comments to structure file

# -- Functions -----------------------------------------------------------------------------------------------------------------------------

function __fish_kdb_no_subcommand -d 'Check if the current commandline buffer does not contain a subcommand'
    set subcommands (__fish_kdb_print_subcommands)
    for input in (commandline -opc)
        if contains -- $input $subcommands
            return 1
        end
    end
    return 0
end

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

# -- Completions ---------------------------------------------------------------------------------------------------------------------------

complete -c kdb -n '__fish_kdb_no_subcommand' -x -a '(__fish_kdb_print_subcommands -v)'


set -x PATH (brew --prefix coreutils)/libexec/gnubin $PATH

### RBENV
set -x RBENV_ROOT (brew --prefix rbenv)
set -x PATH $RBENV_ROOT/bin $PATH
set -x PATH $RBENV_ROOT/shims $PATH

set -x GEM_HOME (brew --prefix)/opt/gems
set -x GEM_PATH (brew --prefix)/opt/gems

### NVM
source ~/.config/fish/nvm-wrapper/nvm.fish

Replace brew --prefix with values; time ~200ms->20ms

## Note: Replaced calls to brew --prefix with actual values since
## it is slow (~ 200 ms)
set -x PATH /usr/local/opt/libexec/gnubin $PATH

### RBENV
set -x RBENV_ROOT /usr/local/opt/rbenv
set -x PATH $RBENV_ROOT/bin $PATH
set -x PATH $RBENV_ROOT/shims $PATH

set -x GEM_HOME /usr/local/opt/gems
set -x GEM_PATH /usr/local/opt/gems

### NVM
#source ~/.config/fish/nvm-wrapper/nvm.fish


#!/usr/bin/env fish

# PATH

if test -d /usr/local/sbin
  set PATH /usr/local/sbin $PATH
end

if test -x /usr/local/bin/cargo
  set PATH ~/.cargo/bin $PATH
end

if test -x /usr/local/bin/yarn
  set PATH ~/.yarn/bin ~/.config/yarn/global/node_modules/.bin $PATH
end

if test -z "$NVIM_LISTEN_ADDRESS"
  set EDITOR nvim --noplugin
  set VISUAL nvim --noplugin
end

if test -n "$NVIM_LISTEN_ADDRESS"
  if test -x /usr/local/bin/page
    set PAGER /usr/local/bin/page
  end
end

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

Set MANPAGER as neovim inside a neovim instance

#!/usr/bin/env fish

# PATH

if test -d /usr/local/sbin
  set PATH /usr/local/sbin $PATH
end

if test -x /usr/local/bin/cargo
  set PATH ~/.cargo/bin $PATH
end

if test -x /usr/local/bin/yarn
  set PATH ~/.yarn/bin ~/.config/yarn/global/node_modules/.bin $PATH
end

# Neovim settings

if test -z "$NVIM_LISTEN_ADDRESS"
  set EDITOR nvim --noplugin
  set VISUAL nvim --noplugin
end

if test -n "$NVIM_LISTEN_ADDRESS"
  set MANPAGER "/usr/local/bin/nvr -c 'set ft=man' -o -"
  if test -x /usr/local/bin/page
    set PAGER /usr/local/bin/page
  end
end

# Fisher plugins

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


#!/usr/bin/fish

set UNIFI_API_KEY get-from-unifi-video-user-account-page
set UNIFI_SERVER_ADDR https://<hostname or IP>:<port>

# shared storage between two containers on my server, it's OK
set SAMBA_USER username
set SAMBA_PASS password
set SAMBA_ADDR //192.168.0.4/Users
set SAMBA_DIR path/to/share

set json_file $argv
set camera_name (cat $json_file | jq --raw-output .'meta | .cameraName')
set start_time (date --date=@(math (cat $json_file | jq '.startTime'/1000)) +%Y%m%d_%Hh%Mm%Ss)
set end_time (date --date=@(math (cat $json_file | jq '.endTime'/1000)) +%Y%m%d_%Hh%Mm%Ss)
set record_id (string match --regex '.*/(.*).json' $json_file)[2]
set output_file (string join "_" $start_time "to" $end_time $camera_name ".mp4")

#curl --remote-name --remote-header-name --insecure (string join "" $UNIFI_SERVER_ADDR "/api/2.0/recording/" $record_id "/download?apiKey=" $UNIFI_API_KEY)
curl --output $output_file --insecure (string join "" $UNIFI_SERVER_ADDR "/api/2.0/recording/" $record_id "/download?apiKey=" $UNIFI_API_KEY)
smbclient --user=$SAMBA_USER%$SAMBA_PASS $SAMBA_ADDR --directory $SAMBA_DIR --command "put $output_file"

Make script more generic, & move files instead of copy.

#!/usr/bin/fish

set UNIFI_API_KEY get-from-unifi-video-user-account-page
set UNIFI_SERVER_ADDR https://<hostname or IP>:<port>
set BACKUP_DIR /path/to/backups

set json_file $argv
set camera_name (cat $json_file | jq --raw-output .'meta | .cameraName')
set start_time (date --date=@(math (cat $json_file | jq '.startTime'/1000)) +%Y%m%d_%Hh%Mm%Ss)
set end_time (date --date=@(math (cat $json_file | jq '.endTime'/1000)) +%Y%m%d_%Hh%Mm%Ss)
set record_id (string match --regex '.*/(.*).json' $json_file)[2]
set output_file (string join "_" $start_time "to" $end_time $camera_name ".mp4")

curl --output /tmp/$output_file --insecure (string join "" $UNIFI_SERVER_ADDR "/api/2.0/recording/" $record_id "/download?apiKey=" $UNIFI_API_KEY)
mv /tmp/$output_file $BACKUP_DIR/


Add function to apply a policy to a user or group

function apply-policy --argument-names type target policy
  print-status iam/apply-policy "$type $target $policy"
  aws iam put-$type-policy --$type-name $target --policy-name $policy --policy-document file://iam/$type-policy/$target/$policy.json
end


function store-secret --argument key
    trace (status --current-filename) $argv

    set value (rest $argv)

    if empty "$key" "$value"
        usage store-secret '<key>' '<value>'
        return 23
    end

    set trusted (get config/trusted)

    if empty trusted
        print --failure "No trusted recipients defined in config/trusted"
        return 2
    end

    echo $value | gpg --encrypt --armor --no-comments --recipient $trusted | tee $key
end


# Shortcuts
alias reload! "source ~/.config/fish/config.fish"
alias ... "cd ../.."
alias dl "cd ~/Downloads"
alias dt "cd ~/Desktop"
alias c "cd ~/code"
alias storm="open -a /Applications/WebStorm.app"
alias pubkey="more ~/.ssh/id_rsa.pub | pbcopy | echo '=> Public key copied to pasteboard.'"

Use projects in EAP WebStorm versions using `storm`

# Shortcuts
alias reload! "source ~/.config/fish/config.fish"
alias ... "cd ../.."
alias dl "cd ~/Downloads"
alias dt "cd ~/Desktop"
alias c "cd ~/code"
alias storm="open -a (mdfind -name 'kMDItemFSName==\"*.app\"' -onlyin /Applications/ | grep 'WebStorm.')"
alias pubkey="more ~/.ssh/id_rsa.pub | pbcopy | echo '=> Public key copied to pasteboard.'"


function bass
  set -l bash_args $argv
  set -l bass_debug
  if test "$bash_args[1]_" = '-d_'
    set bass_debug true
    set -e bash_args[1]
  end

  set -l script_file (mktemp)
  if command -v python3 >/dev/null 2>&1
    command python3 (dirname (status -f))/__bass.py $bash_args 3>$script_file
  else
    command python (dirname (status -f))/__bass.py $bash_args 3>$script_file
  end
  set -l bass_status $status
  if test $bass_status -ne 0
    return $bass_status
  end

  if test -n "$bass_debug"
    cat $script_file
  end
  source $script_file
  command rm $script_file
end

function __bass_usage
  echo "Usage: bass [-d] <bash-command>"
end

Improve startup speed by running Python with `-sS`

function bass
  set -l bash_args $argv
  set -l bass_debug
  if test "$bash_args[1]_" = '-d_'
    set bass_debug true
    set -e bash_args[1]
  end

  set -l script_file (mktemp)
  if command -v python3 >/dev/null 2>&1
    command python3 -sS (dirname (status -f))/__bass.py $bash_args 3>$script_file
  else
    command python -sS (dirname (status -f))/__bass.py $bash_args 3>$script_file
  end
  set -l bass_status $status
  if test $bass_status -ne 0
    return $bass_status
  end

  if test -n "$bass_debug"
    cat $script_file
  end
  source $script_file
  command rm $script_file
end

function __bass_usage
  echo "Usage: bass [-d] <bash-command>"
end


function psg -d "Details on a given process with table headers retained (ps aux | grep $argv); use [a]rgv to avoid showing grep command"
  ps axu | grep '[C]OMMAND\|'$argv                # show detailed table of processes matching description; [] avoids catching COMMAND in self, you'd still have to enclose relevant $argv part in [] to avoid catching self by your argument. Grep would trip over [] in self
	# -a: all users, no group leaders (1st member of a group of related processes), no processes without controlling terminal
	# -x: adds processes without controlling terminal, such as daemons (launched during boot and run in the background)
	# -u: detailed information about each process
end

Complete process list function to exclude itself in results

function psg -d "Details on a given process with table headers retained (ps aux | grep $argv); use [a]rgv to avoid showing grep command or add grep -v grep"
  if test -z $argv    # no arguments
		ps axu | grep -v grep | grep '[C]OMMAND\|'
	else if test (string length "$argv") -eq 1       # argument of 1 character length
		ps axu | grep -v grep | grep '[C]OMMAND\|'"$argv"
	else
		set -l argv1st (string sub -l1 $argv); set -l argvrest (string sub -s2 $argv)	#separate first char
		ps axu | grep '[C]OMMAND\|'"[$argv1st]$argvrest"
	end
  # show detailed table of processes matching description; [] avoids catching COMMAND in self, you'd still have to enclose relevant $argv part in [] to avoid catching self by your argument. Grep would trip over [] in self
	# -a: all users, no group leaders (1st member of a group of related processes), no processes without controlling terminal
	# -x: adds processes without controlling terminal, such as daemons (launched during boot and run in the background)
	# -u: detailed information about each process
end


function git_status
    if git rev-parse --is-inside-work-tree 1> /dev/null 2>& 1
        if not git diff --quiet
            set_color red
            echo -n "✘ "
            set_color normal
        end
        if not git diff --quiet --cached
            set_color yellow
            echo -n "✷ "
            set_color normal
        end
        set_color blue
        echo -n ""(git name-rev --name-only --no-undefined --always HEAD) ""
        set_color normal
    end
end

function fish_prompt
    set_color yellow
    echo -n "$PWD "
    set_color normal
    git_status
    echo -n "\$ "
end

Make fish prompt more compact, show unstaged files

function git_status
    if git rev-parse --is-inside-work-tree 1> /dev/null 2>& 1
        if not git diff --quiet
            set_color red
            echo -n "✘"
            set_color normal
        end
        if not git diff --quiet --cached
            set_color yellow
            echo -n "✔"
            set_color normal
        end
        begin
          set -l IFS ""
          if test -n ""(git ls-files --others --exclude-standard)""
            set_color green
            echo -n "☆"
          end
        end
        set_color blue
        echo -n ""(git name-rev --name-only --no-undefined --always HEAD)""
        set_color normal
    end
end

function fish_prompt
    set_color yellow
    echo -n "$PWD"
    set_color normal
    git_status
    echo -n "\$"
end


function fish_prompt
    set -l yellow (set_color yellow)
    set -l blue (set_color blue)
    set -l normal (set_color normal)

    set branch (git branch 2>/dev/null | grep \* | sed 's/\*//g' | sed 's/ //g')

    if set -q branch
        echo $yellow(prompt_pwd) [$blue$branch$yellow] ">> "
    else
        echo $yellow (prompt_pwd) ">> "
    end
end

Add UnicodeBox Format To Fish Prompt

function fish_prompt
    set -l yellow (set_color yellow)
    set -l blue (set_color blue)
    set -l normal (set_color normal)

    set branch (git branch 2>/dev/null | grep \* | sed 's/\*//g' | sed 's/ //g')

    echo "$blue┏╸$yellow"(prompt_pwd)

    if test -n "$branch";
        echo "$blue┣╸$yellow<$blue$branch$yellow>"
    end

    echo "$blue┗╸"
end


# rbenv
set PATH $HOME/.rbenv/bin $PATH
set PATH $HOME/.rbenv/shims $PATH
status --is-interactive; and source (rbenv init -|psub)

# base16 shell
if status --is-interactive
  eval sh $HOME/code/dotfiles/base16-builder-ruby/templates/shell/scripts/base16-onedark.sh
end

Remove old rbenv loading setup

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

# base16 shell
if status --is-interactive
  eval sh $HOME/code/dotfiles/base16-builder-ruby/templates/shell/scripts/base16-onedark.sh
end


# Initializes sharship prompt
if command -v starship > /dev/null
    starship init fish | source
end

# Initializes asdf
if test -f ~/.asdf/asdf.fish > /dev/null
    source ~/.asdf/asdf.fish
end

# Abbreviations
abbr --add be bundle exec
abbr --add dc docker-compose
abbr --add g git
abbr --add gd git diff
abbr --add gds git diff --staged

# Open file in a running emacs session
alias em="emacsclient --no-wait"

set -xg EDITOR "emacsclient --nowait"

# FZF
if command -v fzf > /dev/null
    set -xg FZF_DEFAULT_OPTS '--height 40% --border'
    if command -v fd > /dev/null
        set -xg FZF_DEFAULT_COMMAND  'fd --type=file --hidden --no-ignore-vcs'
    end

    function gcf
        git checkout (git branch --all | sed "s/.* //" | fzf)
    end
end

# bat as a cat replacement
if command -v bat > /dev/null
    alias cat="bat"

    function batf
        tail -f $argv | bat --paging=never -l log
    end
end

# `tm` alias to attach to running tmux session or create a new one
if command -v tmux > /dev/null
    function tm -d "Attach to running tmux session or create a new one"
        tmux attach || tmux new
    end
end

Add aliases for mkdir -p, .., ..., ...., /

# Initializes sharship prompt
if command -v starship > /dev/null
    starship init fish | source
end

# Initializes asdf
if test -f ~/.asdf/asdf.fish > /dev/null
    source ~/.asdf/asdf.fish
end

# Abbreviations
abbr --add ... cd ../..
abbr --add .... cd ../../..
abbr --add ..... cd ../../../..
abbr --add / cd /
abbr --add be bundle exec
abbr --add dc docker-compose
abbr --add g git
abbr --add gd git diff
abbr --add gds git diff --staged
abbr --add mp mkdir --parents

# Open file in a running emacs session
alias em="emacsclient --no-wait"
set -xg EDITOR "emacsclient --nowait"

# FZF
if command -v fzf > /dev/null
    set -xg FZF_DEFAULT_OPTS '--height 40% --border'
    if command -v fd > /dev/null
        set -xg FZF_DEFAULT_COMMAND  'fd --type=file --hidden --no-ignore-vcs'
    end

    function gcf
        git checkout (git branch --all | sed "s/.* //" | fzf)
    end
end

# bat as a cat replacement
if command -v bat > /dev/null
    alias cat="bat"

    function batf
        tail -f $argv | bat --paging=never -l log
    end
end

# `tm` alias to attach to running tmux session or create a new one
if command -v tmux > /dev/null
    function tm -d "Attach to running tmux session or create a new one"
        tmux attach || tmux new
    end
end


Add function to revoke a user's access key

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

    aws iam delete-access-key --user-name "$user" --access-key-id "$key"
end


function take --description 'Creates a directory and takes you inside'
	mkdir -p $argv[1]
	cd $argv[1]
end

Use 4 spaces for padding


function ll
    ls -al
end

function gll
    git log --graph --date=short --pretty=format:'%Cgreen%h %Cblue%cd (%cr) %Cred%an%C(yellow)%d%Creset: %s'
end

function glll
    git log --graph --stat --date=short --pretty=format:'%Cgreen%h %Cblue%cd (%cr) %Cred%an%C(yellow)%d%Creset: %s'
end

function goops
    git add -A
    git reset --hard HEAD
end

Add conversion shortcuts for Reason

function ll
    ls -al
end

function gll
    git log --graph --date=short --pretty=format:'%Cgreen%h %Cblue%cd (%cr) %Cred%an%C(yellow)%d%Creset: %s'
end

function glll
    git log --graph --stat --date=short --pretty=format:'%Cgreen%h %Cblue%cd (%cr) %Cred%an%C(yellow)%d%Creset: %s'
end

function goops
    git add -A
    git reset --hard HEAD
end

# Converts ML code into Reason
alias mlre "pbpaste | refmt -use-stdin true -parse ml -print re -is-interface-pp false | pbcopy"

# Converts Reason code into ML
alias reml "pbpaste | refmt -use-stdin true -parse re -print ml -is-interface-pp false | pbcopy"


# development environment
set -gx EDITOR (type -p nvim)
set -gx VIRTUAL_ENV_DISABLE_PROMPT 1

# GPG stuff
set -gx GPG_TTY (tty)

# pager stuff
set -gx PAGER bat

# PATH stuff
set PATH $PATH \
  $DOTFILES/bin \
  ~/.nodejs/{node,yarn}/bin \
  ./node_modules/.bin

# macOS specific vars
if test (uname) = 'Darwin'
  set PATH $PATH ~/Library/Python/*/bin
end

Fix issue with bat set as PAGER variable

# development environment
set -gx EDITOR (type -p nvim)
set -gx VIRTUAL_ENV_DISABLE_PROMPT 1

# GPG stuff
set -gx GPG_TTY (tty)

# pager stuff
set -gx PAGER less

# PATH stuff
set PATH $PATH \
  $DOTFILES/bin \
  ~/.nodejs/{node,yarn}/bin \
  ./node_modules/.bin

# macOS specific vars
if test (uname) = 'Darwin'
  set PATH $PATH ~/Library/Python/*/bin
end


if [ -d ~/.rbenv ]
    set --export PATH ~/.rbenv/shims $PATH
    rbenv rehash > /dev/null ^&1

    function rbenv_shell
      set --local vers $argv[1]

      switch "$vers"
        case '--complete'
          echo '--unset'
          echo 'system'
          exec rbenv-versions --bare
          return
        case '--unset'
          set --erase RBENV_VERSION
        case ''
          if [ -z "$RBENV_VERSION" ]
            echo "rbenv: no shell-specific version configured" >&2
            return 1
          else
            echo "$RBENV_VERSION"
          end
        case '*'
          rbenv prefix "$vers" > /dev/null
          set --global --export RBENV_VERSION "$vers"
      end
    end

    function rbenv
      set -l command $argv[1]
      [ (count $argv) -gt 1 ]; and set -l args $argv[2..-1]

      switch "$command"
        case shell
          rbenv_shell $args
        case '*'
          command rbenv $command $args
      end
    end
end

set --local bundled_commands foreman guard haml html2haml pry rackup rails rake rspec

for command in $bundled_commands
    alias $command="run_with_bundler $command"
end

Remove broken bundle exec shim


Add a function to get the fish version as a number


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'
set -x EMACS_TRUE_COLOR_SEPARATOR ';'

# 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.2/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

# psci
set psci_env $HOME/Works/env/psci
function psci
  set prev (pwd)
  cd $psci_env
  pulp psci
  cd $prev
end

Use psc-package for psci instead of pulp

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'
set -x EMACS_TRUE_COLOR_SEPARATOR ';'

# 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.2/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

# psci
set psci_env $HOME/Works/env/psci
function psci
  set prev (pwd)
  cd $psci_env
  psc-package repl
  cd $prev
end


#!/usr/bin/env fish

# for i in (expr (count $argv) - 1)
# 	echo $argv[$i]
# end

if [ $argv = 'add' ]
	# vim pairs.yaml
	echo Nickname:
	read nickname
	echo Name:
	read name
	echo Email:
	read email

	echo "- nickname: $nickname" >> pairs.yaml
	echo "  name: $name" >> pairs.yaml
	echo "  email: $email" >> pairs.yaml

	exit 0
end

grep "nickname: $argv[1]" pairs.yaml > /dev/null; or exit 1
grep "nickname: $argv[2]" pairs.yaml > /dev/null; or exit 1

set first (cat pairs.yaml | grep -A2 "nickname: $argv[1]" | cut -d':' -f2 | sed s/^\ //)
set second (cat pairs.yaml | grep -A2 "nickname: $argv[2]" | cut -d':' -f2 | sed s/^\ //)

git config user.name (echo $first[2] and $second[2])
git config user.email (echo (echo $first[3] | cut -d'@' -f1)+$second[3])

set_color -u bryellow; echo gitconfig updated; set_color normal
echo Name: (git config --get user.name)
echo Email: (git config --get user.email)

Add top level command for setting pairs

#!/usr/bin/env fish
set pairs_config_path ./.git-pairables.yaml

if [ $argv[1] = 'add' ]
	echo Nickname:
	read nickname
	echo Name:
	read name
	echo Email:
	read email

	echo "- nickname: $nickname" >> $pairs_config_path
	echo "  name: $name" >> $pairs_config_path
	echo "  email: $email" >> $pairs_config_path

	exit 0
end

if [ $argv[1] = 'set' ]
	grep "nickname: $argv[2]" $pairs_config_path > /dev/null; or exit 1
	grep "nickname: $argv[3]" $pairs_config_path > /dev/null; or exit 1

	set first (cat $pairs_config_path | grep -A2 "nickname: $argv[2]" | cut -d':' -f2 | sed s/^\ //)
	set second (cat $pairs_config_path | grep -A2 "nickname: $argv[3]" | cut -d':' -f2 | sed s/^\ //)

	git config user.name (echo $first[2] and $second[2])
	git config user.email (echo (echo $first[3] | cut -d'@' -f1)+$second[3])

	set_color -u bryellow; echo gitconfig updated; set_color normal
	echo Name: (git config --get user.name)
	echo Email: (git config --get user.email)
end


Add function to generate password based on requirements

function generate-password
    set --local length (aws iam get-account-password-policy | jq --raw-output .PasswordPolicy.MinimumPasswordLength)
    set --local requirements (password-requirements)

    set --local password
    while test -z "$password"
        set password (env LC_CTYPE=C tr -c -d (echo $requirements | tr -d \n) < /dev/urandom | fold -w $length | head -n 1)
        for requirement in $requirements
            if not echo $password | grep -q [$requirement]
                if set --query DEBUG
                    echo "Candidate $password does not contain $requirement" >& 2
                end

                set password ''

                break
            end
        end
    end
    echo "$password"
end


# Skip if $cgitc_initialized is set
if not set -q cgitc_initialized
  printf 'Initializing \e[33mcgitc\e[0m ... '
  for line in (cat (dirname (status -f))/abbreviations)
    # 1.  Strip out comments
    # 2.  Squeeze repeating spaces
    # 3.  Strip trailing whitespaces
    set line (echo "$line" | cut -d '#' -f 1 | tr -s ' ' | sed 's/[[:space:]]*$//')

    # Skip empty lines
    if not [ "$line" ]; continue; end

    # Parse lines
    set key   (echo "$line" | cut -d ' ' -f 1)
    set value (echo "$line" | cut -d ' ' -f 2-)

    abbr $key $value
  end

  set -U cgitc_initialized
  echo 'Done'
end

Enable updates for plugin managers

# Skip if cgitc_revision is up to date
set -l current_revision (git -C (dirname (status -f)) rev-parse HEAD)
if [ $cgitc_revision != $current_revision ]
  printf 'Initializing \e[33mcgitc\e[0m ... '
  for line in (cat (dirname (status -f))/abbreviations)
    # 1.  Strip out comments
    # 2.  Squeeze repeating spaces
    # 3.  Strip trailing whitespaces
    set line (echo "$line" | cut -d '#' -f 1 | tr -s ' ' | sed 's/[[:space:]]*$//')

    # Skip empty lines
    if not [ "$line" ]; continue; end

    # Parse lines
    set key   (echo "$line" | cut -d ' ' -f 1)
    set value (echo "$line" | cut -d ' ' -f 2-)

    abbr $key $value
  end

  set -U cgitc_revision $current_revision
  echo 'Done'
end


fortune sadserver_tweets | cowsay
set -gx EDITOR /usr/local/bin/vim
set -gx BUNDLER_EDITOR $EDITOR
set -gx TERM "screen-256color"

# Manpage settings {{{
set -gx MANPAGER "less -X"
# }}}

# Todo.sh settings {{{
set -gx TODOTXT_DEFAULT_ACTION ls
# }}}

set -gx COPYFILE_DISABLE true

# PATH {{{
append-to-path ~/bin
append-to-path ~/Library/Python/2.7/bin
prepend-to-path /usr/local/sbin
set -gx PG_CONFIG /Applications/Postgres.app/Contents/Versions/9.6/bin
append-to-path $PG_CONFIG
# }}}

set JDK jdk1.8.0_112.jdk
set -gx JAVA_HOME /Library/Java/JavaVirtualMachines/$JDK/Contents/Home

# Go {{{
set -gx GOPATH ~/go
append-to-path $GOPATH
append-to-path $GOPATH/bin
# }}}

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

Add homebrew item to path

fortune sadserver_tweets | cowsay
set -gx EDITOR /usr/local/bin/vim
set -gx BUNDLER_EDITOR $EDITOR
set -gx TERM "screen-256color"

# Manpage settings {{{
set -gx MANPAGER "less -X"
# }}}

# Todo.sh settings {{{
set -gx TODOTXT_DEFAULT_ACTION ls
# }}}

set -gx COPYFILE_DISABLE true

# PATH {{{
append-to-path ~/bin
append-to-path ~/Library/Python/2.7/bin
prepend-to-path /usr/local/sbin
set -gx PG_CONFIG /Applications/Postgres.app/Contents/Versions/9.6/bin
append-to-path $PG_CONFIG
prepend-to-path /usr/local/opt/libarchive/bin
# }}}

set JDK jdk1.8.0_112.jdk
set -gx JAVA_HOME /Library/Java/JavaVirtualMachines/$JDK/Contents/Home

# Go {{{
set -gx GOPATH ~/go
append-to-path $GOPATH
append-to-path $GOPATH/bin
# }}}

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


# Set path
set -x PATH /usr/local/share/npm/bin /usr/local/share/python /usr/local/bin /usr/local/sbin $HOME/bin $PATH

# Initialise rbenv
set PATH $HOME/.rbenv/bin $PATH
set PATH $HOME/.rbenv/shims $PATH
rbenv rehash >/dev/null ^&1

# Include aliases
. $HOME/dotfiles/aliases

# Set colors

set fish_color_command 89adff
set fish_color_cwd ffffa4
set fish_color_host 8cd6ff
set fish_color_user fdd8aa

set GREP_COLOR '' # use default grep color

Change pager and set less options

# Set path
set -x PATH /usr/local/share/npm/bin /usr/local/share/python /usr/local/bin /usr/local/sbin $HOME/bin $PATH

# Initialise rbenv
set PATH $HOME/.rbenv/bin $PATH
set PATH $HOME/.rbenv/shims $PATH
rbenv rehash >/dev/null ^&1

# Include aliases
. $HOME/dotfiles/aliases

# Set default pager and options for less
# (copied from zsh, makes it scroll faster for some reason)
set -x PAGER less
set -x LESS '-F -g -i -M -R -S -w -X -z-4'

# Set colors
set fish_color_command 89adff
set fish_color_cwd ffffa4
set fish_color_host 8cd6ff
set fish_color_user fdd8aa

set GREP_COLOR '' # use default grep color