#!/usr/bin/env sh
#
# vv - open most recently viewed files in EDITOR with fzf
# dependencies: fzf | vim/nvim

if [ -n "${oldfiles}" ]; then
  :
else
  oldfiles=$(mktemp)
  trap 'rm -f "$oldfiles"' EXIT HUP INT TERM
fi

if command -v nvim >/dev/null 2>&1; then
 nvim --headless -c "call append(0, v:oldfiles)" \
    -c "write! ${oldfiles}" \
    -c exit 1>/dev/null 2>&1
else
  ${EDITOR:-vi} -c "call append(0, v:oldfiles)" \
    -c "write! ${oldfiles}" \
    -c exit 1>/dev/null 2>&1
fi

files=$(
  rg --invert-match 'term|man|help|qf|fugitive|Preview' "${oldfiles}" \
    | fzf --ansi --reverse \
      --height=80% --padding=0 --margin=1,5 --border='thinblock' \
      --no-info --prompt="" --gutter=" " --pointer=" " \
      --delimiter="/" --with-nth=-2,-1 \
      --multi \
      --bind='ctrl-y:execute-silent(printf '\''%s'\'' {+} | pbcopy)+bell' \
      --bind='ctrl-y:+transform-footer(echo Copied {} to clipboard)' \
      --bind='ctrl-y:+bg-cancel+bg-transform-footer(sleep 1)' \
      --bind="alt-e:execute(${EDITOR:-vi} {1} +{2})" \
      --bind='?:toggle-preview' \
      --preview-window='hidden,50%,border-left' \
      --preview='bat --color=always --style=snip {} | head -200'
)

if [ -n "${files}" ] && [ -e "${files}" ]; then
  ${EDITOR-} "${files}"
else
  exit 1
fi
