4

Is there a way to list the buffers specific to the tab that is open currently in vim or macvim?

1

The following code defines a new command :LsByTab that parses the output of :ls and groups it by tabs. You can call the command with an exclamation mark and/or the flags supported by :ls.

"
" Get the output of :ls as a List of lines.
"
function! s:LsOutput(bang, args)
    redir => ls_output
    exe 'silent ls' . a:bang a:args
    redir END
    return split(ls_output, "\n")
endfunction

"
" Group the output of :ls by tabs and print it.
"
function! LsByTab(bang, args)
    let ls_output = s:LsOutput(a:bang, a:args)

    " Iterate over all tabs.
    for tab in gettabinfo()
        echo '===== tab' tab.tabnr '====='
        " Get the buffer numbers for the current tab.
        let buffers = tabpagebuflist(tab.tabnr)
        " Construct a regular expression that matches the buffer numbers
        " at the start of the lines of the :ls output.
        let buffers_pat = '^\s*\(' . join(buffers, '\|') . '\)\>'
        " Filter the lines from the :ls output so that only the lines for
        " the buffers of the current tab remain.
        let tab_buffers = filter(copy(ls_output), 'v:val =~ buffers_pat')
        " Print the info for the current tab.
        echo join(tab_buffers, "\n")
    endfor
endfunction

command! -bang -nargs=? LsByTab call LsByTab(<q-bang>, <q-args>)
5

The following code will give you the file names for the current tab (if the buffer in a window is connected to a file):

" Get the buffer numbers of all windows on the current tab
let buffers = tabpagebuflist(tabpagenr())
" Get the name of each buffer
let buffernames = map(copy(buffers), {key, val -> bufname(val)})
" Print the buffer names
echo buffernames

This needs a sufficiently new version of Vim, which supports lamdas.

  • 1
    You can replace the 2 first commands by let buffers = tabpagebuflist(). :h tabpagebuflist() – statox Sep 8 '17 at 10:22
  • @statox Thank you, done. When searching for an adequate function in the docs I had only looked for something matching get*(). :-( – Jürgen Krämer Sep 8 '17 at 11:29
  • Lambda free version: let buffernames = map(copy(buffers), 'bufname(v:val)'). Also you can see function group by category via :h function-list – Peter Rincker Sep 8 '17 at 17:25
  • This only tells you the number of the currently open buffers though. I was hoping something more like ls command that groups buffers by which tab they are in. – tushar Sep 9 '17 at 3:09
  • 1
    @tushar You should update your question to make this more clear. See my second answer for a solution that matches your reworded question. – Jürgen Krämer Sep 11 '17 at 8:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.