Teo Gelles
Teo Gelles

Reputation: 82

How to combine :b and :ls functionality in Vim?

In Vim, is there a way to make :b list the buffer numbers next to open buffers, in a way similar to the :ls command but without having to retype :b afterwards?

Upvotes: 2

Views: 402

Answers (1)

romainl
romainl

Reputation: 196476

enter image description here

This great mapping, popularized by a most valuable member of the community, does exactly what you want:

nnoremap gb :ls<CR>:b

A more generic approach…

Vim uses that non-interactive list to display the result of a number of other useful commands. I've written this simple function to insert the right "stub" each time I press <CR> after one of those commands:

function! CmdCR()
    " grab the content of the command line
    let cmdline = getcmdline()

    if cmdline =~ '\C^ls'
        " like :ls but prompts for a buffer command
        return "\<CR>:b"

    elseif cmdline =~ '/#$'
        " like :g//# but prompts for a command
        return "\<CR>:"

    elseif cmdline =~ '\v\C^(dli|il)'
        " like :dlist or :ilist but prompts for a count for :djump or :ijump
        return "\<CR>:" . cmdline[0] . "jump  " . split(cmdline, " ")[1] . "\<S-Left>\<Left>"

    elseif cmdline =~ '\v\C^(cli|lli)'
        " like :clist or :llist but prompts for an error/location number
        return "\<CR>:silent " . repeat(cmdline[0], 2) . "\<Space>"

    elseif cmdline =~ '\C^old'
        " like :oldfiles but prompts for an old file to edit
        return "\<CR>:edit #<"

    else
        " default to a regular <CR>
        return "\<CR>"

    endif
endfunction

cnoremap <expr> <CR> CmdCR()

Upvotes: 3

Related Questions