#!/usr/bin/env bash
#
# rgfzf - interactively search files with rg (with reload)
# shellcheck shell=bash

# shellcheck disable=SC2312
escape() { printf "'%s'\\n" "$(printf '%s' "$1" | sed -e "s/'/'\\\\''/g")"; }
# ssh host "cat $(printf "%q" "$remotefile")"
# ssh host "cat $(escape "$remotefile")"

RG_PREFIX="rg --column --hidden --line-number --no-heading --color=always --smart-case "
INITIAL_QUERY="${*:-}"
IFS=: read -ra selected < <(
  FZF_DEFAULT_COMMAND="${RG_PREFIX} $(escape "${INITIAL_QUERY}")" \
  fzf --multi --ansi \
    --disabled --query "${INITIAL_QUERY}" \
    --bind="change:reload:sleep 0.1; ${RG_PREFIX} {q} || true" \
    --delimiter=':' \
    --color='hl:-1:underline,hl+:-1:underline:reverse' \
    --preview='bat --style=numbers,header,changes,snip --color=always {1} --highlight-line {2}' \
    --preview-window='nohidden,right:60%:~1:+{2}+3/2:border-left'
)
# --preview-window 'nohidden,up,60%,border-bottom,+{2}+3/3,~3'
# [ -n "${selected}" ] && ${EDITOR:-vim} "${selected[0]}" "+${selected[1]}"
