" See https://github.com/junegunn/fzf/blob/master/README-VIM.md
" An action can be a reference to a function that processes selected lines
function! s:build_quickfix_list(lines)
  call setqflist([], ' ', { 'title': 'FZF Selected', 'items': map(copy(a:lines), '{ "filename": v:val }') })
  copen
  cc
endfunction

" https://github.com/junegunn/fzf.vim/pull/733
function! s:list_buffers()
  redir => list
  silent ls
  redir END
  return split(list, "\n")
endfunction

function! s:delete_buffers(lines)
  execute 'bwipeout' join(map(a:lines, {_, line -> split(line)[0]}))
endfunction

command! BD call fzf#run(fzf#wrap({
  \ 'source': s:list_buffers(),
  \ 'sink*': { lines -> s:delete_buffers(lines) },
  \ 'options': '--multi --reverse --bind ctrl-a:select-all+accept'
\ }))

let g:fzf_action = {
\  'ctrl-q': function('s:build_quickfix_list'),
\  'ctrl-t': 'tab split',
\  'ctrl-x': 'split',
\  'ctrl-v': 'vsplit',
\  }

let $FZF_DEFAULT_OPTS = '--layout=reverse --bind "Ctrl-n:preview-down,Ctrl-p:preview-up"'
let g:fzf_layout      = { 'window': { 'width': 0.8, 'height': 0.8 }, }

nnoremap <Leader>b  :Buffers<CR>
nnoremap <Leader>B  :History<CR>
nnoremap <Leader>/  :GFiles?<CR>
nnoremap <Leader>ff :GFiles<CR>
nnoremap <Leader>fF :Files<CR>
nnoremap <Leader>fL :Lines<CR>
nnoremap <Leader>fc :BCommits<CR>
nnoremap <Leader>fC :Commits<CR>
nnoremap <Leader>fh :History:<CR>
nnoremap <Leader>fH :History/<CR>
nnoremap <Leader>fm :Marks<CR>
nnoremap <Leader>fo :Locate<CR>
nnoremap <Leader>fk :Maps<CR>
nnoremap <Leader>f/ :Rg<CR>
nnoremap <Leader>fs :<C-u>Rg <C-r><C-w><CR>
nnoremap <Leader>fw :BD<CR>

imap <C-x><C-w> <Plug>(fzf-complete-word)
imap <C-x><C-p> <Plug>(fzf-complete-path)
imap <C-x><C-f> <Plug>(fzf-complete-file)
imap <C-x><C-l> <Plug>(fzf-complete-line)
