junegunn / fzf.vim

fzf :heart: vim
MIT License
9.51k stars 581 forks source link

Perform different sink actions on Enter and Shift+Enter #1535

Closed pabsan-0 closed 3 months ago

pabsan-0 commented 3 months ago

Hi, I want different actions to be performed with Enter and ShiftEnter.

I'm using fzf to fuzzyfind snippets and would like Enter to copy snippets into my current file and ShiftEnter to edit them. This is what my vimrc lines look like:

let s:snippets_path = "~/snippets/"

function! s:rg_file_read(location)
    let string_list = split(a:location, ':', 2)
    execute 'read ' .. s:snippets_path .. string_list[0]
endfunction

command! -bang -nargs=* CustomSnippets
    \ call fzf#vim#grep(
    \ "rg -m 1 -L --column --no-heading --pretty --smart-case ".shellescape(<q-args>), 
    \ 1, 
    \ fzf#vim#with_preview({'dir': s:snippets_path, 'sink': function('s:rg_file_read')}),
    \ <bang>0)

From man fzf the alternate action could be done on the CLI via something like fzf --bind "enter:execute(less {})", but I can't figure how to port that into vim. Could you please provide some pointers?

junegunn commented 3 months ago
let s:snippets_path = "~/snippets/"

function! s:rg_file_read(lines)
  if len(a:lines) < 2
    return
  endif

  let [key, file] = a:lines
  if key == 'alt-enter'
    execute 'tabedit' s:snippets_path .. file
  else
    execute 'read ' .. s:snippets_path .. file
  endif
endfunction

command! -bang -nargs=* CustomSnippets
    \ call fzf#run(fzf#vim#with_preview(fzf#wrap({
    \   'source': "rg -m 1 -L --no-heading --pretty --smart-case ".shellescape(<q-args>),
    \   'options': ['--reverse', '--ansi', '--expect=alt-enter', '--bind', 'focus:transform:[[ -n {} ]] && [[ ! {} =~ : ]] && exit; [[ $FZF_ACTION =~ up$ ]] && echo up || echo down'],
    \   'dir': s:snippets_path,
    \   'sink*': function('s:rg_file_read')
    \ }), <bang>0))