Reputation: 5498
In my Vimscript I would like to iterate over all/only the buffers containing files on disk. At the moment I'm doing this to get an array of buffer ids:
filter(range(1, bufnr('$')), 'buflisted(v:val)')
And then later on I test each buffer id with:
filereadable(fnamemodify(bufname(buffer_id), ':p'))
I've read the documentation on buflisted, bufloaded, and friends, but I'm still not clear what the difference is between them. Consequently I'm not sure whether my snippet above is optimal.
Furthermore this seems a common task for which there would be a built-in function, but I can't find one.
Is this the best way or is there a better way?
Upvotes: 2
Views: 186
Reputation: 5498
I think the buffer_id -> filename conversion can be done better by:
expand('#' . buffer_id . ':p')
This could be combined with the buffer list into this one-liner:
filter(range(1, bufnr('$')), 'buflisted(v:val) && filereadable(expand("#" . v:val . ":p"))')
Upvotes: 0
Reputation: 172788
I guess the "common way" is just using :bufdo
and have it fail on :write
of unnamed, unpersisted files, but in a plugin, it's good to do more checking.
Your approach looks fine to me. :help 'buflisted'
says:
If it is reset it is not used for ":bnext", "ls", the Buffers menu, etc. This option is reset by Vim for buffers that are only used to remember a file name or marks. Vim sets it when starting to edit a buffer.
So assuming your plugin does something similar to :bufdo
, using buflisted()
is right.
Upvotes: 1