#!/bin/sh
# vim: ft=sh:fdl=0:
# ┌─────────────┐
# │ git         │
# └─────────────┘
# # {{{jj-git finder w fzf
# jj() {
#   cd "${1:-.}/$(find . -maxdepth 5 -type d -name .git | sed 's|/.git$||' | fzf --preview 'tree -L 2 ./{}')" || return 1
# }
# # }}}
# # {{{prepo-grepo-gclone-gsearch
# prepo() {
#   if [ "$#" -ne 0 ]; then
#       url="https://github.com/${(j:/:)@}"
#   else
#       url=$(git remote get-url origin) || return $?
#       [[ "$url" =~ '^git@' ]] && url=$(echo "$url" | sed -e 's#:#/#' -e 's#git@#https://#')
#   fi
#   echo "$url"
# }
#
# grepo() { xdg-open "$(prepo $@)" }
#
# gclone() { git clone "https://github.com/${(j:/:)@}" }
#
# gsearch() {
#   header='["Repostory", "Stars", "Description"]'
#   list="$(curl -fsSL "https://api.github.com/search/repositories?q=$1" |
#       command jq -r "$header, (.items[] | [.full_name, .stargazers_count, .description]) | @tsv" |
#       column -t -s $'\t')"
#   repos=("${(@f)$(echo "$list" | fzf -m -0 -1 --header-lines=1 | awk '{print $1}')}")
#   for repo in ${repos}; do
#       xdg-open "https://github.com/${repo}"
#   done
# }
#
# # }}}
# # {{{fgf
# fgf() {
# 	readonly prompt_add="Add > "
# 	readonly prompt_reset="Reset > "
#
# 	readonly git_root_dir=$(git rev-parse --show-toplevel)
# 	readonly git_unstaged_files="git ls-files --modified --deleted --other --exclude-standard --deduplicate $git_root_dir"
#
# 	local git_staged_files='git status --short | grep "^[A-Z]" | awk "{print \$NF}"'
#
# 	readonly git_reset="git reset -- {+}"
# 	readonly enter_cmd="($git_unstaged_files | grep {} && git add {+}) || $git_reset"
#
# 	readonly preview_status_label="[ Status ]"
# 	readonly preview_status="git status --short"
#
# 	readonly header=$(cat <<-EOF
# 		> CTRL-S to switch between Add Mode and Reset mode
# 		> CTRL_T for status preview | CTRL-F for diff preview | CTRL-B for blame preview
# 		> ALT-E to open files in your editor
# 		> ALT-C to commit | ALT-A to append to the last commit
# 		EOF
# 	)
#
# 	readonly add_header=$(cat <<-EOF
# 		$header
# 		> ENTER to add files
# 		> ALT-P to add patch
# 	EOF
# 	)
#
# 	readonly reset_header=$(cat <<-EOF
# 		$header
# 		> ENTER to reset files
# 		> ALT-D to reset and checkout files
# 	EOF
# 	)
#
# 	readonly mode_reset="change-prompt($prompt_reset)+reload($git_staged_files)+change-header($reset_header)+unbind(alt-p)+rebind(alt-d)"
# 	readonly mode_add="change-prompt($prompt_add)+reload($git_unstaged_files)+change-header($add_header)+rebind(alt-p)+unbind(alt-d)"
#
# 	eval "$git_unstaged_files" | fzf \
# 	--multi \
# 	--reverse \
# 	--no-sort \
# 	--prompt="Add > " \
# 	--preview-label="$preview_status_label" \
# 	--preview="$preview_status" \
# 	--header "$add_header" \
# 	--header-first \
# 	--bind='start:unbind(alt-d)' \
# 	--bind="ctrl-t:change-preview-label($preview_status_label)" \
# 	--bind="ctrl-t:+change-preview($preview_status)" \
# 	--bind='ctrl-f:change-preview-label([ Diff ])' \
# 	--bind='ctrl-f:+change-preview(git diff --color=always {} | sed "1,4d")' \
# 	--bind='ctrl-b:change-preview-label([ Blame ])' \
# 	--bind='ctrl-b:+change-preview(git blame --color-by-age {})' \
# 	--bind="ctrl-s:transform:[[ \$FZF_PROMPT =~ '$prompt_add' ]] && echo '$mode_reset' || echo '$mode_add'" \
# 	--bind="enter:execute($enter_cmd)" \
# 	--bind="enter:+reload([[ \$FZF_PROMPT =~ '$prompt_add' ]] && $git_unstaged_files || $git_staged_files)" \
# 	--bind="enter:+refresh-preview" \
# 	--bind='alt-p:execute(git add --patch {+})' \
# 	--bind="alt-p:+reload($git_unstaged_files)" \
# 	--bind="alt-d:execute($git_reset && git checkout {+})" \
# 	--bind="alt-d:+reload($git_staged_files)" \
# 	--bind='alt-c:execute(git commit)+abort' \
# 	--bind='alt-a:execute(git commit --amend)+abort' \
# 	--bind='alt-e:execute(${EDITOR:-vim} {+})' \
# 	--bind='f1:toggle-header' \
# 	--bind='f2:toggle-preview' \
# 	--bind='ctrl-y:preview-up' \
# 	--bind='ctrl-e:preview-down' \
# 	--bind='ctrl-u:preview-half-page-up' \
# 	--bind='ctrl-d:preview-half-page-down'
# }
# #function fgf() {
# #	readonly prompt_add="Add > "
# #	readonly prompt_reset="Reset > "
# #
# #	readonly git_root_dir=$(git rev-parse --show-toplevel)
# #	readonly git_unstaged_files="git ls-files --modified --deleted --other --exclude-standard --deduplicate $git_root_dir"
# #
# #	local git_staged_files='git status --short | grep "^[A-Z]" | awk "{print \$NF}"'
# #
# #	readonly git_reset="git reset -- {+}"
# #	readonly enter_cmd="($git_unstaged_files | grep {} && git add {+}) || $git_reset"
# #
# #	readonly preview_status_label="[ Status ]"
# #	readonly preview_status="git status --short"
# #
# #	readonly header=$(cat <<-EOF
# #		> CTRL-S to switch between Add Mode and Reset mode
# #		> CTRL-T for status preview | CTRL-F for diff preview | CTRL-B for blame preview
# #		> CTRL-O to open files in your editor
# #		> CTRL-X to commit | CTRL-A to append to the last commit
# #		EOF
# #	)
# #
# #	readonly add_header=$(cat <<-EOF
# #		$header
# #		> ENTER to add files
# #		> CTRL-P to add patch
# #	EOF
# #	)
# #
# #	readonly reset_header=$(cat <<-EOF
# #		$header
# #		> ENTER to reset files
# #		> CTRL-R to reset and checkout files
# #	EOF
# #	)
# #
# #	readonly mode_reset="change-prompt($prompt_reset)+reload($git_staged_files)+change-header($reset_header)+unbind(ctrl-p)+rebind(ctrl-r)"
# #	readonly mode_add="change-prompt($prompt_add)+reload($git_unstaged_files)+change-header($add_header)+rebind(ctrl-p)+unbind(ctrl-r)"
# #
# #	eval "$git_unstaged_files" | fzf \
# #	--multi \
# #	--reverse \
# #	--no-sort \
# #	--prompt="Add > " \
# #	--preview-label="$preview_status_label" \
# #	--preview="$preview_status" \
# #	--header "$add_header" \
# #	--header-first \
# #	--bind='start:unbind(ctrl-r)' \
# #	--bind="ctrl-t:change-preview-label($preview_status_label)" \
# #	--bind="ctrl-t:+change-preview($preview_status)" \
# #	--bind='ctrl-f:change-preview-label([ Diff ])' \
# #	--bind='ctrl-f:+change-preview(git diff --color=always {} | sed "1,4d")' \
# #	--bind='ctrl-b:change-preview-label([ Blame ])' \
# #	--bind='ctrl-b:+change-preview(git blame --color-by-age {})' \
# #	--bind="ctrl-s:transform:[[ \$FZF_PROMPT =~ '$prompt_add' ]] && echo '$mode_reset' || echo '$mode_add'" \
# #	--bind="enter:execute($enter_cmd)" \
# #	--bind="enter:+reload([[ \$FZF_PROMPT =~ '$prompt_add' ]] && $git_unstaged_files || $git_staged_files)" \
# #	--bind="enter:+refresh-preview" \
# #	--bind='ctrl-p:execute(git add --patch {+})' \
# #	--bind="ctrl-p:+reload($git_unstaged_files)" \
# #	--bind="ctrl-r:execute($git_reset && git checkout {+})" \
# #	--bind="ctrl-r:+reload($git_staged_files)" \
# #	--bind='ctrl-c:execute(git commit)+abort' \
# #	--bind='ctrl-a:execute(git commit --amend)+abort' \
# #	--bind='ctrl-o:execute(${EDITOR:-vim} {+})' \
# #	--bind='f1:toggle-header' \
# #	--bind='f2:toggle-preview' \
# #	--bind='ctrl-y:preview-up' \
# #	--bind='ctrl-e:preview-down' \
# #	--bind='ctrl-u:preview-half-page-up' \
# #	--bind='ctrl-d:preview-half-page-down'
# #}
# # }}}
# {{{fgc
fgc() {
  readonly git_log=$(cat <<-EOF
git log --graph --color --format="%C(white)%h - %C(green)%cs - %C(blue)%s%C(red)%d"
EOF
  )
  readonly git_log_all=$(cat <<-EOF
git log --all --graph --color --format="%C(white)%h - %C(green)%cs - %C(blue)%s%C(red)%d"
EOF
  )

  read -r -d '' get_hash <<-'EOF'
echo {} | grep -o "[a-f0-9]\{7\}" | sed -n "1p"
EOF

  readonly git_show="[ \$(${get_hash}) != '' ] && git show --color \$(${get_hash})"
  readonly git_show_subshell=$(cat <<-EOF
[ \$(${get_hash}) != '' ] && sh -c "git show --color \$(${get_hash}) | less -R"
EOF
  )

  readonly git_checkout="[ \$(${get_hash}) != '' ] && git checkout \$(${get_hash})"
  readonly git_reset="[ \$(${get_hash}) != '' ] && git reset \$(${get_hash})"
  readonly git_rebase_interactive="[ \$(${get_hash}) != '' ] && git rebase --interactive \$(${get_hash})"
  readonly git_cherry_pick="[ \$(${get_hash}) != '' ] && git cherry-pick \$(${get_hash})"

  readonly header=$(cat <<-EOF
> ENTER to display the diff with less
EOF
  )

  readonly header_branch=$(cat <<-EOF
${header}
> CTRL-S to switch to All Commits mode
> ALT-C to checkout the commit | ALT-R to reset to the commit
> ALT-I to rebase interactively until the commit
EOF
  )

  readonly header_all=$(cat <<-EOF
${header}
> CTRL-S to switch to Branch Commits mode
> ALT-P to cherry pick
EOF
  )

  readonly reset_header=$(cat <<-EOF
${header}
> ENTER to reset files
> ALT-D to reset and checkout files
EOF
  )

  readonly branch_prompt='Branch > '
  readonly all_prompt='All > '

  readonly mode_all="change-prompt(${all_prompt})+reload(${git_log_all})+change-header(${header_all})+unbind(alt-c)+unbind(alt-r)+unbind(alt-i)+rebind(alt-p)"
  readonly mode_branch="change-prompt(${branch_prompt})+reload(${git_log})+change-header(${header_branch})+rebind(alt-c)+rebind(alt-r)+rebind(alt-i)+unbind(alt-p)"

  eval "${git_log}" | fzf \
    --ansi \
    --reverse \
    --no-sort \
    --prompt="${branch_prompt}" \
    --header-first \
    --header="${header_branch}" \
    --preview="${git_show}" \
    --bind='start:unbind(alt-p)' \
    --bind="ctrl-s:transform:[[ \$FZF_PROMPT =~ '${branch_prompt}' ]] && echo '${mode_all}' || echo '${mode_branch}'" \
    --bind="enter:execute(${git_show_subshell})" \
    --bind="alt-c:execute(${git_checkout})+abort" \
    --bind="alt-r:execute(${git_reset})+abort" \
    --bind="alt-i:execute(${git_rebase_interactive})+abort" \
    --bind="alt-p:execute(${git_cherry_pick})+abort" \
    --bind='f1:toggle-header' \
    --bind='f2:toggle-preview' \
    --bind='ctrl-y:preview-up' \
    --bind='ctrl-e:preview-down' \
    --bind='ctrl-u:preview-half-page-up' \
    --bind='ctrl-d:preview-half-page-down'
}

