summaryrefslogtreecommitdiff
path: root/.local/bin/frg
blob: 97f703ad58f21f9512ef2388cda07d8553c9ca1d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/bin/sh

# https://junegunn.github.io/fzf/tips/ripgrep-integration/#6-bind-enter-to-become-action

help() { echo "frg - grep with fzf

USAGE:
	fgrp [OPTION]... PATTERN

OPTIONS:
	-r  real time grepping in fzf prompt
	-h  show this help message"; }

err() { printf '%s: %s\n' "$0" "$@" >&2; exit 1; }

while getopts 'rh' o; do case "$o" in
	r) rflag=1 ;;
	h) help >&2; exit ;;
	?) err "invalid option passed" ;;
esac done
shift $((OPTIND - 1))

[ -z "$FZF_HISTDIR" ] &&
	export FZF_HISTDIR="${XDG_STATE_HOME:-$HOME/.local/state}/fzf"
mkdir -pv "$FZF_HISTDIR"
export FZF_HIST="$FZF_HISTDIR/grep_history"

if command -v rg >/dev/null; then
	GREP_CMD="rg --smart-case --column --color=always"
elif command -v git >/dev/null; then
	GREP_CMD="git grep -I --ignore-case --column --color=always"
else
	GREP_CMD="grep -Rnsi --exclude-dir=.git --color=always"
fi

RELOAD="reload($GREP_CMD {q} || :)"

OPENER='
	# update history
	sed -i \\\|^{q}$\|d "$FZF_HIST"
	echo {q} >> "$FZF_HIST"

	if [[ $FZF_SELECT_COUNT -eq 0 ]]; then
		$EDITOR {1} +{2}     # No selection. Open the current line in Vim.
	else
		$EDITOR +cw -q {+f}  # Build quickfix list for the selected items.
	fi
	'

query="$*"

fzf() { $GREP_CMD "$query" | command fzf "$@" \
	--ansi --multi --header-first \
	--history="$FZF_HIST" \
	--bind "enter:execute($OPENER)" \
	--bind "ctrl-o:become($OPENER)" \
	--bind 'ctrl-v:toggle-preview,ctrl-space:toggle-preview' \
	--bind "ctrl-r:reload($GREP_CMD '$query')" \
	--bind 'alt-a:select-all,alt-d:deselect-all,ctrl-/:toggle-preview' \
	--delimiter : \
	--preview 'bat --style=full --color=always --highlight-line {2} {1}' \
	--preview-window '~4,+{2}+4/3,<80(up)'; }

if [ "$rflag" = 1 ]; then
	fzf --disabled --query "$query" \
		--header "COMMAND: $GREP_CMD <prompt-query>" \
		--bind "change:$RELOAD"
else
	fzf --header "COMMAND: $GREP_CMD '$query'"
fi