Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect if a specific buffer exists in Vimscript?

Tags:

vim

I want to detect if a specific file is already opened (visible) in a Vim window with Vimscript. If the file isn't open (visible) in a vim-window, I want to open it via :edit.

I have a variable with the expanded file path and want to check whether a file with that expanded filepath is already opened (visible) in a Vim window.

How can I do that?

A second question about that is how I can get a list with all opened (visible) files and all not visible but open files (buffers).

I think this is mainly about buffers.

SOLUTION (2016.02.18)

thx @muru for pointing in to the needed functions. my test solution looks like that in the moment

function! ChooseBuffer(buffername)
    let bnr = bufwinnr(a:buffername)
    if bnr > 0
       :exe bnr . "wincmd w"
    else
       echo a:buffername . ' is not existent'
       silent execute 'split ' . a:buffername
    endif
 endfunction
:nnoremap <leader><leader>d :call ChooseBuffer("divramod.vim")<cr>
:nnoremap <leader><leader>1 :call ChooseBuffer("vim/plugin/divramod/test1.vim")<cr>
:nnoremap <leader><leader>2 :call ChooseBuffer("vim/plugin/divramod/test2.vim")<cr>
:nnoremap <leader><leader>t :call ChooseBuffer("vim/plugin/divramod/test.vim")<cr>

It seems to be the case, that bufwinnr() finds "divramod.vim" despite the fact, that the buffername in the bufferlist is called "vim/plugin/divramod/divramod.vim". It seems to use a regex for searching inside the buffername. i have to experiment, what happens when two buffers with the same filename but different file pathes are opened.

like image 935
divramod Avatar asked Feb 17 '16 19:02

divramod


2 Answers

You can use the bufwinnr() function:

bufwinnr({expr})                                        bufwinnr()
            The result is a Number, which is the number of the first
            window associated with buffer {expr}.  For the use of {expr},
            see bufname() above.  If buffer {expr} doesn't exist or
            there is no such window, -1 is returned.

And from bufname():

            If the {expr} argument is a string it must match a buffer name
            exactly.  The name can be:
            - Relative to the current directory.
            - A full path.
            - The name of a buffer with 'buftype' set to "nofile".
            - A URL name. 

So, something like:

if bufwinnr(myfile) > 0
  echo "Already open"
endif
like image 198
muru Avatar answered Nov 03 '22 15:11

muru


If you want to know if a buffer exists, not that it both exists and is open in some window, use bufexists(buffer_number). I recommend using bufexists(str2nr(buffer_number)), in case your buffer variable happens to be a string. This will return 1, even if your buffer exists, but isn't open in any current windows.

like image 23
w0rp Avatar answered Nov 03 '22 15:11

w0rp