#function fgc() {
#	readonly git_log=$(cat <<-EOF
#		git log --graph --color --format="%C(white)%h - %C(green)%cs - %C(blue)%s%C(red)%d"
#	EOF
#	)
#
#	readonly git_log_all=$(cat <<-EOF
#		git log --all --graph --color --format="%C(white)%h - %C(green)%cs - %C(blue)%s%C(red)%d"
#	EOF
#	)
#
#
#	local get_hash
#	read -r -d '' get_hash <<-'EOF'
#		echo {} | grep -o "[a-f0-9]\{7\}" | sed -n "1p"
#	EOF
#
#	readonly git_show="[[ \$($get_hash) != '' ]] && git show --color \$($get_hash)"
#	readonly git_show_subshell=$(cat <<-EOF
#		[[ \$($get_hash) != '' ]] && sh -c "git show --color \$($get_hash) | less -R"
#	EOF
#	)
#
#	readonly git_checkout="[[ \$($get_hash) != '' ]] && git checkout \$($get_hash)"
#	readonly git_reset="[[ \$($get_hash) != '' ]] && git reset \$($get_hash)"
#	readonly git_rebase_interactive="[[ \$($get_hash) != '' ]] && git rebase --interactive \$($get_hash)"
#	readonly git_cherry_pick="[[ \$($get_hash) != '' ]] && git cherry-pick \$($get_hash)"
#
#	readonly header=$(cat <<-EOF
#		> ENTER to display the diff with less
#	EOF
#	)
#
#	readonly header_branch=$(cat <<-EOF
#		$header
#		> CTRL-S to switch to All Commits mode
#		> CTRL-X to checkout the commit | CTRL-R to reset to the commit
#		> CTRL-I to rebase interactively until the commit
#	EOF
#	)
#
#	readonly header_all=$(cat <<-EOF
#		$header
#		> CTRL-S to switch to Branch Commits mode
#		> CTRL-P to cherry pick
#	EOF
#	)
#
#	readonly reset_header=$(cat <<-EOF
#		$header
#		> ENTER to reset files
#		> CTRL-F to reset and checkout files
#	EOF
#	)
#
#	readonly branch_prompt='Branch > '
#	readonly all_prompt='All > '
#
#	readonly mode_all="change-prompt($all_prompt)+reload($git_log_all)+change-header($header_all)+unbind(ctrl-x)+unbind(ctrl-r)+unbind(ctrl-i)+rebind(alt-p)"
#	readonly mode_branch="change-prompt($branch_prompt)+reload($git_log)+change-header($header_branch)+rebind(ctrl-x)+rebind(ctrl-r)+rebind(ctrl-i)+unbind(alt-p)"
#
#	eval "$git_log" | fzf \
#		--ansi \
#		--reverse \
#		--no-sort \
#		--prompt="$branch_prompt" \
#		--header-first \
#		--header="$header_branch" \
#		--preview="$git_show" \
#		--bind='start:unbind(ctrl-p)' \
#		--bind="ctrl-s:transform:[[ \$FZF_PROMPT =~ '$branch_prompt' ]] && echo '$mode_all' || echo '$mode_branch'" \
#		--bind="enter:execute($git_show_subshell)" \
#		--bind="ctrl-x:execute($git_checkout)+abort" \
#		--bind="ctrl-r:execute($git_reset)+abort" \
#		--bind="ctrl-i:execute($git_rebase_interactive)+abort" \
#		--bind="ctrl-p:execute($git_cherry_pick)+abort" \
#		--bind='f1:toggle-header' \
#		--bind='f2:toggle-preview' \
#		--bind='ctrl-y:preview-up' \
#		--bind='ctrl-e:preview-down' \
#		--bind='ctrl-u:preview-half-page-up' \
#		--bind='ctrl-d:preview-half-page-down'
#}
# }}}

