Running Ripgrep on files #3710
-
How can I configure a keybinding in fzf to run ripgrep over a selected array of files? I want to use fzf as a file picker to open the files in vim by default, but on pressing Ctrl+R, I want to run ripgrep over those files to search for a keyword. Related(?): https://github.com/junegunn/fzf/blob/master/ADVANCED.md#using-fzf-as-interactive-ripgrep-launcher |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Two IdeasA: Direct ApproachWe attempt to map the capability of searching a specified number of files with ripgrep to a single RG_PREFIX=$'rg --with-filename --column --line-number --no-heading --color=always --smart-case ${FZF_QUERY:-\'""\'} -- $(while IFS= read -r line; do printf "%q " "$line"; done < /tmp/rg_files) || true'
fzf \
--ansi \
--multi \
--delimiter : \
--bind 'start:execute-silent(: >/tmp/rg_files)+unbind:change' \
--bind "ctrl-r:rebind(change)+unbind(ctrl-r)+disable-search+clear-query+execute-silent(cp {+f} /tmp/rg_files)+change-preview(bat --color=always {1} --highlight-line {2})+change-preview-window(up,60%,border-bottom,+{2}+3/3,~3)+reload:eval $RG_PREFIX" \
--bind "change:reload:sleep 0.1; eval $RG_PREFIX" \
--bind "enter:transform:[[ {} == *:*:*:* ]] &&
echo 'become:vim \{1} +\{2}' ||
echo 'become:vim \{}'" B: Script ApproachThis idea calls a script from our normal usage. Two things are needed:
#!/usr/bin/env bash
# Original: https://github.com/junegunn/fzf/blob/master/ADVANCED.md#using-fzf-as-interactive-ripgrep-launcher
# Modified version
while getopts :f: cmd_arg; do
case "$cmd_arg" in
f) file_list=$(while IFS=$'\n' read -r line; do printf "%q " "$line"; done <"${OPTARG}") ;;
*)
exit 1
;;
esac
done
shift "$((OPTIND - 1))"
RG_PREFIX="rg --with-filename --column --line-number --no-heading --color=always --smart-case "
INITIAL_QUERY="${*:-}"
: | fzf \
--ansi --disabled --query "$INITIAL_QUERY" \
--bind "start:reload:$RG_PREFIX {q} -- $file_list " \
--bind "change:reload:sleep 0.1; $RG_PREFIX {q} -- $file_list || true" \
--delimiter : \
--preview 'bat --color=always {1} --highlight-line {2}' \
--preview-window 'up,60%,border-bottom,+{2}+3/3,~3' \
--bind 'enter:become:vim {1} +{2}'
fzf \
--multi \
--bind 'ctrl-r:become:modified_rfv -f {+f}' \
--bind 'enter:become:vim {+}' Note The main challenge with any version was to ensure it also worked for filenames containing spaces. Footnotes |
Beta Was this translation helpful? Give feedback.
Two Ideas
A: Direct Approach
We attempt to map the capability of searching a specified number of files with ripgrep to a single
hotkey. This approach sacrifices readability, and one must navigate the complexities of escaping and
quoting.