2

How can I find a buffer in vimscript when I have an absolute path, and as you know vim buffer names can be relative path? Is there a function for that?

user14416
  • 378

2 Answers2

2

The bufnr() function can find buffers (and return its number). Like bufname(), this can take the queried buffer name in several forms (cp. :help bufname()):

  A full match is preferred, otherwise a match at the start, end
  or middle of the buffer name is accepted.  If you only want a
  full match then put "^" at the start and "$" at the end of the
  pattern.

So, one example would be

:echo bufnr('^C:\path\to\file.txt$')

Also, you can convert between relative and absolute paths via the fnamemodify() function.

Ingo Karkat
  • 23,523
0

You can do the following if you are careful:

let bufnr_val = bufnr('^'..escape(full_path '\.*?~,^${}[]')..'$')
if bufnr_val >= 0 && expand('#'..bufnr_val..':p') != full_path
    let bufnr_val = -1
endif

I think the double-check is only useful when full_path in fact doesn't start with /, however. (In which case the snippet should be guaranteed to return -1 anyway) If it does start with / then vim does seem to be matching only the full path.