tags:

views:

99

answers:

3

I really like this vim trick to use the left and right arrows to flip between buffers:

"left/right arrows to switch buffers in normal mode
map <right> :bn<cr>
map <left> :bp<cr>

(Put that in ~/.vimrc)

But sometimes I'm munching on a sandwich or something when scrolling around a file and I really want the arrow keys to work normally. I think what would make most sense is for the arrow keys to have the above buffer-flipping functionality only if there are actually multiple buffers open.

Is there a way to extend the above to accomplish that?

+3  A: 

I'd rather have a completely different mapping because:

  • cursors are really useful, and not having them because you have a hidden buffer will annoy you a lot
  • some plugins use <left> and <right> because they are less obfuscated than l and h; those plugins are likely to break with such mappings

Anyway, you can try this:

nnoremap <expr> <right> (len(filter(range(0, bufnr('$')), 'buflisted(v:val)')) > 1 ? ":bn\<cr>" : "\<right>")
nnoremap <expr> <left> (len(filter(range(0, bufnr('$')), 'buflisted(v:val)')) > 1 ? ":bp\<cr>" : "\<left>")

To see documentation on the pieces above:

:h :map-<expr>
:h len()
:h filter()
:h range()
:h bufnr()
:h buflisted()
Luc Hermitte
Perfect! This does exactly what I had in mind. (After adding the corresponding nnoremap for <left> of course.) I'm open to suggestions for better keys to map :bp and :bn to.
dreeves
My thinking is that if I've opened multiple buffers then I'm being all serious with both hands on the keyboard and definitely using HJKL to navigate. But you're probably right that I'll change my mind the first time I run into a plugin that depends on <left> and <right> being unmapped.
dreeves
+1  A: 

I map Tab and Shift+Tab to switch buffers when in normal mode (makes sense to my brain and the keys are not doing anything useful otherwise).

Add this to your .vimrc

" Use Tab and Shift-Tab to cycle through buffers
nnoremap <Tab> bnext<CR>
nnoremap <S-Tab> :bprevious<CR>
scomar
Good idea, though I actually map TAB to ESC. See http://stackoverflow.com/questions/397229/reaching-up-to-hit-the-escape-key-sucks-especially-in-vim/397242#397242
dreeves
+1  A: 

I use alt-direction to switch between buffers.

nmap <A-Left> :bp<CR>
nmap <A-Right> :bn<CR>

If you modifying hl's defaults, then the arrows would feel more useful. (Like changing whichwrap to allow hl to go past the end of line.)

I do something similar with jk to make them different from my arrows:

" work more logically with wrapped lines
set wrap
set linebreak
noremap j gj
noremap k gk
noremap gj j
noremap gk k

That will wrap long lines and jk will move to what looks like the line below. (If you have one long line, then you'll move to the part of that line below the cursor.) Great for editing prose or long comments.

See also

help showbreak
pydave