# ZSH Config File

# Enable colors and set prompt
autoload -U colors && colors
setopt prompt_subst

function git_prompt_info() {
    local STATUS
    # Use the dotfiles git repo if in the home directory
    if [[ "$PWD" = "$HOME" ]]; then
        STATUS=$(git --git-dir "$HOME/.config/dotfiles/.git" --work-tree "$HOME" status --porcelain | tail -1)
    else
        if ! git rev-parse --git-dir &> /dev/null; then
            return 0
        fi
        STATUS=$(git status --porcelain | tail -1)
    fi

    if [[ -n $STATUS ]]; then
        echo "%{$fg[yellow]%} %{$fg[reset_color]%}"
    fi
}

function git_current_branch {
    # No need to show the branch for the home directory
    local ref
    ref=$(git symbolic-ref --quiet HEAD 2> /dev/null)
    local ret=$?
    if [[ $ret != 0  ]]; then
        [[ $ret == 128 ]] && return # no git repo
        ref=$(git rev-parse --short HEAD 2> /dev/null) || return
    fi
    echo ${ref#refs/heads/}
}

# %B (%b) for bold | %c shows the top directory
PS1='%B%(?:%F{green} :%F{red} )%F{magenta}%c $(git_prompt_info)%f%b '
RPS1='%{$fg[blue]%}$(git_current_branch)%f'

setopt autocd # Automatically cd into typed directory.
stty stop undef # Disable ctrl-s to freeze terminal.
setopt interactive_comments

# History in cache directory:
HISTSIZE=10000000
SAVEHIST=10000000
HISTFILE="${XDG_CACHE_HOME:-$HOME/.cache}/zsh/history"
[ ! -f $HISTFILE ] && mkdir "${XDG_CACHE_HOME:-$HOME/.cache}/zsh"; touch "$HISTFILE"
setopt share_history # Share histories between open sessions
setopt append_history # Append to history file instead of overriding
setopt inc_append_history # Append to history file as you go
setopt hist_ignore_dups # Ignore duplicates directly after each other
setopt hist_find_no_dups # Ignore duplicates when navigating up through history
setopt hist_no_store # Don't store `history` command
setopt hist_ignore_space # Allow using a space to not add the line to the history

# Load aliases and shortcuts if existent.
[ -f "${XDG_CONFIG_HOME:-$HOME/.config}/shell/shortcutrc" ] && source "${XDG_CONFIG_HOME:-$HOME/.config}/shell/shortcutrc"
[ -f "${XDG_CONFIG_HOME:-$HOME/.config}/shell/aliasrc" ] && source "${XDG_CONFIG_HOME:-$HOME/.config}/shell/aliasrc"
[ -f "${XDG_CONFIG_HOME:-$HOME/.config}/shell/zshnameddirrc" ] && source "${XDG_CONFIG_HOME:-$HOME/.config}/shell/zshnameddirrc"

# Load nvm if it is installed
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm

# Basic auto/tab complete:
autoload -U compinit
zstyle ':completion:*' menu select
zmodload zsh/complist
compinit
_comp_options+=(globdots) # Include hidden files.

# vi mode
bindkey -v
export KEYTIMEOUT=1

# Use vim keys in tab complete menu:
bindkey -M menuselect 'h' vi-backward-char
bindkey -M menuselect 'k' vi-up-line-or-history
bindkey -M menuselect 'l' vi-forward-char
bindkey -M menuselect 'j' vi-down-line-or-history
bindkey -v '^?' backward-delete-char

# Change cursor shape for different vi modes.
function zle-keymap-select() {
    case $KEYMAP in
        vicmd) echo -ne '\e[1 q';; # block
        viins|main) echo -ne '\e[5 q';; # beam
    esac
}
zle -N zle-keymap-select
zle-line-init() {
    zle -K viins # initiate `vi insert` as keymap (can be removed if `bindkey -V` has been set elsewhere)
    echo -ne "\e[5 q"
}
zle -N zle-line-init
echo -ne '\e[5 q' # Use beam shape cursor on startup.
preexec() {
    echo -ne '\e[5 q'
}

# function disable_alias_check() {
#   export DISABLE_ALIAS_CHECK=1
#   echo "Alias check disabled."
# }
#
# function enable_alias_check() {
#   unset DISABLE_ALIAS_CHECK
#   echo "Alias check enabled."
# }
#
# function alias_suggestion_check() {
#     if [[ $DISABLE_ALIAS_CHECK = 1 ]] {
#         return
#     }
#     local current_cmd="$1"
#
#     if [[ -z "$current_cmd" || ${#current_cmd} -lt 7 ]]; then
#         return
#     fi
#
#     local recent_count="$(history 500 | grep -c -E "^[0-9 ]+${current_cmd}")"
#     if [[ $recent_count -ge 3 ]]; then
#         echo "\033[33m[ALIAS SUGGESTION]: You've run '$current_cmd' multiple times. Consider making an alias!\033[0m"
#     fi
# }
# preexec_functions+=(alias_suggestion_check)
#
# function remind_alias_if_exists() {
#     if [[ $DISABLE_ALIAS_CHECK = 1 ]] {
#         return
#     }
#     local current_cmd="$1"
#
#     if [[ -z "$current_cmd" || ${#current_cmd} -lt 7 ]]; then
#         return
#     fi
#
#     local matched_alias=""
#     for alias_name expansion in ${(kv)aliases}; do
#         if [[ ${#alias_name} -gt ${#expansion} ]]; then
#             continue
#         fi
#         if [[ "$current_cmd" == "$expansion" ]]; then
#             echo
#             echo -e "\033[33m[ALIAS REMINDER]: You just ran '$current_cmd', which has an alias '$alias_name'.\033[0m"
#             echo -e "\033[33mTry using: $alias_name\033[0m"
#             echo
#             return
#         fi
#         if [[ "$current_cmd" == "$expansion"* ]] && [[ ${#expansion} > ${#matched_alias} ]]; then
#             matched_alias="$alias_name"
#         fi
#     done
#     if [[ -n $matched_alias ]]; then
#         local expansion="${aliases[$matched_alias]}"
#         echo
#         echo -e "\033[33m[ALIAS REMINDER]: You just ran '$current_cmd', which matched an existing alias $matched_alias='$expansion'.\033[0m"
#         echo -e "\033[33mTry using: $matched_alias${current_cmd#$expansion}\033[0m"
#         echo
#     fi
# }
# preexec_functions+=(remind_alias_if_exists)


bindkey -s '^a' 'bc -lq\n'

bindkey -s '^f' 'cd "$(dirname "$(fzf)")"\n'

bindkey '^[[P' delete-char

bindkey '^[[A' history-search-backward
bindkey '^[[B' history-search-forward

# setxkbmap gb

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

set -o ignoreeof # Stop CTRL-D from quitting

# Load syntax highlighting; should be last.
source /usr/share/zsh/plugins/fast-syntax-highlighting/fast-syntax-highlighting.plugin.zsh 2>/dev/null

eval "$(zoxide init --cmd cd zsh)"

eval "$(try init ~/src/tries)"

eval "$(direnv hook zsh)"

[ -f ~/.cache/wal/sequences ] && \cat ~/.cache/wal/sequences

[ -f ~/.cache/wal/colors-tty.sh ] && source ~/.cache/wal/colors-tty.sh
