vimunite.vim

Autoclose buffer occupying Vim's preview window when new buffer opens in preview window


I use Unite.vim frequently to scroll through lists of files in Vim. Sometimes I use Unite's auto-preview feature to have each file open in the preview window as I scroll over it. If I scroll through a large number of files, this leaves me with a bunch of open buffers that I do not need. How can I make the buffer currently occupying the preview window close when a new buffer is opened into the preview window?


Solution

  • I was able to solve this problem by looking through the Unite source, copying the preview function, and making the modification I needed directly on this function to do a vertical open of the preview window:

    function! s:preview.func(candidate)
      let buflisted = buflisted(
            \ unite#util#escape_file_searching(
            \ a:candidate.action__path))
      if filereadable(a:candidate.action__path)
        " If execute this command, unite.vim will be affected by events.
        noautocmd silent execute 'vert pedit!'  " added vert
              \ fnameescape(a:candidate.action__path)
        call SetWidthToHalfScreen()  " added to resize preview window
        let prev_winnr = winnr('#')
        let winnr = winnr()
        wincmd P
        doautoall BufRead
        setlocal nomodified
        execute prev_winnr.'wincmd w'
        execute winnr.'wincmd w'
      endif
      if !buflisted
        call unite#add_previewed_buffer_list(
            \ bufnr(unite#util#escape_file_searching(
            \       a:candidate.action__path)))
      endif
    endfunction
    call unite#custom#action("openable", "preview", s:preview)
    call unite#custom#action("file", "preview", s:preview)
    
    function! SetWidthToHalfScreen()
      let diff = 100 - winwidth(winnr())
      exec "vert resize " . (diff > 0 ? '+' : '-') . abs(diff)
    endfunction