I want to map the tab key to <c-w>w to switch windows when there is more than one window open. But if there is only one window but multiple tabs, I want it to detect that there is only one window and to switch tabs instead by mapping to gt. Note both commands are in the same mode.

Is this possible? I am asking this one key to map to two different choices and the key only performs the second choice when the first one fails.

1 Answer 1


You can do it using an expression-mapping like this:

nnoremap <expr><silent> <tab> winnr('$')>1 ? "\<c-w>w" : 'gt'

this makes the mapping basically check, if there are several windows open (winnr('$') is greater than 1) and in that case returns CTRLW else, it returns gt

Note: the double quotation marks are necessary, to make Vim correctly parse the key code <c-w>.

In case there exists only one tabpage, you need to add 2 checks, something like this:

nnoremap <expr><silent> <tab> winnr('$')>1 ? "\<c-w>w" : (tabpagenr('$')>1 ? 'gt' : ":bn\<cr>")

  • Wow! I tried the exercise and decide to switch buffers if windows and tabs are 1. Could you tell me why this doesn't work? nnoremap <expr><silent> <tab> winnr('$')>1 ? "\<c-w>w" : tabpagewinnr('$')>1 ? 'gt' : ":bn\<enter>". If there are buffers and tabs, it defaults to buffers not tabs.
    – domoremath
    Commented Aug 31, 2017 at 13:38
  • because the ?: expression syntax does not expect several ? Check :h expr1. Will update my answer Commented Aug 31, 2017 at 18:29

Your Answer

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

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