fgco() {
  # shellcheck disable=SC2046,SC2312
  branches=$(git --no-pager branch -vv) && branch=$(echo "${branches}" | fzf --multi) \
    && git checkout $(echo "${branch}" | awk '{ print $1 }' | sed 's/.* //')
}

# {{{fgb.git-branches

fgb() {
  readonly git_branches="git branch --all --color --format=$'%(HEAD) %(color:yellow)%(refname:short)\t%(color:green)%(committerdate:short)\t%(color:blue)%(subject)' | column --table --separator=$'\t'"
  readonly get_selected_branch="echo {} | sed 's/^[* ]*//' | awk '{ print \$1 }'"
  readonly git_log="git log \$(${get_selected_branch}) --graph --color --format='%C(white)%h - %C(green)%cs - %C(blue)%s%C(red)%d'"
  # readonly git_diff="git diff --color $(git branch --show-current)..$(echo {} | sed 's/^[* ]*//' | awk '{ print \$1 }')"
  git_show_subshell=$(cat <<-EOF
[ \$(${get_selected_branch}) != '' ] && sh -c "git show --color \$(${get_selected_branch}) | less -R"
EOF
  )
  header=$(cat <<-EOF
> ALT-M to merge with current * branch | ALT-R to rebase with current * branch
> ALT-C to checkout the branch
> ALT-D to delete the merged local branch | ALT-X to force delete the local branch
> ENTER to open the diff with less
EOF
  )

  # shellcheck disable=SC2312
  eval "${git_branches}" | fzf \
    --ansi \
    --reverse \
    --no-sort \
    --preview-label '[ Commits ]' \
    --preview="${git_log}" \
    --header-first \
    --header="${header}" \
    --bind="alt-c:execute(git checkout \$(${get_selected_branch}))" \
    --bind="alt-c:+reload(${git_branches})" \
    --bind="alt-m:execute(git merge \$(${get_selected_branch}))" \
    --bind="alt-r:execute(git rebase \$(${get_selected_branch}))" \
    --bind="alt-d:execute(git branch --delete \$(${get_selected_branch}))" \
    --bind="alt-d:+reload(${git_branches})" \
    --bind="alt-x:execute(git branch --delete --force \$(${get_selected_branch}))" \
    --bind="alt-x:+reload(${git_branches})" \
    --bind="enter:execute(${git_show_subshell})" \
    --bind='ctrl-f:change-preview-label([ Diff ])' \
    --bind="ctrl-f:+change-preview(git diff --color $(git branch --show-current)..$(echo {} | sed 's/^[* ]*//' | awk '{ print \$1 }'))" \
    --bind='ctrl-i:change-preview-label([ Commits ])' \
    --bind="ctrl-i:+change-preview(${git_log})" \
    --bind='f1:toggle-header' \
    --bind='f2:toggle-preview' \
    --bind='ctrl-y:preview-up' \
    --bind='ctrl-e:preview-down' \
    --bind='ctrl-u:preview-half-page-up' \
    --bind='ctrl-d:preview-half-page-down'
}

