#!/usr/bin/env sh
#
# ---
# source: https://github.com/junegunn/fzf/blob/master/ADVANCED.md#controlling-ripgrep-search-and-fzf-search-simultaneously

tmpfile=$(mktemp -u)
trap 'rm -f "$tmpfile"' EXIT

INITIAL_QUERY="${*:-}"
# shellcheck disable=SC2016
TRANSFORMER='
  rg_pat={q:1}      # the first word is passed to ripgrep
  fzf_pat={q:2..}   # the rest are passed to fzf

  if ! [ -r "$tmpfile" ] || [ $rg_pat != $(cat "$tmpfile") ]; then
    echo "$rg_pat" >"$tmpfile"
    printf "reload:sleep 0.1; rg --column --line-number --no-heading --color=always --smart-case %q || true" "$rg_pat"
  fi
  echo "+search:$fzf_pat"
'
fzf --ansi --disabled --query "${INITIAL_QUERY}" \
  --with-shell 'bash -c' \
  --bind "start,change:transform:${TRANSFORMER}" \
  --color "hl:-1:underline,hl+:-1:underline:reverse" \
  --delimiter : \
  --preview 'bat --color=always {1} --highlight-line {2}' \
  --preview-window 'up,60%,border-line,+{2}+3/3,~3' \
  --bind "enter:become(${EDITOR:-vi} {1} +{2})"
