#!/bin/sh -e
#
# rgff - search both file name and content with ripgrep and fzff
# dependencies: fzf | ripgrep
#
# fzf --preview window ~8,+{1}-5:
# ~8    - show first 8 lines (header)
# +{2}  - delimits input piped into it and provides access via index vars {n}
#         default delimiter is space but can be specified via --delimiter
#         pass the second index variable from bat (which is the line number)
#         number is signed, you can show e.g. +n/-n row (nth row from bottom)
# -5    - subtract 5 rows(go up 5 rows) => no highlighted line as the first line
#         provide context by showing the rows above the highlighted line
#
# ---
# see: https://github.com/junegunn/fzf/issues/2789

query="${*:-}"
selection=$(
  rg --color=always --smart-case --line-number --with-filename "${query}" \
    | fzf --ansi --delimiter=':' \
      --preview='bat --color=always {1} --highlight-line {2}' \
      --preview-window='~8,+{2}-5'
)

file="${selection%%:*}"
num="${selection#*:}"
num="${num%%:*}"

[ -n "${file}" ] && exec ${EDITOR:-vi} "${file}" "+${num}"