# }}}

# {{{fgl.git-log-browser
fgl() {
  git log --graph --color=always \
      --format="%C(auto)%h%d %s %C(black)%C(bold)%cr" "$@" |
  fzf --ansi --no-sort --reverse --tiebreak=index --bind=ctrl-s:toggle-sort \
      --bind "ctrl-m:execute:
                (grep -o '[a-f0-9]\{7\}' | head -1 |
                xargs -I % sh -c 'git show --color=always % | less -R') << 'FZF-EOF'
                {}
FZF-EOF"
}
# }}}
# ┌─────────────┐
# │ apt         │
# └─────────────┘
# {{{fapt

if [[ $OSTYPE == linux* ]]; then
fapt() {
if [ "$#" -lt 1 ]; then
    default_command="show"
fi
case "$1" in
install | reinstall | remove | purge)
    sudo="sudo "
    ;;
esac
apt-cache search "" | fzf --multi --prompt "${sudo}apt $default_command$@ " --reverse --height 40 |
    cut -f 1 -d " " | xargs --no-run-if-empty ${sudo}apt $default_command "$@"
}
# }}}
# {{{fapti.apt-install
fapti() {
  PACKAGE_NAME=$(apt-cache search $1 | fzf | cut --delimiter=" " --fields=1)
  if [ "$PACKAGE_NAME" ]; then
      echo "Installing $PACKAGE_NAME"
      sudo apt install $PACKAGE_NAME
  fi
}
fi
# }}}
# ┌─────────────┐
# │ tmux        │
# └─────────────┘
# ftmux {{{
#ftmux() {
#    prj=$(find $XDG_CONFIG_HOME/tmuxp/ -execdir bash -c 'basename "${0%.*}"' {} ';' | sort | uniq | nl | fzf | cut -f 2)
#    echo $prj
#    [ -n "$prj" ] && tmuxp load $prj
#}
# }}}
# {{{ftmuxp - propose every possible tmuxp session
ftmuxp() {
  if [[ -n $TMUX ]]; then
      return
  fi

  # get the IDs
  ID="$(ls $XDG_CONFIG_HOME/tmuxp | sed -e 's/\.yml$//')"
  if [[ -z "$ID" ]]; then
      tmux new-session
  fi

  create_new_session="Create New Session"

  ID="${create_new_session}\n$ID"
  ID="$(echo $ID | fzf | cut -d: -f1)"

  if [[ "$ID" = "${create_new_session}" ]]; then
      tmux new-session
  elif [[ -n "$ID" ]]; then
      # Change name of urxvt tab to session name
      printf '\033]777;tabbedx;set_tab_name;%s\007' "$ID"
      tmuxp load "$ID"
  fi
}
# }}}
# {{{fmux.choose-tmux-session
# ftmux - help you choose tmux sessions
ftmux() {
  if [[ ! -n $TMUX ]]; then
      # get the IDs
      ID="`tmux list-sessions`"
      if [[ -z "$ID" ]]; then
          tmux new-session
      fi
      create_new_session="Create New Session"
      ID="$ID\n${create_new_session}:"
      ID="`echo $ID | fzf | cut -d: -f1`"
      if [[ "$ID" = "${create_new_session}" ]]; then
          tmux new-session
      elif [[ -n "$ID" ]]; then
          printf '\033]777;tabbedx;set_tab_name;%s\007' "$ID"
          tmux attach-session -t "$ID"
      else
          :  # Start terminal normally
      fi
  fi
}
# }}}
# ┌─────────────┐
# │ files       │
# └─────────────┘
# {{{fwork.list-projects
fwork() {
    result=$(find ~/projects/* -type d -prune -exec basename {} ';' | sort | uniq | nl | fzf | cut -f 2)
    [ -n "$result" ] && cd ~/projects/$result
}
# }}}
# {{{na
# List install files for dotfiles
#fdot() {
#    file=$(find "$DOTFILES/" -exec basename {} ';' | sort | uniq | nl | fzf | cut -f 2)
#    [ -n "$file" ] && "$EDITOR" "$DOTFILES/$file"
#}
# Open pdf with Zathura
#fpdf() {
#    result=$(find -type f -name '*.pdf' | fzf --bind "ctrl-r:reload(find -type f -name '*.pdf')" --preview "pdftotext {} - | less")
#    [ -n "$result" ] && nohup zathura "$result" &>/dev/null & disown
#}
# Open epubs with Zathura
#fepub() {
#    result=$(find -type f -name '*.epub' | fzf --bind "ctrl-r:reload(find -type f -name '*.epub')")
#    [ -n "$result" ] && nohup zathura "$result" &>/dev/null & disown
#}
# Open freemind mindmap
#fmind() {
#    local folders=("$CLOUD/knowledge_base" "$WORKSPACE/alexandria")
#
#    files=""
#    for root in ${folders[@]}; do
#        files="$files $(find $root -name '*.mm')"
#    done
#    result=$(echo "$files" | fzf -m --height 60% --border sharp | tr -s "\n" " ")
#    [ -n "$result" ] && nohup freemind $(echo $result) &>/dev/null & disown }
# List tracking spreadsheets (productivity, money ...)
#ftrack() {
#    file=$(ls $CLOUD/tracking/**/*.{ods,csv} | fzf) || return
#    [ -n "$file" ] && libreoffice "$file" &>/dev/null & }
# }}}
# ┌─────────────┐
# │ shell utils │
# └─────────────┘
# {{{e.find+editor
e() {
  local files
  IFS=$'\n' files=($(fzf -q "`echo $@`" -m -1 -0))
  [[ $? -eq 0 ]] && ${EDITOR:-vim} "${files[@]}"
}
# }}}

edit() {
sel=$(
  command fd "${@:-.}" -Hi -tf -d3 --color=always | \
  fzf --query "${*:-}" \
    --multi \
    --select-1 \
    --exit-0 \
    --bind=ctrl-x:toggle-sort \
    --preview-window=':nohidden,right:65%:wrap' \
    --preview='([[ -f {} ]] && (bat --style=numbers --color=always {})) || ([[ -d {} ]] && (exa -TL 3 --color=always --icons {} | less)) || echo {} 2>/dev/null | head -200'
  )
[ -n "${sel}" ] && ${EDITOR:-vim} "${sel-*}"
}
# {{{o.another-editor
# function o() {
#   files="$(fzf --print0 --preview "bat --theme ansi --color always {}")"
#   if [ -z "$files" ]; then
#     return
#   fi
#   echo -n "$files" | xargs -0 -o "$EDITOR"
# }
# }}}
# {{{cf.fuzzy-cd-from-anywhere
# ex: cf word1 word2 ... (even part of a file name)
# zsh autoload function
cf() {
  local file

  file="$(fd -ai -0 $@ | grep -z -vE '~$' | fzf --read0 -0 -1)"

  if [[ -n $file ]]
  then
     if [[ -d $file ]]
     then
        cd -- $file
     else
        cd -- ${file:h}
     fi
  fi
}
# }}}
# {{{er.fd+fzf-cd
er() {
    entry="$(fd | fzf)"
    [ -f "$entry" ] && cd "$(dirname "$entry")" || return 1
    [ -d "$entry" ] && cd "$entry" || return 1
}
# }}}
# {{{fdr.cd-to-selected-parent-dir
fdr() {
  local declare dirs=()
  get_parent_dirs() {
    if [[ -d "${1}" ]]; then dirs+=("$1"); else return; fi
    if [[ "${1}" == '/' ]]; then
      for _dir in "${dirs[@]}"; do echo $_dir; done
    else
      get_parent_dirs $(dirname "$1")
    fi
  }
  local DIR=$(get_parent_dirs $(realpath "${1:-$PWD}") | fzf-tmux --tac)
  cd "$DIR"
}
# }}}
# {{{fzf-alias
fzf-alias() {
  setopt localoptions
  local selection
  if selection=$(alias |
    sed 's/=/\t/' |
          column -s '       ' -t |
          fzf --preview "echo {2..}" --query="$BUFFER" |
          awk '{ print $1 }'); then
  BUFFER=$selection
  CURSOR=$#BUFFER
fi
zle redisplay
}
zle -N fzf-alias
# }}}
# {{{fpop.search-dirs-stack
fpop() {
    # Only work with alias d defined as:

    # alias d='dirs -v'
    # for index ({1..9}) alias "$index"="cd +${index}"; unset index

    d | fzf --height="20%" | cut -f 1 | source /dev/stdin
}
# }}}
# {{{fif.find-in-file-w-ripgrep
fif() {
  if [ ! "$#" -gt 0 ]; then
  echo "need a string to search for!"; return 1; fi
  rg --files-with-matches --no-messages "$1" \
      | fzf --preview "highlight --out-format=ansi --line-numbers {} 2>/dev/null \
      | rg --colors 'match:bg:yellow' --ignore-case --pretty --context=10 '$1' \
      || rg --ignore-case --pretty --context=10 '$1' {}"
}
# }}}
# {{{fifa.find-using-ripgrep-all
fifa() {
    if [ ! "$#" -gt 0 ]; then return 1; fi
    local file
    file="$(rga --max-count=1 --ignore-case --files-with-matches --no-messages "$*" \
        | fzf-tmux -p +m --preview="rga --ignore-case --pretty --context 10 '"$*"' {}")" \
        && print -z "./$file" || return 1;
}
# }}}
# {{{fman.search-man-pages

fman() {
    man -k . | fzf -q "$1" --prompt='man> ' --preview $'echo {} | tr -d \'()\' | awk \'{printf "%s ", $2} {print $1}\' | xargs -r man' | tr -d '()' | awk '{printf "%s ", $2} {print $1}' | xargs -r man
}
# }}}
# {{{ssh-fzf
ssh_fzf () {
  selected_host=$(grep "Host " ~/.ssh/config | cut -b 6- | fzf --query "$LBUFFER")
  if [ -n "$selected_host" ]; then
    BUFFER="ssh ${selected_host}"
    zle accept-line
  fi
  zle reset-prompt
}
zle -N ssh-fzf
bindkey '^\' ssh-fzf
complete_ssh=$(
  (awk '!/\*/ && /^Host /{ print $2 }' ~/.ssh/config;
  # awk '{ sub(",.*$","",$1); print $1 }' ~/.ssh/known_hosts
  )|sort -u
)
printf '%s\n' "${complete_ssh[@]}" | fzf | xargs -o ssh

# get a list of all available SSH clients from the ~/.ssh/config file + fzf.
# function fssh(){
#   selected_client=$(grep -E "^Host\s+" ~/.ssh/config | awk '{print $2}' | fzf)
#   # check if a selection was made.
#   if [ -n "$selected_client" ]; then
#       # connect to the selected SSH client.
#       ssh "$selected_client"
#   else
#       echo "No SSH client selected. Exiting."
#   fi
# }
# }}}
