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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With