#!/usr/bin/env fish
# -*-  mode:fish; tab-width:4  -*-

function FLSEG_SIGSTATUS

	if [ $FLINT_STATUS -gt 128 ]; and [ $FLINT_STATUS -lt 160 ]
		FLINT_CLOSE $FLCLR_STATUS_BG $FLCLR_STATUS_FG
		printf SIG(kill -l $FLINT_STATUS)
	else if [ $FLINT_STATUS -eq 126 ]
		FLINT_CLOSE $FLCLR_STATUS_BG $FLCLR_STATUS_FG
		printf "NOEXEC"
	else if [ $FLINT_STATUS -eq 127 ]
		FLINT_CLOSE $FLCLR_STATUS_BG $FLCLR_STATUS_FG
		printf "NFOUND"
	else if [ $FLINT_STATUS -gt 0 ]
		FLINT_CLOSE $FLCLR_STATUS_BG $FLCLR_STATUS_FG
		printf $FLINT_STATUS
	end

end

Update for OSX, show the SIGNAME in UPPERCASE as `kill -l $SIG` return SIGNAME in lowercase

#!/usr/bin/env fish
# -*-  mode:fish; tab-width:4  -*-

function FLSEG_SIGSTATUS

	if [ $FLINT_STATUS -gt 128 ]; and [ $FLINT_STATUS -lt 160 ]
		FLINT_CLOSE $FLCLR_STATUS_BG $FLCLR_STATUS_FG
		printf SIG(kill -l $FLINT_STATUS | tr '[a-z]' '[A-Z]')
	else if [ $FLINT_STATUS -eq 126 ]
		FLINT_CLOSE $FLCLR_STATUS_BG $FLCLR_STATUS_FG
		printf "NOEXEC"
	else if [ $FLINT_STATUS -eq 127 ]
		FLINT_CLOSE $FLCLR_STATUS_BG $FLCLR_STATUS_FG
		printf "NFOUND"
	else if [ $FLINT_STATUS -gt 0 ]
		FLINT_CLOSE $FLCLR_STATUS_BG $FLCLR_STATUS_FG
		printf $FLINT_STATUS
	end

end


# Neovim
set --local neovim_guis \
	/Applications/FVim.app/Contents/MacOS/FVim \
	/Applications/goneovim.app/Contents/MacOS/goneovim
set --export EDITOR $neovim_guis[(random 1 2)]

# Nix
set NIX_LINK $HOME/.nix-profile
set --export NIX_PATH nixpkgs=$HOME/.nix-defexpr/channels/nixpkgs
set --export SSL_CERT_FILE $NIX_LINK/etc/ssl/certs/ca-bundle.crt

# XDG
if [ -z $XDG_CONFIG_HOME ]
	set --export XDG_CONFIG_HOME $HOME/.config
	set --export XDG_DATA_HOME $HOME/.local/share
	set --export XDG_CACHE_HOME $HOME/.cache
end

# NPM
set --export NPM_CONFIG_USERCONFIG $XDG_CONFIG_HOME/npm/config

# Postgres
set --export PSQLRC $XDG_CONFIG_HOME/psqlrc

set PATH $NIX_LINK/bin $NIX_LINK/sbin $PATH
set PATH ~/.local/bin $PATH
set PATH ~/.luarocks/bin $PATH
set PATH node_modules/.bin $XDG_DATA_HOME/node_modules $PATH
set --export PATH $PATH

