-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvgc
More file actions
executable file
·86 lines (74 loc) · 2.73 KB
/
vgc
File metadata and controls
executable file
·86 lines (74 loc) · 2.73 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/bin/bash
# vgc -- rg with context on STDIN on $PWD, with help
# usage: pipe | vgc pattern
# OR just: vgc pattern [optional list of paths to search]
# optional N (single digit) *before* the pattern; default 5
# set -x
export PS4=':.$LINENO:'
# ----------------------------------------------------------------------
# preview (invoked by fzf)
# For the life of me I could not figure out how to roll this functionality
# directly into the `--preview=` option! Oh well, this works fine too.
[[ $1 == --preview ]] && {
shift
q="$*"
q=${q// /\\|}
grep --color=always -i -e '$' -e "$q" -e 20..-..-.. -e XXX -e TODO -e NOTE -e WARNING -e OBSOLETE -e ERROR
# I'm sure this code won't survive past 2099. I know *I* won't :-)
exit 0
}
# ----------------------------------------------------------------------
# main
c=5
[[ $1 =~ ^[1-9]$ ]] && c=$1 && shift
q="$1"; shift
_vgc () {
: "c is for context"
: "change the query and hit enter to restart with the new query string"
: "starts with a context of 5; type a number and hit enter to change it (query string will revert to $1)"
rg -n -C$c "$q" "$@" |
perl -pe 's/^--\n/\0/' |
fzf \
-q "$q" \
--read0 \
--preview-window=wrap:top:75% \
--preview="echo {} | $0 --preview {q}" \
--print-query \
--expect "enter,esc,ctrl-c,ctrl-n" \
--header "ctrl-n to accept new query and restart
escape or ctrl-c to exit without doing anything
enter to open vim quickfix list with selected entries"
}
[[ -t 0 ]] || {
VGCTMPF=$HOME/tmp/vgc.$$
rm -f $VGCTMPF
cat > $VGCTMPF
trap "rm -f $VGCTMPF" 0
}
while :; do
if [[ -t 0 ]]; then
r=$(_vgc "$@") # search PWD if nothing specified
else
r=$(cat $VGCTMPF | _vgc)
fi
newq=$(echo "$r" | head -1)
[[ $newq =~ ^[1-9][0-9]*$ ]] && c=$newq || q="$newq"
k=$(echo "$r" | sed -ne '2p')
[[ $k == esc ]] && exit # user hit esc, exit
[[ $k == ctrl-c ]] && exit # user hit esc, exit
[[ $k == ctrl-n ]] && continue # user hit ctrl-n, loop
[[ $k == enter ]] && { # user hit enter, open vim quickfix list
# make a vim search pattern out of the first line of $x (which is the "query",
# due to using "--print-query" in the fzf command)
q=$(echo "$r" | head -1 | tr ' ' '|')
if [[ -t 0 ]]; then
# start vim with the quickfix list set to "$r". \v is "very
# magic"; allows '|' to act as alternation in regex
vim -q <(echo "$r"|tail -n +2|grep -E ":[0-9]+:") -c copen -c "let @/='\v$q'"
else
# stdin was a pipe
echo "$r"|tail -n +3
break
fi
}
done