eval "$(dircolors -b ~/.dircolors)"

autoload -Uz compinit
compinit
zmodload -a complist
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}' 'r:|[._-]=* r:|=*' 'l:|=* r:|=*'
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
zstyle ':completion:*' use-compctl false
zstyle ':completion:*' use-cache on
zstyle ':completion:*' cache-path ~/.zshcache
__git_files () {
	_wanted files expl 'local files' _files
}
zstyle :compinstall filename "$HOME/.zshrc"
source $HOME/.zsh_autosuggestions.zsh

HISTFILE=~/.histfile
HISTSIZE=10000
SAVEHIST=10000

setopt no_beep
setopt extendedglob
setopt prompt_subst
setopt complete_in_word
setopt no_auto_menu
setopt no_always_last_prompt
setopt share_history
setopt hist_ignore_all_dups
setopt hist_ignore_space
setopt extended_history
setopt promptsubst
setopt autopushd
setopt pushdignoredups
setopt nomatch

autoload -U edit-command-line
zle -N edit-command-line
bindkey -e
bindkey '^[[3~' delete-char
bindkey '^[[1;5C' forward-word
bindkey '^[[1;5D' backward-word
bindkey '\C-v' edit-command-line
bindkey '\Ea' push-line
local WORDCHARS=${WORDCHARS//\//}\| # remove forward slash, add pipe

autoload -U url-quote-magic
zle -N self-insert url-quote-magic

source $HOME/.zsh_fast_syntax_highlighting/fast-syntax-highlighting.plugin.zsh

if builtin which bat > /dev/null; then
	export MANPAGER='sh -c "col -bx | bat --language man --paging always --style plain"'
	export MANROFFOPT='-c'
elif builtin which nvim > /dev/null; then
	export MANPAGER='vim +Man!'
else
	export MANPAGER='vim -M +MANPAGER -'
fi
export GREP_COLORS='ms=01;36:mc=01;31:sl=:cx=:fn=35:ln=33:bn=33:se=01;34'

for coreutil in `find /usr/bin -maxdepth 1 -name 'uu_*'`; do
	[[ ${coreutil#/usr/bin/} = 'uu_[' ]] && continue
	alias ${coreutil#/usr/bin/uu_}=${coreutil#/usr/bin/}
done
if [ -x ~/bin/eza ]; then
	export EZA_COLORS=bu=0:cr=0
	alias ls='eza --group-directories-first --mounts --group --hyperlink --icons=auto'
else
	alias ls='ls --color=auto -hv --group-directories-first'
fi
if [ $TERM = xterm-kitty ]; then
	alias ssh='kitten ssh'
fi
alias ll='ls -l'
alias l.='ls -Ad .*'
alias la='ls -A'
alias llr='lr -1AGl -ov'
alias grep='grep --color -s'
alias df='df -hx tmpfs'
alias du='du --max-depth=1'
alias sr='screen -r'
alias gil='git log --graph --abbrev-commit --stat --summary -C --decorate --date=local'
alias gime='git short --author raylu'
alias giw='git show -C --date=local --decorate'
alias gip='git pull --ff-only'
alias gib='git branch'
alias gis='git status'
alias gid='git diff -C --date=local'
alias gic='git checkout'
alias giu='git reset HEAD\^'
alias hgw='hg diff --change .'
alias class='xprop -notype WM_CLASS'
alias fx='FX_NO_MOUSE=1 FX_COLLAPSED=1 FX_SHOW_SIZE=1 fx'
alias tree='tree -AvL 10'
alias vi='nvim -p'
alias vil='vi *(.om[1])'
alias sudovi="sudo vi -N -u $HOME/.vimrc"
alias shrug="echo -n '¯\\(°_o)/¯' | xclip -selection clipboard"
function https() {
	openssl s_client -connect $1:443 -servername $1 < /dev/null | \
	openssl x509 -noout -text -certopt no_header,no_version,no_serial,no_signame,no_pubkey,no_sigdump
}
function cl() {
	if [ $# = 0 ]; then
		cd && ls
	else
		cd "$*" && ls
	fi
}
function pdf() {
	atril "$*" &> /dev/null &!
}

if [ -d /usr/lib/cargo/bin ]; then
	PATH=/usr/lib/cargo/bin:$PATH
	if [ -d /usr/lib/cargo/bin/coreutils ]; then
		PATH=/usr/lib/cargo/bin/coreutils:$PATH
	fi
fi

if [ -d $HOME/.cargo/bin ]; then
	PATH=$HOME/.cargo/bin:$PATH
fi
export BUN_INSTALL=$HOME/.bun
if [ -d $BUN_INSTALL ]; then
	source $BUN_INSTALL/_bun
	PATH="$BUN_INSTALL/bin:$PATH"
fi
if [ -d $HOME/bin ]; then
	PATH=$HOME/bin:$PATH
fi
if builtin which nvim > /dev/null; then
	export EDITOR=nvim
else
	export EDITOR=vi
fi

if builtin which oh-my-posh > /dev/null; then
	eval "$(oh-my-posh init zsh -c ~/.config/oh-my-posh.toml)"
elif builtin which starship > /dev/null; then
	eval "$(starship init zsh)"
else
	autoload colors
	colors
	bright_cyan='%{[96m%}' # not provided by colors
	autoload -Uz vcs_info
	zstyle ':vcs_info:*' unstagedstr "%{$fg[red]%}*"
	zstyle ':vcs_info:*' stagedstr "%{$fg[red]%}+"
	zstyle ':vcs_info:*' formats "$bright_cyan%b%u%c"
	zstyle ':vcs_info:*' actionformats "$bright_cyan%b%u%c|%a"
	zstyle ':vcs_info:git:*' check-for-changes true
	zstyle ':vcs_info:(sv[nk]|bzr):*' branchformat '%b:%r'
	zstyle ':vcs_info:bzr:*' use-simple true
	zstyle ':vcs_info:*' enable git hg bzr svn cvs
	precmd () { vcs_info }
	PROMPT="%{$fg_bold[grey]%}%* " # time
	PROMPT+="%{${fg_bold[green]}%}%m%{${reset_color}%}:" # host
	PROMPT+="%{${fg_bold[blue]}%}%50<...<%~%<<%{${reset_color}%} " # path
	PROMPT+='${vcs_info_msg_0_} '
	PROMPT+="%(?..%{$fg_bold[red]%}%? %{$reset_color%})" # exit status
	PROMPT+="%1(j.%{$fg[green]%}%j .)" # suspended jobs
	PROMPT+=$'%{$reset_color%} \n%(!.#.\$) '
fi

if builtin which jj > /dev/null; then
	source <(COMPLETE=zsh jj)
fi
if builtin which procs > /dev/null; then
	source <(procs --gen-completion-out zsh)
fi

if builtin which aws_completer > /dev/null; then
	autoload bashcompinit && bashcompinit
	complete -C aws_completer aws
fi

if builtin which fzf > /dev/null; then
	FZF_DEFAULT_OPTS='--no-mouse'
	source "/usr/share/fzf/shell/key-bindings.zsh"

	__fzf_git_commit_sha() {
		setopt localoptions pipefail no_aliases 2> /dev/null
		if jj root &> /dev/null; then
			jj --ignore-working-copy --color=always log --no-graph \
				-T 'if(root, format_root_commit(self), label(
						if(current_working_copy, "working_copy"),
						format_short_commit_header(self) ++ "\n" ++ if(description, description.first_line(),
							label(if(empty, "empty"), description_placeholder)
						)
					)) ++ "\x00"' |
				$(__fzfcmd) --read0 --ansi --no-sort --reverse --highlight-line \
					--height ${FZF_TMUX_HEIGHT:-40%} --accept-nth 1 \
					--preview='jj --ignore-working-copy --color=always show --stat {1}'
		else
			git log --color=always -n 50 --format='%C(auto)%h%d %s %C(black)%C(bold)%cr' |
				FZF_DEFAULT_OPTS="--ansi --no-sort --tiebreak=index --reverse \
					--preview 'git show --color=always {1}' ${FZF_DEFAULT_OPTS-}" $(__fzfcmd) -m "$@" |
				sed -r -e 's/([0-9a-f]+) .+/\1/' -e 's/.+ ([0-9a-f]+)/\1/'
		fi
	}
	fzf-git-commit-sha-widget() {
		LBUFFER="${LBUFFER}$(__fzf_git_commit_sha)"
		local ret=$?
		zle reset-prompt
		return $ret
	}
	zle -N fzf-git-commit-sha-widget
	bindkey '^G' fzf-git-commit-sha-widget

	__fzf_git_branch() {
		setopt localoptions pipefail no_aliases 2> /dev/null
		git branch --all --color=always \
			--format='%(if)%(HEAD)%(then)%(color:bold green)%(else)%(if:equals=refs/remotes)%(refname:rstrip=-2)%(then)%(color:red)%(end)%(end)%(refname:short)' |
			FZF_DEFAULT_OPTS="--ansi --no-sort --tiebreak=index --reverse ${FZF_DEFAULT_OPTS-}" \
				$(__fzfcmd) \
				--preview 'git log --color=always --abbrev-commit --stat --summary -C --decorate --date=local {1} --max-count=20' \
				--height ${FZF_TMUX_HEIGHT:-40%} "$@"
	}
	fzf-git-branch-widget() {
		LBUFFER="${LBUFFER}$(__fzf_git_branch)"
		local ret=$?
		zle reset-prompt
		return $ret
	}
	zle -N fzf-git-branch-widget
	bindkey '^H' fzf-git-branch-widget

	__fzf_pid() {
		setopt localoptions pipefail no_aliases 2> /dev/null
		ps axo pid,start,user,command |
			FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-40%} --reverse ${FZF_DEFAULT_OPTS-}" $(__fzfcmd) -m "$@" |
			awk '{print $1}'
	}
	fzf-pid-widget() {
		LBUFFER="${LBUFFER}$(__fzf_pid)"
		local ret=$?
		zle reset-prompt
		return $ret
	}
	zle -N fzf-pid-widget
	bindkey '^O' fzf-pid-widget

	__fzf_rg() {
		setopt localoptions pipefail no_aliases 2> /dev/null
		RELOAD='reload:rg --column --color=always --smart-case {q} || :'
		$(__fzfcmd) --disabled --ansi --multi \
				--bind "start:$RELOAD" --bind "change:$RELOAD" \
				--bind 'alt-a:select-all,alt-d:deselect-all,ctrl-/:toggle-preview' \
				--delimiter : \
				--preview 'bat --style=full --color=always --highlight-line {2} {1}' \
				--preview-window '~4,+{2}+4/3,<80(up)' \
				--query "$*" |
			cut -d: -f1
	}
	fzf-rg-widget() {
		LBUFFER="${LBUFFER}$(__fzf_rg)"
		local ret=$?
		zle reset-prompt
		return $ret
	}
	zle -N fzf-rg-widget
	bindkey '^S' fzf-rg-widget
fi

stty stop undef