Use test instead of [

# Neovim
set --local neovim_guis \
	/Applications/FVim.app/Contents/MacOS/FVim \
	/Applications/goneovim.app/Contents/MacOS/goneovim
set --export EDITOR $neovim_guis[(random 1 2)]

# Nix
set NIX_LINK $HOME/.nix-profile
set --export NIX_PATH nixpkgs=$HOME/.nix-defexpr/channels/nixpkgs
set --export SSL_CERT_FILE $NIX_LINK/etc/ssl/certs/ca-bundle.crt

# XDG
if test -z $XDG_CONFIG_HOME
	set --export XDG_CONFIG_HOME $HOME/.config
	set --export XDG_DATA_HOME $HOME/.local/share
	set --export XDG_CACHE_HOME $HOME/.cache
end

# NPM
set --export NPM_CONFIG_USERCONFIG $XDG_CONFIG_HOME/npm/config

# Postgres
set --export PSQLRC $XDG_CONFIG_HOME/psqlrc

set PATH $NIX_LINK/bin $NIX_LINK/sbin $PATH
set PATH ~/.local/bin $PATH
set PATH ~/.luarocks/bin $PATH
set PATH node_modules/.bin $XDG_DATA_HOME/node_modules $PATH
set --export PATH $PATH


set fvim /Applications/FVim.app/Contents/MacOS/FVim
if [ -e $fvim ]
	set --export EDITOR $fvim
else
	set --export EDITOR nvim
end

# XDG
set --export XDG_CONFIG_HOME $HOME/.config
set --export XDG_DATA_HOME $HOME/.local/share

# Nix
set --export NIX_PATH nixpkgs=$HOME/.nix-defexpr/channels
set --export NIX_PROFILES /nix/var/nix/profiles/default $HOME/.nix-profile
set --export SSL_CERT_FILE $HOME/.nix-profile/etc/ssl/certs/ca-bundle.crt

# NPM
set --export NPM_CONFIG_USERCONFIG $XDG_CONFIG_HOME/npm/config

# Postgres
set --export PSQLRC $XDG_CONFIG_HOME/psqlrc

for profile in $NIX_PROFILES
	set PATH $profile/bin $PATH
end
set PATH $HOME/.local/bin $PATH
set PATH $HOME/.luarocks/bin $PATH
set PATH ./node_modules/.bin $XDG_DATA_HOME/node_modules/bin $PATH
set --export PATH $PATH

Add goneovim as available editor

# Neovim
set --local neovim_guis \
	/Applications/FVim.app/Contents/MacOS/FVim \
	/Applications/goneovim.app/Contents/MacOS/goneovim
set --export EDITOR $neovim_guis[(random 1 2)]

# XDG
set --export XDG_CONFIG_HOME $HOME/.config
set --export XDG_DATA_HOME $HOME/.local/share

# Nix
set --export NIX_PATH nixpkgs=$HOME/.nix-defexpr/channels
set --export NIX_PROFILES /nix/var/nix/profiles/default $HOME/.nix-profile
set --export SSL_CERT_FILE $HOME/.nix-profile/etc/ssl/certs/ca-bundle.crt

# NPM
set --export NPM_CONFIG_USERCONFIG $XDG_CONFIG_HOME/npm/config

# Postgres
set --export PSQLRC $XDG_CONFIG_HOME/psqlrc

for profile in $NIX_PROFILES
	set PATH $profile/bin $PATH
end
set PATH $HOME/.local/bin $PATH
set PATH $HOME/.luarocks/bin $PATH
set PATH ./node_modules/.bin $XDG_DATA_HOME/node_modules/bin $PATH
set --export PATH $PATH


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

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

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

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

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

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

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

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

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

Use -gx for fish variables

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

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

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

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

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

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

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

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

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


# 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 gf='git fetch'
alias gl='git pull'

Add sudo emacs -nw alias as sue

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

# 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

# emacs alias
alias e="emacs -nw"
alias sue='sudo emacs -nw'

# 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 gf='git fetch'
alias gl='git pull'


function gcv --description="git commit verbose"
  if test (count (command git status --porcelain | command grep "^[^ ?]")) -eq 0
    set_color yellow
    echo "Nothing to commit..."
    set_color normal
    return 1
  end

  set -l arguments

  set -l cmd "command git diff --cached --name-only"

  eval "$GISH_DIR/include/parse $argv"

  if test (count $ARGV) -gt 0
    set arguments (gish find -c $cmd $ARGV)

    if test -z $arguments
      set_color red
      echo "No matches found"
      set_color normal
      return 0
    end
  end

  command git commit --verbose $OPTV $ARGV
  gs
end


Add a function to prepend a string to the front of the current command

# Taken from
# https://github.com/fish-shell/fish-shell/issues/288#issuecomment-158704275

function prepend_command -d "Prepends string to the front of the current command"
  set -l prepend $argv[1]
  if test -z "$prepend"
    echo "prepend_command needs one argument."
    return 1
  end

  set -l cmd (commandline)
  if test -z "$cmd"
    commandline -r $history[1]
  end

  set -l old_cursor (commandline -C)
  commandline -C 0
  commandline -i "$prepend "
  commandline -C (math $old_cursor + (echo $prepend | wc -c))
end


# FIXME: This doesn't play nice with tmux/screen
# I looked into it, but no solution seems readily
# available. Going into a vt is a rare occurence
# and I do not need tmux there, but it would be
# nice to have.
function use_simple_glyph --description 'Checks if simple glyphs should be used'
	test $TERM = "linux"
end

Allow manual toggle of simple glyphs

# FIXME: This doesn't play nice with tmux/screen
# I looked into it, but no solution seems readily
# available. Going into a vt is a rare occurence
# and I do not need tmux there, but it would be
# nice to have.
function use_simple_glyph --description 'Checks if simple glyphs should be used'
  set -q config_use_simple_glyph
	  or test $TERM = "linux"
end


function d -d 'Trash'
  if type -q trash-put > /dev/null
    set_color $yellow
    printf 'Trashing file \"%s\"\n' $argv
    set_color normal
    trash-put $argv
  else if type -q trash > /dev/null
    trash -av $argv
  else
    log warn 'No trash program is available'
    rm -ri $argv
  end
end

Add `dddd` as the alias for `rm -rf`

function d -d 'Trash'
  if type -q trash-put > /dev/null
    set_color $yellow
    printf 'Trashing file \"%s\"\n' $argv
    set_color normal
    trash-put $argv
  else if type -q trash > /dev/null
    trash -av $argv
  else
    log warn 'No trash program is available'
    rm -ri $argv
  end
end

function dddd -d 'Remove directory without prompt'
  rm -rf $argv
end


function fish_prompt --description 'Write out the prompt'

	set -l last_status $status

	# Just calculate these once, to save a few cycles when displaying the prompt
	if not set -q __fish_prompt_hostname
		set -g __fish_prompt_hostname (hostname|cut -d . -f 1)
	end

	if not set -q __fish_prompt_normal
		set -g __fish_prompt_normal (set_color normal)
	end

	if not set -q -g __fish_classic_git_functions_defined
		set -g __fish_classic_git_functions_defined

		function __fish_repaint_user --on-variable fish_color_user --description "Event handler, repaint when fish_color_user changes"
			if status --is-interactive
				set -e __fish_prompt_user
				commandline -f repaint ^/dev/null
			end
		end

		function __fish_repaint_host --on-variable fish_color_host --description "Event handler, repaint when fish_color_host changes"
			if status --is-interactive
				set -e __fish_prompt_host
				commandline -f repaint ^/dev/null
			end
		end

		function __fish_repaint_status --on-variable fish_color_status --description "Event handler; repaint when fish_color_status changes"
			if status --is-interactive
				set -e __fish_prompt_status
				commandline -f repaint ^/dev/null
			end
		end
	end

	set -l delim '>'

	switch $USER

	case root

		if not set -q __fish_prompt_cwd
			if set -q fish_color_cwd_root
				set -g __fish_prompt_cwd (set_color $fish_color_cwd_root)
			else
				set -g __fish_prompt_cwd (set_color $fish_color_cwd)
			end
		end

	case '*'

		if not set -q __fish_prompt_cwd
			set -g __fish_prompt_cwd (set_color $fish_color_cwd)
		end

	end

	set -l prompt_status
	if test $last_status -ne 0
		if not set -q __fish_prompt_status
			set -g __fish_prompt_status (set_color $fish_color_status)
		end
		set prompt_status "$__fish_prompt_status [$last_status]$__fish_prompt_normal"
	end

	if not set -q __fish_prompt_user
		set -g __fish_prompt_user (set_color $fish_color_user)
	end
	if not set -q __fish_prompt_host
		set -g __fish_prompt_host (set_color $fish_color_host)
	end

	echo -n -s "$__fish_prompt_user" "$USER" "$__fish_prompt_normal" @ "$__fish_prompt_host" "$__fish_prompt_hostname" "$__fish_prompt_normal" ' ' "$__fish_prompt_cwd" (prompt_pwd) (__fish_git_prompt) "$__fish_prompt_normal" "$prompt_status" "$delim" ' '
end


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

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

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

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

# direnv
eval (direnv hook fish)

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

# Python
fish_add_path --path --move /home/$USER/.local/bin

# Rust
fish_add_path --path --move /home/$USER/.cargo/bin

# aliases
alias s="start"
alias j="jump"
alias l="ls -al"
alias electric-monk="list-projects | each gitkeeper"

Move the GOPRIVATE variable to the individual .envrc files

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

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

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

# Go
set -x GOPATH $HOME/.go
fish_add_path --path --move /home/$USER/.go/bin

# direnv
eval (direnv hook fish)

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

# Python
fish_add_path --path --move /home/$USER/.local/bin

# Rust
fish_add_path --path --move /home/$USER/.cargo/bin

# aliases
alias s="start"
alias j="jump"
alias l="ls -al"
alias electric-monk="list-projects | each gitkeeper"


function jump
  if test (count $argv) -ne 1
    echo "Usage: jump <MARK_NAME>"
  else
    if test -d $MARKPATH/$argv[1] -a -L $MARKPATH/$argv[1]
      cd $MARKPATH/$argv[1]
      cd (pwd -P)
    else
      echo "No such mark: $argv[1]"
    end
  end
end

Use readlink to determine the path

function jump
  if test (count $argv) -ne 1
    echo "Usage: jump <MARK_NAME>"
  else
    if test -d $MARKPATH/$argv[1] -a -L $MARKPATH/$argv[1]
      cd (readlink $MARKPATH/$argv[1])
    else
      echo "No such mark: $argv[1]"
    end
  end
end


## Aliases
alias vi="nvim"
alias vim="nvim"
alias git="hub"
alias diff="colordiff -u"
alias ctags="/usr/local/bin/ctags"
alias deckset="open -a Deckset"
alias rm="rm -i"
alias zatsu="memo edit zatsu.md"
alias ls="exa --icons"
alias la="ls -al" # workaround: exa does not support -A option
alias ghqg="$GOPATH/bin/get -shallow -unshallow ghq"
alias tig="env TERM=xterm-256color tig"

## Abbreviations
abbr -a b "bundle"
abbr -a v "vagrant"
abbr -a k "kubectl"
abbr -a kc "kubectl ctx"
abbr -a kn "kubectl ns"
abbr -a ks "kubesec"
abbr -a kp "kube-prompt"
abbr -a d "docker"
abbr -a dc "docker compose"
abbr -a tf "terraform"
abbr -a be "bundle exec"
abbr -a bb "brew bundle"
abbr -a gcoo "git-branch-fzf"
abbr -a docker-stop "docker ps -aq | xargs docker stop"
abbr -a docker-rm "docker ps -aq | xargs docker rm -f"
abbr -a docker-rmi "docker images -f dangling=true -q | xargs docker rmi -f"

Use normal diff command instead of colordiff

## Aliases
alias vi="nvim"
alias vim="nvim"
alias git="hub"
alias diff="diff -u"
alias ctags="/usr/local/bin/ctags"
alias deckset="open -a Deckset"
alias rm="rm -i"
alias zatsu="memo edit zatsu.md"
alias ls="exa --icons"
alias la="ls -al" # workaround: exa does not support -A option
alias ghqg="$GOPATH/bin/get -shallow -unshallow ghq"
alias tig="env TERM=xterm-256color tig"

## Abbreviations
abbr -a b "bundle"
abbr -a v "vagrant"
abbr -a k "kubectl"
abbr -a kc "kubectl ctx"
abbr -a kn "kubectl ns"
abbr -a ks "kubesec"
abbr -a kp "kube-prompt"
abbr -a d "docker"
abbr -a dc "docker compose"
abbr -a tf "terraform"
abbr -a be "bundle exec"
abbr -a bb "brew bundle"
abbr -a gcoo "git-branch-fzf"
abbr -a docker-stop "docker ps -aq | xargs docker stop"
abbr -a docker-rm "docker ps -aq | xargs docker rm -f"
abbr -a docker-rmi "docker images -f dangling=true -q | xargs docker rmi -f"


Add VIMODE segment to use insted of the default fish_mode_prompt

#!/usr/bin/env fish
# -*-  mode:fish; tab-width:4  -*-
set FLSYM_VIMODE_DEFAULT "NORMAL"
set FLSYM_VIMODE_INSERT  "INSERT"
set FLSYM_VIMODE_REPLACE "REPLACE"
set FLSYM_VIMODE_VISUAL  "VISUAL"

set FLCLR_VIMODE_DEFAULT_BG green
set FLCLR_VIMODE_DEFAULT_FG black
set FLCLR_VIMODE_INSERT_BG  white
set FLCLR_VIMODE_INSERT_FG  black
set FLCLR_VIMODE_REPLACE_BG red
set FLCLR_VIMODE_REPLACE_FG normal
set FLCLR_VIMODE_VISUAL_BG  orange
set FLCLR_VIMODE_VISUAL_FG  normal

functions -e fish_mode_prompt

function FLSEG_VIMODE

  if set -q __fish_vi_mode
    switch $fish_bind_mode
      case default
        FLINT_CLOSE $FLCLR_VIMODE_DEFAULT_BG $FLCLR_VIMODE_DEFAULT_FG
    		printf $FLSYM_VIMODE_DEFAULT
      case insert
        FLINT_CLOSE $FLCLR_VIMODE_INSERT_BG $FLCLR_VIMODE_INSERT_FG
        printf $FLSYM_VIMODE_INSERT
      case replace-one
        FLINT_CLOSE $FLCLR_VIMODE_REPLACE_BG $FLCLR_VIMODE_REPLACE_FG
        printf $FLSYM_VIMODE_REPLACE
      case visual
        FLINT_CLOSE $FLCLR_VIMODE_VISUAL_BG $FLCLR_VIMODE_VISUAL_FG
        printf $FLSYM_VIMODE_VISUAL
    end
  end

end


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

    aws iam update-login-profile --user-name $user --password $password --password-reset-required
end


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

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

test "navigates to cloned project when given user repo"
  "$HOME/github.com/gh_user/gh_repo" = (
    # Quoting required due to fish test bug: https://github.com/fish-shell/fish-shell/issues/2342
    mock git 0 "test \"\$args\" = 'clone -q git@github.com:gh_user/gh_repo.git $repo_path'
                and mkdir -p $repo_path"
    gh gh_user gh_repo
    pwd
  )
end

Test clone navigation for user/repo

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

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

test "navigates to cloned project when given user repo"
  "$HOME/github.com/gh_user/gh_repo" = (
    # Quoting required due to fish test bug: https://github.com/fish-shell/fish-shell/issues/2342
    mock git 0 "test \"\$args\" = 'clone -q git@github.com:gh_user/gh_repo.git $repo_path'
                and mkdir -p $repo_path"
    gh gh_user gh_repo
    pwd
  )
end

test "navigates to cloned project when given user/repo"
  "$HOME/github.com/gh_user/gh_repo" = (
    mock git 0 "test \"\$args\" = 'clone -q git@github.com:gh_user/gh_repo.git $repo_path'
                and mkdir -p $repo_path"
    gh gh_user/gh_repo
    pwd
  )
end


function weather.location -d "Get the current geographic location"
  # Attempt to get our external IP address.
  if not set ip (__weather_get_ip)
    echo "No Internet connection or IP service unavailable."
    return 1
  end

  # Fetch location data based on our IP
  if not set geoip_data (weather.fetch "https://ipapi.com/ip_api.php?ip=$ip")
    echo "Unable to query GeoIP data; please try again later."
    return 1
  end

  # Echo coordiantes.
  echo $geoip_data | jq '.latitude'
  echo $geoip_data | jq '.longitude'
  echo $geoip_data | jq -r '.city?'
  echo $geoip_data | jq -r '.country_name'
end

function __weather_get_ip -d "Get the current device's public IP address"
  # Attempt to get our external IP using the OpenDNS resolver.
  if type -q dig
    if set -q __weather_system_dns
      if not set ip (dig +short myip.opendns.com)
        return 1
      end
    else
      if not set ip (dig +short myip.opendns.com @resolver1.opendns.com)
        return 1
      end
    end
  end

  # Attempt to get our external IP using a web service.
  if test -z $ip
    if not set ip (weather.fetch "http://ipecho.net/plain")
      return 1
    end
  end

  echo $ip
end

Return early, as soon as the IP is retrieved

function weather.location -d "Get the current geographic location"
  # Attempt to get our external IP address.
  if not set ip (__weather_get_ip)
    echo "No Internet connection or IP service unavailable."
    return 1
  end

  # Fetch location data based on our IP
  if not set geoip_data (weather.fetch "https://ipapi.com/ip_api.php?ip=$ip")
    echo "Unable to query GeoIP data; please try again later."
    return 1
  end

  # Echo coordiantes.
  echo $geoip_data | jq '.latitude'
  echo $geoip_data | jq '.longitude'
  echo $geoip_data | jq -r '.city?'
  echo $geoip_data | jq -r '.country_name'
end

function __weather_get_ip -d "Get the current device's public IP address"
  # Attempt to get our external IP using the OpenDNS resolver.
  if type -q dig
    if set -q __weather_system_dns
      if set ip (dig +short myip.opendns.com 2>/dev/null)
        echo $ip
        return
      end
    else
      if set ip (dig +short myip.opendns.com @resolver1.opendns.com 2>/dev/null)
        echo $ip
        return
      end
    end
  end

  # Attempt to get our external IP using a web service.
  if set ip (weather.fetch "http://ipecho.net/plain")
    echo $ip
  end

end


set -gx NPM_DIR "$HOME/.npm-data"
set -gx NODE_PATH "$NPM_DIR/lib/node_modules:$NODE_PATH"
set -gx PATH ~/bin $NPM_DIR/bin $HOME/.local/bin $PATH

mkdir -p ~/bin $NPM_DIR/bin

set -gx fish_greeting ""

test -d ~/.linuxbrew && eval (~/.linuxbrew/bin/brew shellenv)
test -d /home/linuxbrew/.linuxbrew && eval (/home/linuxbrew/.linuxbrew/bin/brew shellenv)

if type -q nvim
  set -gx EDITOR nvim
  set -gx VISUAL nvim
  set -gx MANPAGER "nvim +Man! -c ':set signcolumn='"
  alias vimdiff="nvim -d"
end

set -gx FZF_DEFAULT_COMMAND "rg --files --hidden --follow -g \"!.git/\" 2> /dev/null"
set -gx FZF_CTRL_T_COMMAND $FZF_DEFAULT_COMMAND

# Other git aliases are in git config
alias g="git"
alias gg="g a .; and g c -a"
alias lg="lazygit"

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

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

Fix my man pages showing errors when opened in nvim

set -gx NPM_DIR "$HOME/.npm-data"
set -gx NODE_PATH "$NPM_DIR/lib/node_modules:$NODE_PATH"
set -gx PATH ~/bin $NPM_DIR/bin $HOME/.local/bin $PATH

mkdir -p ~/bin $NPM_DIR/bin

set -gx fish_greeting ""

test -d ~/.linuxbrew && eval (~/.linuxbrew/bin/brew shellenv)
test -d /home/linuxbrew/.linuxbrew && eval (/home/linuxbrew/.linuxbrew/bin/brew shellenv)

if type -q nvim
  set -gx EDITOR nvim
  set -gx VISUAL nvim
  set -gx MANPAGER "nvim +Man!"
  alias vimdiff="nvim -d"
end

set -gx FZF_DEFAULT_COMMAND "rg --files --hidden --follow -g \"!.git/\" 2> /dev/null"
set -gx FZF_CTRL_T_COMMAND $FZF_DEFAULT_COMMAND

# Other git aliases are in git config
alias g="git"
alias gg="g a .; and g c -a"
alias lg="lazygit"

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

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


# Go
function g -d 'Change directory and look up'
  set is_okay true
  if test -z $argv # if no argument
    cd -
  else
    if test -e $argv # if the file exists
      cd $argv
    else
      set is_okay false
      set_color $red
      echo 'Cannot find "'$argv'"'
      set_color normal
    end
  end

  if eval $is_okay
    ls -AF .
  end
end
alias gh 'g $HOME'
alias gconfig 'g $HOME/.config/fish/'
alias grepo 'g $HOME/repos/'
alias .. 'g ..'
alias ... 'g ../..'
alias .... 'g ../../..'
alias ..... 'g ../../../..'

# See

## Let ls (exa) to use the ISO date and time format. See https://www.gnu.org/software/coreutils/manual/html_node/Formatting-file-timestamps.html
set -gx TIME_STYLE long-iso

function s -d 'List files in details'
  if type -q exa;
    exa -lag $argv
  else;
    ls -AFlh $argv
  end
end
function st -d 'List files ordered from oldest to newest'
  s -tr
end
function sf -d 'List files with filter'
  s | grep $argv
end

Simplify the `g` (cd replacement) function

# Go
function g -d 'Change directory and look up'
  if test -z $argv # if no argument
    cd -
  else if not test -e $argv # If the file does not exist
    set_color $red
    echo ''
    cd $argv
    echo ''
    set_color normal
  else
    cd $argv
  end

  ls -AF .
end
alias gh 'g $HOME'
alias gconfig 'g $HOME/.config/fish/'
alias grepo 'g $HOME/repos/'
alias .. 'g ..'
alias ... 'g ../..'
alias .... 'g ../../..'
alias ..... 'g ../../../..'

# See

## Let ls (exa) to use the ISO date and time format. See https://www.gnu.org/software/coreutils/manual/html_node/Formatting-file-timestamps.html
set -gx TIME_STYLE long-iso

function s -d 'List files in details'
  if type -q exa;
    exa -lag $argv
  else;
    ls -AFlh $argv
  end
end
function st -d 'List files ordered from oldest to newest'
  s -tr
end
function sf -d 'List files with filter'
  s | grep $argv
end


function randombase64 -d "Generate random base64 string"
  set -l n $argv[1]; test -z $n; and set n 12
  # https://en.wikipedia.org/wiki/Birthday_problem#Probability_table
  dd if=/dev/urandom bs=1 count=$n ^/dev/null | base64 | cut -b -$n
end

Remove /, + from output

function randombase64 -d "Generate random base64 string"
  set -l n $argv[1]; test -z $n; and set n 16
  # https://en.wikipedia.org/wiki/Birthday_problem#Probability_table
  dd if=/dev/urandom bs=1 count=$n ^/dev/null | base64 | tr -d "[/+]" | cut -b -$n
end


if test "$FZF_LEGACY_KEYBINDINGS" -eq 1
    bind \ct '__fzf_find_file'
    bind \cr '__fzf_reverse_isearch'
    bind \ec '__fzf_cd'
    bind \eC '__fzf_cd_with_hidden'

    if bind -M insert >/dev/null 2>/dev/null
        bind -M insert \ct '__fzf_find_file'
        bind -M insert \cr '__fzf_reverse_isearch'
        bind -M insert \ec '__fzf_cd'
        bind -M insert \eC '__fzf_cd --hidden'
    end
else
    bind \cf '__fzf_find_file'
    bind \cr '__fzf_reverse_isearch'
    bind \eo '__fzf_cd'
    bind \eO '__fzf_cd --hidden'

    if bind -M insert >/dev/null 2>/dev/null
        bind -M insert \cf '__fzf_find_file'
        bind -M insert \cr '__fzf_reverse_isearch'
        bind -M insert \eo '__fzf_cd'
        bind -M insert \eO '__fzf_cd --hidden'
    end
end

set -q FZF_COMPLETE ;and bind \t '__fzf_complete'

Make FZF_COMPLETE use a proper if statement

if test "$FZF_LEGACY_KEYBINDINGS" -eq 1
    bind \ct '__fzf_find_file'
    bind \cr '__fzf_reverse_isearch'
    bind \ec '__fzf_cd'
    bind \eC '__fzf_cd_with_hidden'

    if bind -M insert >/dev/null 2>/dev/null
        bind -M insert \ct '__fzf_find_file'
        bind -M insert \cr '__fzf_reverse_isearch'
        bind -M insert \ec '__fzf_cd'
        bind -M insert \eC '__fzf_cd --hidden'
    end
else
    bind \cf '__fzf_find_file'
    bind \cr '__fzf_reverse_isearch'
    bind \eo '__fzf_cd'
    bind \eO '__fzf_cd --hidden'

    if bind -M insert >/dev/null 2>/dev/null
        bind -M insert \cf '__fzf_find_file'
        bind -M insert \cr '__fzf_reverse_isearch'
        bind -M insert \eo '__fzf_cd'
        bind -M insert \eO '__fzf_cd --hidden'
    end
end

if set -q FZF_COMPLETE
    bind \t '__fzf_complete'
end


function fish_right_prompt
    set -l status_color yellow
    set -l status_char "😄 "

    if test $status -ne 0
        set status_color red
        set status_char "😡 "
    end

    if test "$CMD_DURATION" -gt 50
        set -l duration (printf $CMD_DURATION | humanize_duration)
        print_color $status_color "$status_char $duration"
    else
        print_color brblack (date "+%a %H:%M")
    end
end

Increase minimum command duration to 200ms

function fish_right_prompt
    set -l status_color yellow
    set -l status_char "😄 "

    if test $status -ne 0
        set status_color red
        set status_char "😡 "
    end

    if test "$CMD_DURATION" -gt 200
        set -l duration (printf $CMD_DURATION | humanize_duration)
        print_color $status_color "$status_char $duration"
    else
        print_color brblack (date "+%a %H:%M")
    end
end


function fish_right_prompt --description 'Write out the prompt'
	set -l last_status $status

  if not set -q __fish_git_prompt_show_informative_status
      set -g __fish_git_prompt_show_informative_status 1
  end
  if not set -q __fish_git_prompt_hide_untrackedfiles
      set -g __fish_git_prompt_hide_untrackedfiles 1
  end

  if not set -q __fish_git_prompt_color_branch
      set -g __fish_git_prompt_color_branch magenta --bold
  end
  if not set -q __fish_git_prompt_showupstream
      set -g __fish_git_prompt_showupstream "informative"
  end
  if not set -q __fish_git_prompt_char_upstream_ahead
      set -g __fish_git_prompt_char_upstream_ahead "↑"
  end
  if not set -q __fish_git_prompt_char_upstream_behind
      set -g __fish_git_prompt_char_upstream_behind "↓"
  end
  if not set -q __fish_git_prompt_char_upstream_prefix
      set -g __fish_git_prompt_char_upstream_prefix ""
  end

  if not set -q __fish_git_prompt_char_stagedstate
      set -g __fish_git_prompt_char_stagedstate "●"
  end
  if not set -q __fish_git_prompt_char_dirtystate
      set -g __fish_git_prompt_char_dirtystate "✚"
  end
  if not set -q __fish_git_prompt_char_untrackedfiles
      set -g __fish_git_prompt_char_untrackedfiles "…"
  end
  if not set -q __fish_git_prompt_char_conflictedstate
      set -g __fish_git_prompt_char_conflictedstate "✖"
  end
  if not set -q __fish_git_prompt_char_cleanstate
      set -g __fish_git_prompt_char_cleanstate "✔"
  end

  if not set -q __fish_git_prompt_color_dirtystate
      set -g __fish_git_prompt_color_dirtystate blue
  end
  if not set -q __fish_git_prompt_color_stagedstate
      set -g __fish_git_prompt_color_stagedstate yellow
  end
  if not set -q __fish_git_prompt_color_invalidstate
      set -g __fish_git_prompt_color_invalidstate red
  end
  if not set -q __fish_git_prompt_color_untrackedfiles
      set -g __fish_git_prompt_color_untrackedfiles $fish_color_normal
  end
  if not set -q __fish_git_prompt_color_cleanstate
      set -g __fish_git_prompt_color_cleanstate green --bold
  end

  if not set -q __fish_prompt_normal
      set -g __fish_prompt_normal (set_color normal)
  end

  # Main

  printf '%s ' (__fish_vcs_prompt)

  set_color normal
end


function bucket-exists --argument-names name
  print-status s3/bucket-exists $name
  aws s3api list-buckets | jq -e ".Buckets[] | select(.Name == \"$name\")" >/dev/null ^/dev/null
end


Add function to detach a policy from a thing

function detach-policy --argument type name policy
    if empty "$type" "$name" "$policy"
        usage detach-policy '<type>' '<name>' '<policy>'
        return (false)
    end

    print-status detach-policy "$argv"

    aws iam detach-$type-policy --$type-name "$name" --policy-arn (lookup-policy "$policy")
end


function swift_releases \
        --description='Check for Swift releases' \
        --argument-names swift_version days

    set -l branch_name development

    if test -n "$swift_version"
        set swift_version "-$swift_version"
        set branch_name "swift$swift_version-branch"
    end

    if test -z "$days"
        set days 7
    end

    echo "Checking for Swift $branch_name snapshot releases ($days days)"
    echo

    set -l year (date "+%Y")
    set -l month (date "+%m")
    set -l current_day (date "+%d")

    # jot generates a decending sequence of integers
    for day in (jot $days $current_day 1 -1)
        # Zero pad month and day
        set month (printf "%02d" $month)
        set day (printf "%02d" $day)

        set -l date $year-$month-$day
        echo -n $date

        set -l release_slug "swift$swift_version-DEVELOPMENT-SNAPSHOT-$date-a"
        set -l url "https://swift.org/builds/$branch_name/xcode/$release_slug/$release_slug-osx.pkg"
        #echo $url

        set -l status_code (
            curl \
                --head \
                --location \
                --silent \
                --output /dev/null \
                --write-out "%{http_code}" \
                $url
       )

       echo " - $status_code"
       if test $status_code = 200
           echo $url
       end
    end
end

Add special 'trunk' version value so that days can be specified

function swift_releases \
        --description='Check for Swift releases' \
        --argument-names swift_version days

    set -l branch_name development

    if test $swift_version = "trunk"
        # use default branch name
        # clear swift version
        set -e swift_version
    else if test -n "$swift_version"
        set swift_version "-$swift_version"
        set branch_name "swift$swift_version-branch"
    end

    if test -z "$days"
        set days 7
    end

    echo "Checking for Swift $branch_name snapshot releases ($days days)"
    echo

    set -l year (date "+%Y")
    set -l month (date "+%m")
    set -l current_day (date "+%d")

    # jot generates a decending sequence of integers
    for day in (jot $days $current_day 1 -1)
        # Zero pad month and day
        set month (printf "%02d" $month)
        set day (printf "%02d" $day)

        set -l date $year-$month-$day
        echo -n $date

        set -l release_slug "swift$swift_version-DEVELOPMENT-SNAPSHOT-$date-a"
        set -l url "https://swift.org/builds/$branch_name/xcode/$release_slug/$release_slug-osx.pkg"
        #echo $url

        set -l status_code (
            curl \
                --head \
                --location \
                --silent \
                --output /dev/null \
                --write-out "%{http_code}" \
                $url
       )

       echo " - $status_code"
       if test $status_code = 200
           echo $url
       end
    end
end


function git_exists -d 'Checks if git is present'
  # Use which instead of type. We always use command to execute
  # git and this is much, much cheaper
  which git 2> /dev/null >/dev/null
end

Use command -s instead of which

function git_exists -d 'Checks if git is present'
  # Use command -s instead of type. which would also
  # work, but a builtin must work
  command -s git 2> /dev/null >/dev/null
end


function src-hilite-lesspipe
    test -f $source_highlight_style_file; and set stylefile $source_highlight_style_file; or set stylefile esc.style
    for source in $argv
        switch "$source"
            case "*ChangeLog" "*changelog"
                source-highlight --failsafe -f esc --lang-def=changelog.lang --style-file=$stylefile -i "$source"
            case "Makefile" "*makefile"
                source-highlight --failsafe -f esc --lang-def=makefile.lang --style-file=$stylefile -i "$source"
            case "*.tar" "*.tgz" "*.gz" "*.bz2" "*.xz" "*.zip"
                lesspipe.sh "$source"
            case "*"
                source-highlight --failsafe --infer-lang -f esc --style-file=$stylefile -i "$source"
        end
    end
end

Add support for ubuntu lesspipe

function src-hilite-lesspipe
    test -f $source_highlight_style_file; and set stylefile $source_highlight_style_file; or set stylefile esc.style
    for source in $argv
        switch "$source"
            case "*ChangeLog" "*changelog"
                command source-highlight --failsafe -f esc --lang-def=changelog.lang --style-file=$stylefile -i "$source"
            case "Makefile" "*makefile"
                command source-highlight --failsafe -f esc --lang-def=makefile.lang --style-file=$stylefile -i "$source"
            case "*.tar" "*.tgz" "*.gz" "*.bz2" "*.xz" "*.zip"
                if type -qf lesspipe.sh
                    command lesspipe.sh "$source"
                else if type -qf lesspipe
                    command lesspipe "$source"
                end
            case "*"
                command source-highlight --failsafe --infer-lang -f esc --style-file=$stylefile -i "$source"
        end
    end
end


Add function to compare the same file between dirs

function vdiff -d "Vim diff the same file between directories"
  set --local lhs (realpath $argv[2])
  set --local rhs (realpath $argv[1]/$argv[2])
  echo "Diffing '$lhs' with '$rhs'"
  vimdiff $lhs $rhs
end


function add-user-to-group --argument-names user group
    print-status iam/add-user-to-group "$user $group"
    aws iam add-user-to-group --user-name $user --group-name $group
end


function _do_prompt_git
  git_exists; and git_is_git_repo
end

function fish_right_prompt
  if set -q VIRTUAL_ENV
    # Let's hope python won't break this way to read the version
    set -l python_version (python --version | sed -e 's/Python //g')
    set -l virtual_env_short (shorten_path $VIRTUAL_ENV)
    set_color -b yellow
    set_color black
    echo -n "$virtual_env_short@$python_version"
    set_color normal
  end
  set_color normal
  echo ""
end

Remove unused function in right prompt


# simotek prompt theme, by Simon Lees <http://github.com/simotek/>
function fish_greeting --description 'Print the shell greeting'
    colors

    set -l c_n '\x1b[94m'
    set -l c_w '\x1b[93m'

    set -l location (printf "\x1b[94mWelcome to \x1b[95m%s" (hostname))
    set -l system (printf "\x1b[94mRunning \x1b[95m%s\x1b[94m on \x1b[95m%s" (uname -mrs) (tty | sed -e 's/.*tty\(.*\)/\1/'))
    set -l datetime (printf "\x1b[94mIt is \x1b[95m%s\x1b[94m (%s) on \x1b[95m%s" (date +%T) (date +%Z) (date +%F))

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

end

Use defined env vars for colors

# simotek prompt theme, by Simon Lees <http://github.com/simotek/>
function fish_greeting --description 'Print the shell greeting'
    colors

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

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

end


function fish_right_prompt -d "Show right prompt"
    set last_status "$status"
    if math "$last_status > 0" >/dev/null
        set_color red
    else
        set_color green
    end
    echo -n "$last_status"
    set_color blue
    date "+%H%M" | tr -d '\n'
    set_color magenta
    date "+%h%d" | tr -d '\n'
    set_color normal
end

Fix broken right status prompt

function fish_right_prompt -d "Show right prompt"
    set last_status "$status"
    if test "$last_status" -gt 0 >/dev/null
        set_color red
    else
        set_color green
    end
    echo -n "$last_status"
    set_color blue
    date "+%H%M" | tr -d '\n'
    set_color magenta
    date "+%h%d" | tr -d '\n'
    set_color normal
end


function config_brew
    if contains $argv "clean"
        brew bundle cleanup --global --force
    end
    if not type brew >/dev/null ^&1
        echo "Install brew"
        return 1
    end
    brew tap "homebrew/bundle"
    brew update
    brew bundle --global
    brew cleanup
    brew cask cleanup
end

Make brew cleanup more intense

function config_brew
    if contains $argv "clean"
        brew bundle cleanup --global --force
    end
    if not type brew >/dev/null ^&1
        echo "Install brew"
        return 1
    end
    brew tap "homebrew/bundle"
    brew update
    brew bundle --global
    brew cleanup -s
    brew cask cleanup
end


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

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

function fish_prompt
  set -l last_status $status
  set -l cyan (set_color -o cyan)
  set -l yellow (set_color -o yellow)
  set -l red (set_color -o red)
  set -l blue (set_color -o blue)
  set -l green (set_color -o green)
  set -l normal (set_color normal)

  if test $last_status = 0
      set arrow "$green➜ "
  else
      set arrow "$red➜ "
  end
  set -l cwd $cyan(basename (prompt_pwd))

  if [ (_git_branch_name) ]

    if test (_git_branch_name) = 'master'
      set -l git_branch (_git_branch_name)
      set git_info "$normal ($red$git_branch$normal)"
    else
      set -l git_branch (_git_branch_name)
      set git_info "$normal ($blue$git_branch$normal)"
    end

    if [ (_is_git_dirty) ]
      set -l dirty "$yellow ✗"
      set git_info "$git_info$dirty"
    end
  end

  echo -n -s $arrow $cwd $git_info $normal ' '
end

Improve last command status indicator

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

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

function fish_prompt
  set -l last_status $status
  set -l cyan (set_color -o cyan)
  set -l yellow (set_color -o yellow)
  set -l red (set_color -o red)
  set -l blue (set_color -o blue)
  set -l green (set_color -o green)
  set -l normal (set_color normal)

  if test $last_status = 0
      set status_indicator "$green✔ "
  else
      set status_indicator "$red✗ "
  end
  set -l cwd $cyan(basename (prompt_pwd))

  if [ (_git_branch_name) ]

    if test (_git_branch_name) = 'master'
      set -l git_branch (_git_branch_name)
      set git_info "$normal ($red$git_branch$normal)"
    else
      set -l git_branch (_git_branch_name)
      set git_info "$normal ($blue$git_branch$normal)"
    end

    if [ (_is_git_dirty) ]
      set -l dirty "$yellow ✗"
      set git_info "$git_info$dirty"
    end
  end

  echo -n -s $status_indicator $cwd $git_info $normal ' '
end


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

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

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

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

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

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

# 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 ]
  source ~/.local.fish
end

Add workaround for emacs terminals

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

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

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

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

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

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

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

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

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

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


function parent --argument-names key limit
    if test -z "$key"
        print-status usage 'parent <key> [limit]'
    end

    if test -z "$limit"
        set limit 1
    end

    if test $limit -gt 1
        parent (dirname $key) (math $limit - 1)
    else
        dirname $key
    end
end

Abort if no arguments given

function parent --argument-names key limit
    if test -z "$key"
        print-status usage 'parent <key> [limit]'
        return -1
    end

    if test -z "$limit"
        set limit 1
    end

    if test $limit -gt 1
        parent (dirname $key) (math $limit - 1)
    else
        dirname $key
    end
end


function init -a path --on-event init_fonts
  set -g FONT_MOCK_INDEX "$path/mock_index.json"
  set -g FONT_MOCK_SHOW "$path/mock_show.json"

  set -q XDG_DATA_HOME;
      or set -l XDG_DATA_HOME "$HOME/.local"

  set -q FONTS_PATH;
    or set -g FONTS_PATH "$XDG_DATA_HOME/share/fonts"

  set -g FONTS_CONFIG "$OMF_CONFIG/fonts"

  mkdir -p $FONTS_CONFIG

end

Support OS X user font path

function init -a path --on-event init_fonts
  set -g FONT_MOCK_INDEX "$path/mock_index.json"
  set -g FONT_MOCK_SHOW "$path/mock_show.json"

  if not set -q FONTS_PATH
    if test 'Darwin' = (uname)
      set -g FONTS_PATH "$HOME/Library/Fonts"
    else
      set -q XDG_DATA_HOME; or set -l XDG_DATA_HOME "$HOME/.local"
      set -g FONTS_PATH "$XDG_DATA_HOME/share/fonts"
    end
  end

  set -g FONTS_CONFIG "$OMF_CONFIG/fonts"
  mkdir -p $FONTS_CONFIG

end


# Aliases

alias cat="bat"
alias flushdns="sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder"
alias ll="ls -lAh"
alias ls="gls --color"
alias v="nvim"

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Configure MariaDB

set PATH /usr/local/opt/mariadb/bin $PATH

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Set up dircolors

eval (gdircolors -c $HOME/.dircolors)

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Source prompt

starship init fish | source

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Source local config

source $HOME/.fishconfig.local

Include Homebrew’s executables path in $PATH

# Aliases

alias cat="bat"
alias flushdns="sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder"
alias ll="ls -lAh"
alias ls="gls --color"
alias v="nvim"

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Configure MariaDB

set PATH /usr/local/opt/mariadb/bin $PATH

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Include Homebrew’s executables path

set -g fish_user_paths "/usr/local/sbin" $fish_user_paths

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Set up dircolors

eval (gdircolors -c $HOME/.dircolors)

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Source prompt

starship init fish | source

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# Source local config

source $HOME/.fishconfig.local


function __fish_complete_plugin_cd -d "Completions for the plugin-cd command"
	set -l token (commandline -ct)
  set -l last_two_char (echo $token | sed 's/.*\(..\)/\1/')
  if test "$last_two_char" = ".."
    echo "$token/"
  else
    set -l base (echo $token | sed -e 's@^\(.*\)/[^/]*$@\1/@')
    set -l resolved_path (echo $token | sed -e 's@^\.$@:@;s@^\.\([^\.]\)@:\1@g;s@\([^\.]\)\.$@\1:@g' -e 's@\([^\.]\)\.\([^\.]\)@\1:\2@g' -e 's@\([^\.]\)\.\([^\.]\)@\1:\2@g' -e 's@\.\{2\}\(\.*\)@::\1@g' -e 's@\.@\/\.\.@g' -e 's@:@\.@g')

    if test -e $resolved_path; and not test -d $resolved_path
      return
    else
      printf "%s\n" (command ls -adp "$resolved_path"* | sed 's|.*/\([^/]*.\)$|\1|' | sed "s|^|$base|")
    end
  end
end

complete -c cd -e
complete -f -c cd -a "(__fish_complete_plugin_cd)"

Fix the complete error when file not exist

function __fish_complete_plugin_cd -d "Completions for the plugin-cd command"
	set -l token (commandline -ct)
  set -l last_two_char (echo $token | sed 's/.*\(..\)/\1/')
  if test "$last_two_char" = ".."
    echo "$token/"
  else
    set -l base (echo $token | rev | cut -d/ -s -f2- | rev )
    test -n $base; and set -l base $base/
    set -l resolved_path (echo $token | sed -e 's@^\.$@:@;s@^\.\([^\.]\)@:\1@g;s@\([^\.]\)\.$@\1:@g' -e 's@\([^\.]\)\.\([^\.]\)@\1:\2@g' -e 's@\([^\.]\)\.\([^\.]\)@\1:\2@g' -e 's@\.\{2\}\(\.*\)@::\1@g' -e 's@\.@\/\.\.@g' -e 's@:@\.@g')

    if test -e $resolved_path; and not test -d $resolved_path
      return
    else
      set -l path_test $resolved_path*
      if test -n "$path_test"
        printf "%s\n" (command ls -adp "$resolved_path"* | sed 's|.*/\([^/]*.\)$|\1|' | sed "s|^|$base|")
      end
    end
  end
end

complete -c cd -e
complete -f -c cd -a "(__fish_complete_plugin_cd)"


function shell::termcolor
  if not string match --quiet "256color" $TERM
    set --export --global TERM $argv[1]
  end
end

function shell::color
  if test -f "$HOME/.config/shell/$argv[1]"
    eval sh "$HOME/.config/shell/$argv[1]"
  end
end

function shell::dircolors
  if not test -f "$HOME/.config/shell/$argv[1]"
    return
  end

  set try_cmds "dircolors" "gdircolors"
  set cmd

  for try_cmd in $try_cmds
    if command --search --quiet $try_cmd
      set cmd $try_cmd
      break
    end
  end

  bass (eval $cmd "$HOME/.config/shell/$argv[1]")
end


#!/usr/bin/env fish

set -x ASDF_DIR (dirname (status -f))
set -l asdf_data_dir (
  if test -n "$ASDF_DATA_DIR"; echo $ASDF_DATA_DIR;
  else; echo $HOME/.asdf; end)

# Add asdf to PATH
set -l asdf_bin_dirs $ASDF_DIR/bin $ASDF_DIR/shims $asdf_data_dir/shims

for x in $asdf_bin_dirs
  set PATH $x (string match -v $x $PATH)
end

# Add function wrapper so we can export variables
function asdf
  set command $argv[1]
  set -e argv[1]

  switch "$command"
  case "shell"
    # eval commands that need to export variables
    source (env ASDF_SHELL=fish asdf "sh-$command" $argv | psub)
  case '*'
    # forward other commands to asdf script
    command asdf "$command" $argv
  end
end

Fix setting PATH to work with fish 2.2

#!/usr/bin/env fish

set -x ASDF_DIR (dirname (status -f))
set -l asdf_data_dir (
  if test -n "$ASDF_DATA_DIR"; echo $ASDF_DATA_DIR;
  else; echo $HOME/.asdf; end)

# Add asdf to PATH
set -l asdf_bin_dirs $ASDF_DIR/bin $ASDF_DIR/shims $asdf_data_dir/shims

for x in $asdf_bin_dirs
  if test -d $x
    set PATH $x (echo $PATH | command xargs printf '%s\n' | command grep -v $x)
  end
end

# Add function wrapper so we can export variables
function asdf
  set command $argv[1]
  set -e argv[1]

  switch "$command"
  case "shell"
    # eval commands that need to export variables
    source (env ASDF_SHELL=fish asdf "sh-$command" $argv | psub)
  case '*'
    # forward other commands to asdf script
    command asdf "$command" $argv
  end
end


Add function to find real users in a group

function real-users-in-group --argument group
    if empty "$group"
        usage real-users-in-group '<group>'
        return (false)
    end

    print-status real-users-in-group "$argv"

    aws iam get-group --group-name "$group" | jq --raw-output .Users[].UserName | sort
end


Add command to set fish color scheme to monokai

function set_colors_monokai
	# Colors:
	set fish_color_normal normal # the default color
	set fish_color_command F92672 # the color for commands
	set fish_color_quote E6DB74 # the color for quoted blocks of text
	set fish_color_redirection 66D9EF # the color for IO redirections
	set fish_color_end F92672 # the color for process separators like ';' and '&'
	set fish_color_error F8F8F2 --background=F92672 # the color used to highlight potential errors
	set fish_color_param normal # the color for regular command parameters
	set fish_color_comment 75715E # the color used for code comments
	set fish_color_match normal # the color used to highlight matching parenthesis
	set fish_color_search_match --background=49483E # the color used to highlight history search matches
	set fish_color_operator 66D9EF # the color for parameter expansion operators like '*' and '~'
	set fish_color_escape AE81FF # the color used to highlight character escapes like '\n' and '\x70'
	set fish_color_cwd A6E22E # the color used for the current working directory in the default prompt
	set fish_color_cwd_root F92672 # the color used for the current working directory in a root prompt
	set fish_color_user A6E22E # the color used to print the current username in some of fish default prompts
	set fish_color_host FD971F # the color used to print the current host system in some of fish default prompts
	set fish_color_autosuggestion 75715E # the color used for autosuggestions
	set fish_color_status F92672

	# Additionally, the following variables are available to change the highlighting in the completion pager:
	set fish_pager_color_prefix normal # the color of the prefix string, i.e. the string that is to be completed
	set fish_pager_color_completion 75715E # the color of the completion itself
	set fish_pager_color_description 66D9EF # the color of the completion description
	set fish_pager_color_progress normal # the color of the progress bar at the bottom left corner
	set fish_pager_color_secondary normal # the background color of the every second completion
end


function pacman-recent --description="Show last 25 upgraded/installed packages"
  command tac /var/log/pacman.log | head -n 1000 | grep --ignore-case --extended-regexp 'installed|upgraded' | tail --lines=25
end

Increase to last 50 items

function pacman-recent --description="Show last 25 upgraded/installed packages"
  command tac /var/log/pacman.log | head -n 1000 | grep --ignore-case --extended-regexp 'installed|upgraded' | tail --lines=50
end


function fish_prompt
	# save exit status so it's not clobbered by successful commands below
	set -l exit_code $status
	set -l hostname_prefix ""
	set -l directory_prefix ""

	# if we're not who we logged in as, display the username
	if [ (whoami) != "mpcsh" ]
		set hostname_prefix "at "
		set directory_prefix "in "

		if [ (whoami) = "root" ]
			set_color red
		else
			set_color green
		end
		printf "%s " (whoami)
		set_color normal
	end

	# if we're ssh'ed, display the hostname
	if test -n "$SSH_CONNECTION"
		set directory_prefix "in "

		printf "%s" $hostname_prefix
		set_color yellow
		printf "%s " (hostname)
		set_color normal
	end

	# print PWD
	printf "%s" $directory_prefix
	set_color blue
	printf "%s " (prompt_pwd)
	set_color normal

	# prompt char - red if previous command failed
	if test $exit_code -ne 0
		set_color red
	end
	printf "» "
	set_color normal
end

function fish_right_prompt
	# git status
	set_color purple
	printf "%s" (__fish_git_prompt)
	set_color normal
end

Speed up fish launch (remove command-not-found)

function fish_prompt
	# save exit status so it's not clobbered by successful commands below
	set -l exit_code $status
	set -l hostname_prefix ""
	set -l directory_prefix ""

	# if we're not who we logged in as, display the username
	if [ $USER != "mpcsh" ]
		set hostname_prefix "at "
		set directory_prefix "in "

		if [ $USER = "root" ]
			set_color red
		else
			set_color green
		end
		printf "%s " $USER
		set_color normal
	end

	# if we're ssh'ed, display the hostname
	if test -n "$SSH_CONNECTION"
		set directory_prefix "in "

		printf "%s" $hostname_prefix
		set_color yellow
		printf "%s " (hostname)
		set_color normal
	end

	# print PWD
	printf "%s" $directory_prefix
	set_color blue
	printf "%s " (prompt_pwd)
	set_color normal

	# prompt char - red if previous command failed
	if test $exit_code -ne 0
		set_color red
	end
	printf "» "
	set_color normal
end

function fish_right_prompt
	# git status
	set_color purple
	printf "%s" (__fish_git_prompt)
	set_color normal
end


function _pure_set_color \
    --description 'Set color' \
    --argument-names var

    set --local color $var
    if set -q $var
        set color $$var
    end

    set --local result (set_color $color)
    echo "$result"
end

Read escape sequences from color variables for backwards compatibility

function _pure_set_color \
    --description 'Set color' \
    --argument-names var

    set --local color $var
    # Backwards compatibility for colors defined as control sequencies instead of fish colors
    if not string match --quiet --all --regex '\e\[[^m]*m' $color[1]
        and set -q $color
            set color $$var
    end

    set --local result $color
    if not string match --quiet --all --regex '\e\[[^m]*m' $result[1]
        set result (set_color $color)
    end

    echo "$result"
end


function up --description "Starts a php:apache Docker container using the current path on a random port"
    set -l port (shuf -i 8000-8099 -n 1)
    set -l cdir (pwd | string replace 'cygdrive' '')
    subl .
    cygstart http://docker:{$port}
    docker run --rm -v $cdir:/var/www/html -p {$port}:80 php:apache
end

Use Docker composer if there is a file with the given port

function up --description "Starts a php:apache Docker container using the current path on a random port or the Docker compose"
    subl .

    if test -e ./docker-compose.yml
        cygstart http://docker:{$argv}
        docker-compose up
    else
        set -l cdir (pwd | string replace 'cygdrive' '')
        set -l port (shuf -i 8000-8099 -n 1)

        cygstart http://docker:{$port}
        docker run --rm -v {$cdir}:/var/www/html -p {$port}:80 php:apache
    end
end


fish_vi_key_bindings

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

set -x GOPATH "$HOME/go"

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

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

Add npm installed bin directory

fish_vi_key_bindings

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

set -x GOPATH "$HOME/go"

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

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


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

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

    echo " $ref "
    set_color normal
   end
end

function fish_right_prompt -d "Prints right prompt"
  get_git_status
end

Add commit hash to right prompt when deattached

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

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

    echo " $ref "
    set_color normal
   end
end

function fish_right_prompt -d "Prints right prompt"
  get_git_status
end


function review_end
  set current_branch (git branch | ag -Q \* | cut -f 2 -d ' ')

  if [ $current_branch = "master" ]
    echo "Already on master"
  else
    git co master
    git branch -D $current_branch
  end
end

Switch to main by default

function review_end
  set current_branch (git branch | ag -Q \* | cut -f 2 -d ' ')

  if [ $current_branch = "main" ]
    echo "Already on main"
  else
    git co main
    git branch -D $current_branch
  end
end


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

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

function fish_prompt
  set -l last_status $status
  set -l cyan (set_color -o cyan)
  set -l yellow (set_color -o yellow)
  set -l red (set_color -o red)
  set -l blue (set_color -o blue)
  set -l green (set_color -o green)
  set -l normal (set_color normal)

  if test $last_status = 0
      set arrow "$green➜ "
  else
      set arrow "$red➜ "
  end
  set -l cwd $cyan(basename (prompt_pwd))

  if [ (_git_branch_name) ]
    set -l git_branch $red(_git_branch_name)
    set git_info "$blue git:($git_branch$blue)"

    if [ (_is_git_dirty) ]
      set -l dirty "$yellow ✗"
      set git_info "$git_info$dirty"
    end
  end

  echo -n -s $arrow $cwd $git_info $normal ' '
end

Add space between the arrow and current directory name in robbyrussell theme

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

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

function fish_prompt
  set -l last_status $status
  set -l cyan (set_color -o cyan)
  set -l yellow (set_color -o yellow)
  set -l red (set_color -o red)
  set -l blue (set_color -o blue)
  set -l green (set_color -o green)
  set -l normal (set_color normal)

  if test $last_status = 0
      set arrow "$green➜ "
  else
      set arrow "$red➜ "
  end
  set -l cwd $cyan(basename (prompt_pwd))

  if [ (_git_branch_name) ]
    set -l git_branch $red(_git_branch_name)
    set git_info "$blue git:($git_branch$blue)"

    if [ (_is_git_dirty) ]
      set -l dirty "$yellow ✗"
      set git_info "$git_info$dirty"
    end
  end

  echo -n -s $arrow ' ' $cwd $git_info $normal ' '
end


Add a function to show the contents of various compressed file formats

function show_archive --description "List contents of compressed files"
  for file in $argv
    if test -f $file
      echo -s "Listing: " (set_color --bold blue) $file (set_color normal)
      switch $file
        case *.tar
          tar -tf $file
        case *.tar.bz2 *.tbz2
          bunzip2 -c $file | tar -tf - --
        case *.tar.gz *.tgz
          tar -ztf $file
        case *.zip *.ZIP
          unzip -l $file
        case *.bz2
          bunzip2 $file
          # Can also use: bzip2 -d $file
        case *.gz
          gunzip $file
        case *.rar
          unrar x $file
        case *.pax
          pax -r < $file
        case '*'
          echo "Extension not recognized, cannot list contents of $file"
      end
    else
      echo "$file is not a valid file"
    end
  end
end


# Go
function g -d 'Change directory and look up'
  set is_okay true
  if test -z $argv
    cd -
  else
    if test -e $argv
      cd $argv
    else
      set is_okay false
      set_color $red
      echo 'Cannot find "'$argv'"'
      set_color normal
    end
  end

  if eval $is_okay
    ls -AF .
  end
end
alias gh 'g $HOME'
alias gconfig 'g $HOME/.config/fish/'
alias grepo 'g $HOME/repos/'
alias .. 'g ..'
alias ... 'g ../..'
alias .... 'g ../../..'
alias ..... 'g ../../../..'

# See
function s -d 'List files in details'
  ls -AFlh $argv
end
function st -d 'List files ordered from oldest to newest'
  s -tr
end
function sf -d 'List files with filter'
  s | grep $argv
end

Use exa for list current directory is possible

# Go
function g -d 'Change directory and look up'
  set is_okay true
  if test -z $argv
    cd -
  else
    if test -e $argv
      cd $argv
    else
      set is_okay false
      set_color $red
      echo 'Cannot find "'$argv'"'
      set_color normal
    end
  end

  if eval $is_okay
    ls -AF .
  end
end
alias gh 'g $HOME'
alias gconfig 'g $HOME/.config/fish/'
alias grepo 'g $HOME/repos/'
alias .. 'g ..'
alias ... 'g ../..'
alias .... 'g ../../..'
alias ..... 'g ../../../..'

# See
function s -d 'List files in details'
  if type -q exa;
		exa -la $argv
	else;
		ls -AFlh $argv
	end
end
function st -d 'List files ordered from oldest to newest'
  s -tr
end
function sf -d 'List files with filter'
  s | grep $argv
end


function setup-mac --description "Setup script for OS X"

  function _setup_homebrew
    if not type brew >/dev/null
      ruby -e (curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)
      brew update
    end
    echo "homebrew installed"
  end

  function _setup_rbenv
    if not type rbenv >/dev/null
      brew install --HEAD rbenv ruby-build rbenv-default-gems
      rbenv rehash
      echo "To update rbenv and ruby-build, brew update; and brew upgrade --HEAD rbenv ruby-build"
    end
    echo "rbenv installed"
  end

  function _setup_aliases
    if test -f ~/.config/fish/osx-aliases.fish
      source ~/.config/fish/osx-aliases.fish
      echo "mac aliases installed"
    end
  end

  function _run_osx_script
    if test -f ~/.osx
      source ~/.osx
    else
      echo "Could not find OS X script"
    end
  end

  _setup_homebrew
  _setup_rbenv
  _setup_aliases
  _run_osx_script

end

Print reminders for tasks easier done manually

function setup-mac --description "Setup script for OS X"

  function _setup_homebrew
    if not type brew >/dev/null
      ruby -e (curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)
      brew update
    end
    echo "homebrew installed"
  end

  function _setup_rbenv
    if not type rbenv >/dev/null
      brew install --HEAD rbenv ruby-build rbenv-default-gems
      rbenv rehash
      echo "To update rbenv and ruby-build, brew update; and brew upgrade --HEAD rbenv ruby-build"
    end
    echo "rbenv installed"
  end

  function _setup_aliases
    if test -f ~/.config/fish/osx-aliases.fish
      source ~/.config/fish/osx-aliases.fish
      echo "mac aliases installed"
    end
  end

  function _run_osx_script
    if test -f ~/.osx
      source ~/.osx
    else
      echo "Could not find OS X script"
    end
  end

  function _print_reminders
    echo -e "A few more things you may wish to do:
     - gem install iStats"
  end

  _setup_homebrew
  _setup_rbenv
  _setup_aliases
  _run_osx_script
  _print_reminders
end


. helper.fish

function setup_tank
  function ruby-build
    switch $argv[1]
      case '--definitions'
        echo 'known'
      case '*'
        echo "ruby-build $argv"
    end
  end
end

function clean_tank
  functions -e which
  functions -e ruby-build
end

function it_returns_status_1_without_ruby-build
  function which; return 1; end

  fry-install
  test $status -eq 1
end

function it_outputs_error_message_without_ruby-build
  function which; return 1; end

  test (fry-install) = 'fry-install: This feature requires ruby-build'
end

function it_returns_status_1_without_args
  fry-install
  test $status -eq 1
end

function it_outputs_ruby-build_definitions_without_args
  contains 'known' (fry-install)
end

function it_outputs_error_message_without_args
  contains 'fry-install: No <ruby> given' (fry-install)
end

function it_returns_status_1_when_unknown
  fry-install unknown
  test $status -eq 1
end

function it_outputs_ruby-build_definitions_when_unknown
  contains 'known' (fry-install unknown)
end

function it_outputs_error_message_when_unknown
  contains "fry-install: Unknown ruby 'unknown'" (fry-install unknown)
end

function it_returns_status_0_when_known
  fry-install known
  test $status -eq 0
end

function it_installs_ruby_when_known
  contains "ruby-build known $fry_rubies/known" (fry-install known)
end

. $fish_tank


# Initializes GPG agent on OSX, for signing Git commits, etc.
function gpg-init
    if not begin
        # Is the agent running already? Does the agent-info file exist, and if so,
        # is there a process with the pid given in the file?
        [ -f ~/.gnupg/.gpg-agent-info ]
              and kill -0 (cut -d : -f 2 ~/.gnupg/.gpg-agent-info) ^/dev/null
    end
         # no, it is not running. Start it!
        gpg-agent --daemon --no-grab \
            --write-env-file ~/.gnupg/.gpg-agent-info \
            >/dev/null ^&1
    end
         # get the agent info from the info file, and export it so GPG can see it.
    set -gx GPG_AGENT_INFO (cut -c 16- ~/.gnupg/.gpg-agent-info)
    set -gx GPG_TTY (tty)
end

Kill GPG agent before starting a new one

function gpg-init
	if not begin
        # Is the agent running already? Does the agent-info file exist, and if so,
        # is there a process with the pid given in the file?
        [ -f ~/.gnupg/.gpg-agent-info ]
              and kill -0 (cut -d : -f 2 ~/.gnupg/.gpg-agent-info) ^/dev/null
    end
         # no, it is not running. Start it!
        killall gpg-agent; and
        gpg-agent --daemon --no-grab \
            --write-env-file ~/.gnupg/.gpg-agent-info \
            >/dev/null ^&1
    end
         # get the agent info from the info file, and export it so GPG can see it.
    set -gx GPG_AGENT_INFO (cut -c 16- ~/.gnupg/.gpg-agent-info)
    set -gx GPG_TTY (tty)
end


Add function to find corresponding key for secrets

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

    if empty $key
        usage keys-for-secret '<key>'
        return 23
    end

    if is-secret $key
        get $key | gpg --batch --list-packets --quiet | string match ":pubkey *" | awk '{ print $NF }'
    else
        false
    end
end


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

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

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

fish_vi_mode

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

set -x GOPATH "$HOME/go"

source /usr/share/autojump/autojump.fish

Add pip completion to fish

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

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

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

fish_vi_mode

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

set -x GOPATH "$HOME/go"

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

source /usr/share/autojump/autojump.fish


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

Update fish 2.4.0 vi insert mode bindings

function vi_key_bindings
    fish_vi_key_bindings

    bind -M insert \ca beginning-of-line
    bind -M insert \ce end-of-line
    bind -M insert \cf accept-autosuggestion
end


function _prompt_dir_component
  _prompt_wrap_text (abbreviated_working_directory) brblue
end

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

function _prompt_git_component
  if git rev-parse --git-dir > /dev/null ^ /dev/null
    _prompt_wrap_text (git rev-parse --abbrev-ref HEAD) green
  end
end

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

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

Add ability to display tag name or short SHA

function _prompt_dir_component
  _prompt_wrap_text (abbreviated_working_directory) brblue
end

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

function _prompt_git_component
  if git rev-parse --git-dir >/dev/null ^&1
    set --local sha (git rev-parse HEAD)
    set --local ref (git show-ref --tags --heads | grep $sha; or echo '')

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

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

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

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


import plugins/fish-spec
import plugins/ta

function describe_ta -d "ta: to-done task manager"
    function before_all
    end

    function after_all
    end

    # function it_does_something
    # end

end

spec.run $argv

Add test stub for ta plugin.

import plugins/fish-spec
import plugins/ta

function describe_ta -d "ta: to-done task manager"
    function before_all
    end

    function after_all
    end

    function it_does_something
      ta -h
      expect $status --to-equal 0
    end

end

spec.run $argv


# This file should be sourced from your ~/.config/config.fish file.
#
# Copyright 2014-2016 Simon Edwards <simon@simonzone.com>
#
# This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
#

if test -n "$EXTRATERM_COOKIE"
    echo "Setting up Extraterm support."

    # Put our enhanced commands at the start of the PATH.
    set -l filedir (dirname (status -f))
    set -x PATH $PWD/$filedir $PATH

    function extraterm_preexec -e fish_preexec
      echo -n -e -s "\033&" $EXTRATERM_COOKIE ";2;fish\007"
      echo -n $argv[1]
      echo -n -e "\000"
    end

    function extraterm_postexec -e fish_postexec
      set -l status_backup $status
      echo -n -e -s "\033" "&" $EXTRATERM_COOKIE ";3\007"
      echo -n $status_backup
      echo -n -e "\000"
    end

    function from
        exfrom.py $argv
    end

    function show
        exshow.py $argv
    end
end

Fix for the fish shell integration and the path setting. The problem only affected fish on cygwin.

# This file should be sourced from your ~/.config/config.fish file.
#
# Copyright 2014-2016 Simon Edwards <simon@simonzone.com>
#
# This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
#

if test -n "$EXTRATERM_COOKIE"
    echo "Setting up Extraterm support."

    # Put our enhanced commands at the start of the PATH.
    set -l filedir (dirname (status -f))
    set -x PATH (realpath $filedir) $PATH

    function extraterm_preexec -e fish_preexec
      echo -n -e -s "\033&" $EXTRATERM_COOKIE ";2;fish\007"
      echo -n $argv[1]
      echo -n -e "\000"
    end

    function extraterm_postexec -e fish_postexec
      set -l status_backup $status
      echo -n -e -s "\033" "&" $EXTRATERM_COOKIE ";3\007"
      echo -n $status_backup
      echo -n -e "\000"
    end

    function from
        exfrom.py $argv
    end

    function show
        exshow.py $argv
    end
end


# Set the prompt.
function fish_prompt --description "Write out the prompt"
	echo -n "$USER:"
	set_color $fish_color_cwd
	echo -ns (prompt_pwd)
	set_color normal
	echo -ns '> '
end

# Shortcuts
function sz --description "Calculate the size of a directory"
	command du -sh $argv
end
function upd --description "Updates homebrew packages"
	command brew update
	and command brew upgrade
end
function blog --description "Starts the Hugo server for my blog"
	cd ~/icloud/blog
	and command hugo server -w
end
function notif --description "Makes a notification via Notification Center"
	command terminal-notifier -activate com.apple.Terminal -message "$argv"
end
function sucontext --description "Sets up the ConTeXt root"
	echo "TODO: implement this function"
end

# Environment variables
set dev ~/Development
set go_root (command go env GOROOT)
set -x GOPATH $dev/go
set -x VAGRANT_CWD $dev/vagrant
set -x EDITOR vim

# Path
set PATH $PATH $dev/scripts $GOPATH/bin $go_root/bin ~/.cabal/bin

Change echo options for prompt to work in vagrant

# Set the prompt.
function fish_prompt --description "Write out the prompt"
	echo -n "$USER:"
	set_color $fish_color_cwd
	echo -n (prompt_pwd)
	set_color normal
	echo -n '> '
end

# Shortcuts
function sz --description "Calculate the size of a directory"
	command du -sh $argv
end
function upd --description "Updates homebrew packages"
	command brew update
	and command brew upgrade
end
function blog --description "Starts the Hugo server for my blog"
	cd ~/icloud/blog
	and command hugo server -w
end
function notif --description "Makes a notification via Notification Center"
	command terminal-notifier -activate com.apple.Terminal -message "$argv"
end
function sucontext --description "Sets up the ConTeXt root"
	echo "TODO: implement this function"
end

# Environment variables
set dev ~/Development
set go_root (command go env GOROOT)
set -x GOPATH $dev/go
set -x VAGRANT_CWD $dev/vagrant
set -x EDITOR vim

# Path
set PATH $PATH $dev/scripts $GOPATH/bin $go_root/bin ~/.cabal/bin


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

Increase the zubora function visibility

# 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 zubora -d "zubora 'commit message' [files to add;optional]"
    if test (count $argv) -gt 1
        set_color -o; echo \$git add $argv[2..-1]
        set_color normal; git add $argv[2..-1]
    else
        set_color -o; echo \$git add -A
        set_color normal; git add -A
    end
    set_color -o; echo \$git commit -m $argv[1]
    set_color normal; git commit -m $argv[1]
    set_color -o; echo \$git push
    set_color normal; git push
end


#!/usr/bin/fish

set -x DISPLAY=:20.0
set -x GOMA_DIR=$HOME/goma
python $GOMA_DIR/goma_ctl.py ensure_start

Use proper fish shell syntax for export

#!/usr/bin/fish

set -x DISPLAY :20.0
set -x GOMA_DIR $HOME/goma
python $GOMA_DIR/goma_ctl.py ensure_start


#!/usr/bin/env fish

set fish_greeting
set -x GOPATH $HOME/Code/gopkg
set -x MAILDIR $HOME/mail
set -x EDITOR vim
set -x GEM_HOME $HOME/.local/gems/(ruby -v | awk '{print $2}')
set -x GEM_PATH $GEM_HOME
set -x HOMEBREW_BUILD_FROM_SOURCE 1
set -x COCOAPODS_DISABLE_STATS 1
set -x PATH $GEM_HOME/bin $HOME/bin $GOPATH/bin \
            /usr/local/bin /usr/local/sbin /usr/bin \
            /bin /usr/sbin /sbin /usr/local/go/bin

source /usr/local/share/chruby/chruby.fish
source $HOME/.config/fish/functions/aliases.fish

Set /usr/bin first in PATH

#!/usr/bin/env fish

set fish_greeting
set -x GOPATH $HOME/Code/gopkg
set -x MAILDIR $HOME/mail
set -x EDITOR vim
set -x GEM_HOME $HOME/.local/gems/(ruby -v | awk '{print $2}')
set -x GEM_PATH $GEM_HOME
set -x HOMEBREW_BUILD_FROM_SOURCE 1
set -x COCOAPODS_DISABLE_STATS 1
set -x PATH /usr/bin $GEM_HOME/bin $HOME/bin \
            /usr/local/bin /usr/local/sbin $GOPATH/bin \
            /bin /usr/sbin /sbin /usr/local/go/bin

source /usr/local/share/chruby/chruby.fish
source $HOME/.config/fish/functions/aliases.fish


set POWERLINE_COMMAND "$PWD/scripts/powerline -p $PWD/powerline/config_files"
set POWERLINE_COMMAND "$POWERLINE_COMMAND -t default_leftonly.segment_data.hostname.args.only_if_ssh=false"
set POWERLINE_COMMAND "$POWERLINE_COMMAND -c ext.shell.theme=default_leftonly"
set VIRTUAL_ENV
source powerline/bindings/fish/powerline.fish ; cd tests/shell/3rd
cd .git
cd ..
set VIRTUAL_ENV "$HOME/.virtenvs/some-virtual-environment"
set VIRTUAL_ENV
bash -c "echo \$\$>pid ; while true ; do sleep 0.1s ; done" &
false
kill (cat pid) ; sleep 1s
false
true is the last line
exit

Use `.` for sourcing in fish

set POWERLINE_COMMAND "$PWD/scripts/powerline -p $PWD/powerline/config_files"
set POWERLINE_COMMAND "$POWERLINE_COMMAND -t default_leftonly.segment_data.hostname.args.only_if_ssh=false"
set POWERLINE_COMMAND "$POWERLINE_COMMAND -c ext.shell.theme=default_leftonly"
set VIRTUAL_ENV
. powerline/bindings/fish/powerline.fish ; cd tests/shell/3rd
cd .git
cd ..
set VIRTUAL_ENV "$HOME/.virtenvs/some-virtual-environment"
set VIRTUAL_ENV
bash -c "echo \$\$>pid ; while true ; do sleep 0.1s ; done" &
false
kill (cat pid) ; sleep 1s
false
true is the last line
exit


set LS_COLORS dxfxcxdxbxegedabagacad

function serve
        if test (count $argv) -ge 1
            if python -c 'import sys; sys.exit(sys.version_info[0] != 3)'
                /bin/sh -c "(cd $argv[1] && python -m http.server)"
            else
                /bin/sh -c "(cd $argv[1] && python -m SimpleHTTPServer)"
            end
        else
            python -m SimpleHTTPServer
        end
end

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 pmr 'python manage.py runserver'
alias ipn 'ipython notebook'

alias git hub
alias top 'glances'

alias pkill-emacs 'pkill -SIGUSR2 Emacs'

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

alias psql pgcli

Add alias for `python manage.py shell_plus`

set LS_COLORS dxfxcxdxbxegedabagacad

function serve
        if test (count $argv) -ge 1
            if python -c 'import sys; sys.exit(sys.version_info[0] != 3)'
                /bin/sh -c "(cd $argv[1] && python -m http.server)"
            else
                /bin/sh -c "(cd $argv[1] && python -m SimpleHTTPServer)"
            end
        else
            python -m SimpleHTTPServer
        end
end

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 git hub
alias top 'glances'

alias pkill-emacs 'pkill -SIGUSR2 Emacs'

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

alias psql pgcli


function __parse_git_branch
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
end

function fish_prompt --description 'Write out the prompt'
	# Just calculate this once, to save a few cycles when displaying the prompt
	if not set -q __fish_prompt_hostname
		set -g __fish_prompt_hostname (hostname|cut -d . -f 1)
	end

	set -l color_cwd
	set -l suffix
	switch $USER
	case root toor
		if set -q fish_color_cwd_root
			set color_cwd $fish_color_cwd_root
		else
			set color_cwd yellow
		end
		set suffix '#'
	case '*'
		set color_cwd yellow
		set suffix '>'
	end

	echo -s (set_color green) "$USER" @ "$__fish_prompt_hostname" ' ' (set_color $color_cwd) (prompt_pwd) (set_color red) (__parse_git_branch) (set_color normal)
	echo "$suffix "
end

Add right prompt to fish config

function __parse_git_branch
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
end

function fish_prompt --description 'Write out the prompt'
    # Just calculate this once, to save a few cycles when displaying the prompt
    if not set -q __fish_prompt_hostname
        set -g __fish_prompt_hostname (hostname|cut -d . -f 1)
    end

    set -l color_cwd
    set -l suffix
    switch $USER
    case root toor
        if set -q fish_color_cwd_root
            set color_cwd $fish_color_cwd_root
        else
            set color_cwd yellow
        end
        set suffix '#'
    case '*'
        set color_cwd yellow
        set suffix '>'
    end

    set -l prompt_pwd (prompt_pwd)
    set -l git_branch (__parse_git_branch)

    set -l left_prompt "$USER@$__fish_prompt_hostname $prompt_pwd $git_branch"
    set -l left_prompt_color (set_color green)"$USER@$__fish_prompt_hostname" (set_color yellow)$prompt_pwd (set_color red)$git_branch

    set -l right_prompt (date "+%y-%m-%d %H:%M:%S")
    set -l right_prompt_color (set_color normal)$right_prompt

    set -l columns (math $COLUMNS - (string length $left_prompt) - (string length $right_prompt) + 27)
    if not test -n "$git_branch"
        set columns (math $columns + 1)
    end

    printf "%s %"$columns"s\n" "$left_prompt_color" "$right_prompt_color"
    echo -s (set_color normal) "$suffix "
end


function update-casks -d "Update, upgrade, and cleanup Homebrew casks"
  command brew cask update; and brew cu; and brew cask cleanup; and brew cask doctor
end

Remove duplicates in `Open With` menu.

function update-casks -d "Update, upgrade, and cleanup Homebrew casks"
  command brew cask update; and brew cu; and brew cask cleanup; and brew cask doctor
  # Remove duplicates in the “Open With” menu
  /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user
end


Add function to show functions visible to fish.

function list-functions --description "Lists all autoloaded functions fish can see. Does not guarantee order."
	for dir in $fish_function_path
		for func in (ls "$dir")
			echo "$func"
		end
	end
end


# urdh prompt theme, by Simon Sigurdhsson <http://github.com/urdh/>
function fish_greeting --description 'Print the shell greeting'
    colors

    set -l c_n '\x1b[92m'
    set -l c_w '\x1b[93m'

    set -l location (printf "\x1b[92mWelcome to \x1b[95m%s" (hostname))
    set -l system (printf "\x1b[92mRunning \x1b[95m%s\x1b[92m on \x1b[95m%s" (uname -mrs) (tty | sed -e 's/.*tty\(.*\)/\1/'))
    set -l datetime (printf "\x1b[92mIt is \x1b[95m%s\x1b[92m (%s) on \x1b[95m%s" (date +%T) (date +%Z) (date +%F))

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

end

Change greeting colors for the billionth time

# urdh prompt theme, by Simon Sigurdhsson <http://github.com/urdh/>
function fish_greeting --description 'Print the shell greeting'
    colors

    set -l c_n '\x1b[94m'
    set -l c_w '\x1b[93m'

    set -l location (printf "\x1b[94mWelcome to \x1b[95m%s" (hostname))
    set -l system (printf "\x1b[94mRunning \x1b[95m%s\x1b[94m on \x1b[95m%s" (uname -mrs) (tty | sed -e 's/.*tty\(.*\)/\1/'))
    set -l datetime (printf "\x1b[94mIt is \x1b[95m%s\x1b[94m (%s) on \x1b[95m%s" (date +%T) (date +%Z) (date +%F))

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

end


set --export EDITOR vim
set --export PATH /usr/local/bin $PATH

set fish_color_command white
set fish_color_autosuggestion yellow
set fish_pager_color_description yellow
set fish_color_param white

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

Fix a brew doctor issue

set --export EDITOR vim
set --export PATH /usr/local/bin $PATH
set --export PATH /usr/local/sbin $PATH

set fish_color_command white
set fish_color_autosuggestion yellow
set fish_pager_color_description yellow
set fish_color_param white

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


#!/usr/local/bin/fish

set applicationsFolder "/Applications"
set apps "CodeKit" "Tower" "Transmit" "MAMP PRO"

# Functions

function __open_app
    set -l application $argv
    echo "Opening $application..."
    osascript -e "launch app \"$application\""
end

function __close_app
    set -l application $argv
    echo "Closing $application..."
    osascript -e "quit app \"$application\""
end

# Handle command line args
set -l mode open
while set -q argv[1]
    switch $argv[1]
        case '-h' '--help'
            __fish_print_help abbr
            exit
        case '-o' '--open'
            set mode add
        case '-c' '--close'
            set mode close
        case '*'
            __fish_print_help abbr
            exit
    end
    set -e argv[1]
end

# Run the app
for application in $apps
    switch $mode
        case 'open'
            __open_app "$application"
        case 'close'
            __close_app "$application"
    end
end


############################################
# ALIASES
############################################

# navigation
alias .. "cd .."
alias ... "cd ../.."
alias .... "cd ../../.."
alias ..... "cd ../../../.."

# shortcuts
alias dt "cd ~/Desktop"
alias dl "cd ~/Downloads"
alias p "cd ~/Projects"
alias f "cd ~/Projects/fathom"

# listings
alias l "ls -laF"

# git
alias gs "git status -s"
alias ga "git add"
alias gc "git commit"

# enable aliases to be sudo’ed
alias sudo "sudo "

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

# show/hide desktop (useful when presenting)
alias showdesktop="defaults write com.apple.finder CreateDesktop -bool true and killall Finder"
alias hidedesktop="defaults write com.apple.finder CreateDesktop -bool false and killall Finder"

############################################
# FUNCTIONS
############################################

# create a new directory and cd into it
function mkd
	mkdir -p $argv; and cd $argv
end

Fix aliases to work with fish

############################################
# ALIASES
############################################

# navigation
alias .. "cd .."
alias ... "cd ../.."
alias .... "cd ../../.."
alias ..... "cd ../../../.."

# shortcuts
alias dt "cd ~/Desktop"
alias dl "cd ~/Downloads"
alias p "cd ~/Projects"
alias f "cd ~/Projects/fathom"

# listings
alias l "ls -laF"

# git
alias gs "git status -s"
alias ga "git add"
alias gc "git commit"

# enable aliases to be sudo’ed
alias sudo "sudo "

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

# show/hide desktop (useful when presenting)
alias showdesktop "defaults write com.apple.finder CreateDesktop -bool true; and killall Finder"
alias hidedesktop "defaults write com.apple.finder CreateDesktop -bool false; and killall Finder"

############################################
# FUNCTIONS
############################################

# create a new directory and cd into it
function mkd
	mkdir -p $argv; and cd $argv
end


function fish_prompt
    echo '> '
end

function fish_right_prompt
    set -l current_k8s_context (kubectl config current-context)
    set -l gcp_project (cat ~/.config/gcloud/active_config)
    #    set -l gcp_project (cat ~/.config/gcloud/configurations/config_(cat ~/.config/gcloud/active_config) | grep project | cut -f 3 -d " ")

    set -x envs
    if contains $current_k8s_context $FISH_PROMPT_K8S_CONTEXT_NAMES
        set envs $envs (printf '⎈ %s' $current_k8s_context)
    end
    if contains $gcp_project $FISH_PROMPT_GCP_CONFIG_NAMES
        set envs $envs (printf 'GCP:%s' $gcp_project)
    end
    if [ (count $envs) -gt 0 ]
        echo '['
        set_color red
        printf '%s' (string join ',' $envs)
        set_color normal
        echo ']'
    end
    __fish_git_prompt
end

Fix not to show error messages when there is no context for kubectl

function fish_prompt
    echo '> '
end

function fish_right_prompt
    set -l current_k8s_context (kubectl config current-context)
    set -l gcp_project (cat ~/.config/gcloud/active_config)
    #    set -l gcp_project (cat ~/.config/gcloud/configurations/config_(cat ~/.config/gcloud/active_config) | grep project | cut -f 3 -d " ")

    set -x envs
    if type -q kubectl
	set -l current_k8s_context (kubectl config current-context 2>/dev/null)
	if contains "$current_k8s_context" $FISH_PROMPT_K8S_CONTEXT_NAMES
            set envs $envs (printf '⎈ %s' $current_k8s_context)
	end
    end
    if contains $gcp_project $FISH_PROMPT_GCP_CONFIG_NAMES
        set envs $envs (printf 'GCP:%s' $gcp_project)
    end
    if [ (count $envs) -gt 0 ]
        echo '['
        set_color red
        printf '%s' (string join ',' $envs)
        set_color normal
        echo ']'
    end
    __fish_git_prompt
end


function workon
    if not set -q argv[1]
        vf ls
    else
        vf activate $argv[1]
    end
end
function deactivate
    vf deactivate
end
function mktmpenv
    vf tmp $argv
end
function mkvirtualenv
    # Check if the first argument is an option to virtualenv
    # if it is then the the last argument must be the DEST_DIR.
    set -l idx 1
    switch $argv[1]
        case '-*'
            set idx -1
    end

    # Extract the DEST_DIR and remove it from $argv
    set -l env_name $argv[$idx]
    set -e argv[$idx]

    vf new $argv $env_name
end
function lsvirtualenv
    vf ls
end
function rmvirtualenv
    vf rm $argv
end
function add2virtualenv
    vf addpath $argv
end
function cdvirtualenv
    vf cd $argv
end
function cdsitepackages
    vf cdpackages $argv
end
function allvirtualenv
    vf all $argv
end
function setvirtualenvproject
    vf connect
end
function toggleglobalsitepackages
    vf globalpackages
end

complete -x -c workon -a "(vf ls)"
complete -x -c rmvirtualenv -a "(vf ls)"

Use same arg parsing for mkvirtualenv as `vf new`

function workon
    if not set -q argv[1]
        vf ls
    else
        vf activate $argv[1]
    end
end
function deactivate
    vf deactivate
end
function mktmpenv
    vf tmp $argv
end
function mkvirtualenv
    vf new $argv
end
function lsvirtualenv
    vf ls
end
function rmvirtualenv
    vf rm $argv
end
function add2virtualenv
    vf addpath $argv
end
function cdvirtualenv
    vf cd $argv
end
function cdsitepackages
    vf cdpackages $argv
end
function allvirtualenv
    vf all $argv
end
function setvirtualenvproject
    vf connect
end
function toggleglobalsitepackages
    vf globalpackages
end

complete -x -c workon -a "(vf ls)"
complete -x -c rmvirtualenv -a "(vf ls)"


set fish_greeting ""

abbr --add g git
abbr --add gc 'git commit'
abbr --add gca 'git commit -a'
abbr --add gd 'git diff'
abbr --add gst 'git status'
abbr --add p 'pass'
abbr --add pc 'pass -c'

setenv SSH_AUTH_SOCK $XDG_RUNTIME_DIR/gnupg/S.gpg-agent.ssh
gpg-connect-agent updatestartuptty /bye > /dev/null

# Start X at login
if status --is-login
    set PATH $PATH /usr/bin /sbin
    if test -z "$DISPLAY" -a $XDG_VTNR = 1
        startx
    end
end

Add zathura abbreviation in fish.

set fish_greeting ""

abbr --add g git
abbr --add gc 'git commit'
abbr --add gca 'git commit -a'
abbr --add gd 'git diff'
abbr --add gst 'git status'
abbr --add p 'pass'
abbr --add pc 'pass -c'
abbr --add z 'zathura --fork'

setenv SSH_AUTH_SOCK $XDG_RUNTIME_DIR/gnupg/S.gpg-agent.ssh
gpg-connect-agent updatestartuptty /bye > /dev/null

# Start X at login
if status --is-login
    set PATH $PATH /usr/bin /sbin
    if test -z "$DISPLAY" -a $XDG_VTNR = 1
        startx
    end
end


function moj_host --description='Prints an emoji for the current host.'

    set -l host (hostname)
    if string match '*.*' $host >/dev/null
        set -l tokens (string split '.' $host)
        set host $tokens[1]
        set domain $tokens[2]
    end

    switch $host
        case greymatter hi-c-era.local
            echo 💻
        case imac rundmg
            echo 🖥
        case mini
            echo ⌨
        case '*'
            echo (string sub --length 1 (hostname))❓
    end
end

Remove .local domain from host case

function moj_host --description='Prints an emoji for the current host.'
    set -l host (hostname)
    if string match '*.*' $host >/dev/null
        set -l tokens (string split '.' $host)
        set host $tokens[1]
        set domain $tokens[2]
    end

    switch $host
        case greymatter hi-c-era
            echo 💻
        case imac rundmg
            echo 🖥
        case mini
            echo ⌨
        case '*'
            echo (string sub --length 1 (hostname))❓
    end
end


function check_vpn --description="Return true if connected to VPN"
  command curl --silent https://am.i.mullvad.net/json | jq '.mullvad_exit_ip'
end

Use pango formatting, add bar mode

function check_vpn --description="Return true if connected to VPN"
  argparse --name check_vpn 'h/help' 'b/barmode' -- $argv
  or return 1  # error

  function print_help
    echo "Usage: check_vpn [options]"
    echo "Options:"
    echo (set_color green)"-b"(set_color $fish_color_normal)": Output text for i3status-rs bar"
  end

  if set -lq _flag_help
    print help
    return
  end

  set MODE std
  if set -lq _flag_barmode
    set MODE bar
  end

  set val (curl --silent https://am.i.mullvad.net/json | jq '.mullvad_exit_ip')
  if test $MODE = bar
    if test $val = true
      printf "VPN"
    else
      printf "VPN"
    end
  else
    if test $val = true
      return 0
    else
      return 1
    end
  end
end


set --global --export SCRIPT_DIR (dirname (dirname (status -f)))
set --global --export SOURCE_DIR (dirname $SCRIPT_DIR)
set --global --export PROFILE (status -f)

set --local os (uname -s)

if not contains $SCRIPT_DIR/fish/functions $fish_function_path
    set fish_function_path $SCRIPT_DIR/fish/functions $fish_function_path
end

for script in (ls -d $SCRIPT_DIR/fish/init/*)
    . $script
end

Simplify the startup script even more

set --global --export PROFILE (status -f)
set --global --export SCRIPT_DIR (dirname (dirname $PROFILE))
set --global --export SOURCE_DIR (dirname $SCRIPT_DIR)

if not contains $SCRIPT_DIR/fish/functions $fish_function_path
    set fish_function_path $SCRIPT_DIR/fish/functions $fish_function_path
end

for script in (ls -d $SCRIPT_DIR/fish/init/*)
    . $script
end