1

I know that I can do a conditional key mapping by map-expression:

map [key] [condition] ? [foo] : [bar]

But now my situation is somehow awkward. I want to map <C-h> to <C-w>h if I have more than one windows in my VIM, and map it to :bprev if there is only one window in my VIM.

I've tried with

    nnoremap <C-h> winnr('$')>1 ? '<C-w>h' : ':bprev<CR>'

But it doesn't work as .vimrc is only read once when I start VIM. So I also tried with autocmd and failed. Could anyone help me?

1

1 Answer 1

4

You need the <expr> modifier:

nnoremap <expr> <C-h> winnr('$')>1 ? '<C-w>h' : ':bprev<CR>'

This conditional is evaluated every time the mapped key is sent, instead of once at mapping time.

1
  • Thanks so much, I found I didn't see <expr> in the doc...
    – WW00WW
    Feb 18, 2019 at 1:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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