pathbufferfilenamesvim

vimscript: switch to buffer by filename path


I have a vimscript which needs to switch to a particular buffer. That buffer will be specified by either full path, partial path, or just its name.

For example:

I am in the directory /home/user/code and I have 3 vim buffers open foo.py src/foo.py and src/bar.py.

The simplest solution I can see is to somehow get a list of the buffers stored in a variable and use trial and error.

It would be nice if the solution was cross platform, but it needs to at least run on Linux.


Solution

  • The bufname() / bufnr() functions can lookup loaded buffers by partial filename. You can anchor the match to the end by appending a $, like this:

    echo bufnr('/src/foo.py$')