-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgr
executable file
·71 lines (60 loc) · 2.61 KB
/
gr
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
71
#!/usr/bin/env sh
# vim: ft=sh ts=4 sw=4 sts=4 et :
# Find a regex pattern using rg and fzf
has() {
command -v "$1" >/dev/null 2>&1
}
# Temporary files used by the script
REGEX_QUERY_FILE="/tmp/rg-fzf-r-$$"
FUZZY_QUERY_FILE="/tmp/rg-fzf-f-$$"
OUTPUT_FILE="/tmp/rg-fzf-o-$$"
cleanup() {
rm -f "$REGEX_QUERY_FILE" "$FUZZY_QUERY_FILE" "$OUTPUT_FILE"
}
trap cleanup HUP INT QUIT ABRT EXIT
# $1: search root path
main() {
# Set preview command based on available tools
if has bat; then
preview_cmd='bat --theme base16 --paging never --style numbers,header-filename --color always {1} --highlight-line {2}'
elif has batcat; then
preview_cmd='batcat --theme base16 --paging never --style numbers,header-filename --color always {1} --highlight-line {2}'
elif has fzf-file-previewer; then
preview_cmd='fzf-file-previewer {1} {2}'
elif has cat; then
preview_cmd='cat {1}'
fi
# Set grep command based on available tools
if has rg; then
grep_cmd="rg --no-messages --hidden --follow --smart-case --column --line-number --no-heading --color=always "
elif has grep; then
grep_cmd="grep -i -r -n -H -I --color=always "
fi
# Set editor
if has nvim; then
editor='nvim'
elif has vim; then
editor='vim'
fi
root_path="$1"
initial_query="${*:-}"
regex_search_hint=$(printf ":: <\033[33;1mctrl-g\033[0m> to \033[33;1mRegex Search\033[0m")
fuzzy_search_hint=$(printf ":: <\033[33;1mctrl-t\033[0m> to \033[33;1mFuzzy Search\033[0m")
regex_prompt=' Rg> '
fuzzy_prompt=' Fzf> '
: | fzf --ansi --disabled --query "$initial_query" \
--bind "start:reload($grep_cmd {q} \"$root_path\")+unbind(ctrl-g)" \
--bind "change:reload:sleep 0.1; $grep_cmd {q} \"$root_path\" || true" \
--bind "ctrl-t:unbind(change,ctrl-t)+change-prompt($fuzzy_prompt)+enable-search+rebind(ctrl-g)+transform-query(echo {q} > \"$REGEX_QUERY_FILE\"; cat \"$FUZZY_QUERY_FILE\")+change-header($regex_search_hint)" \
--bind "ctrl-g:unbind(ctrl-g)+change-prompt($regex_prompt)+disable-search+reload($grep_cmd {q} \"$root_path\" || true)+rebind(change,ctrl-t)+transform-query(echo {q} > \"$FUZZY_QUERY_FILE\"; cat \"$REGEX_QUERY_FILE\")+change-header($fuzzy_search_hint)" \
--prompt "$regex_prompt" \
--delimiter ':' \
--header "$fuzzy_search_hint" \
--preview "$preview_cmd" \
--preview-window '+{2}-6,~1' >"$OUTPUT_FILE"
# Let editor read the output file as error file and jump to the first error
if [ -s "$OUTPUT_FILE" ]; then
$editor +"cfile $OUTPUT_FILE"
fi
}
main "$@"