" set up fzf-bibtex
let g:fzf_bibtex_cache = '~/.cache/'
let g:fzf_bibtex_sources = g:pandoc#biblio#bibs

" prepare bibtex_ls function to look for bib files in cwd/parent/subdirs,
" attach the standard bibtex source file
" return the command with standard cache directory filled
function! s:bibtex_ls(...)
  let bibfiles = (
      \ globpath('.', '*.bib', v:true, v:true) +
      \ globpath('..', '*.bib', v:true, v:true) +
      \ globpath('*/', '*.bib', v:true, v:true)
      \ )
  let bibfiles = join(bibfiles, ' ')
  let source_cmd = 'bibtex-ls -cache ' . g:fzf_bibtex_cache . ' ' .bibfiles . ' ' . join(g:fzf_bibtex_sources)
  return source_cmd
endfunction

" NORMAL MODE CITATION
" insert citation from normal mode at cursor (with brackets)
function! s:bibtex_cite_sink(lines)
    let r=system("bibtex-cite ", a:lines)
    execute ':normal! i[' . r . ']'
endfunction
command! -bang -nargs=* CiteRef call fzf#run(fzf#wrap({
      \ 'source': <sid>bibtex_ls(<q-args>),
      \ 'sink*': function('<sid>bibtex_cite_sink'),
      \ 'up': '25%',
      \ 'options': '--ansi --multi --prompt "Cite> "'
      \ }))

" INSERT MODE CITATION
" insert citation from insert mode at cursor (no brackets inserted)
function! s:bibtex_cite_sink_insert(lines)
    let r=system("bibtex-cite ", a:lines)
    execute ':normal! i' . r
    call feedkeys('a', 'n')
endfunction

" MARKDOWN CITATION
" insert markdown formatted reference
function! s:bibtex_markdown_sink(lines)
  let r=system("bibtex-markdown -cache " . g:fzf_bibtex_cache . ' ' . join(g:fzf_bibtex_sources), a:lines)
  echo join(a:lines, '; ')
  execute ':normal! a' . r
endfunction
command! -bang -nargs=* CiteMarkdown call fzf#run(fzf#wrap({
      \ 'source': <sid>bibtex_ls(),
      \ 'sink*': function('<sid>bibtex_markdown_sink'),
      \ 'up': '25%',
      \ 'options': '--ansi --multi --prompt "Markdown> "'
      \ }))
