Jonathan
Jonathan

Reputation: 539

how do I conditionally bind a key to do two different actions in vim?

I'd like to bind <C-n> to do one of two things in Vim depending on the state of the editor. If I have tabs open I'd like it to switch to the next tab, otherwise I'd like it to open a new tab. I've looked at the help and come up with this, but it's not working, and I'm a viml noob.

function TabBind()
    if range(tabpagenr()) < 2
        nno <C-n> :tabnew
    else
        nno <C-n> :tabn
    endif
endfunction

Is this possible? and if so how?

Upvotes: 1

Views: 112

Answers (2)

Luc Hermitte
Luc Hermitte

Reputation: 32966

You can also define such simple thing as one-liners. For instance I have the following mapping to go to the next diff (in diff mode), or to the next error message otherwise.

nnoremap <expr> <silent> <F3>   (&diff ? "]c:call \<sid>NextDiff()\<cr>" : ":cn\<cr>")

In your case, your mapping will be:

nnoremap <expr> <silent> <c-n> (tabpagenr('$') < 2 ? ":tabnew\<cr>" : ":tabn\<cr>")

Upvotes: 1

buff
buff

Reputation: 2053

The idea is that you map a function that decides what to do on the fly.

function TabBind()
    if tabpagenr('$') < 2
        tabnew
    else
        tabn
    endif
endfunction

nno <C-n> :call TabBind()<cr>

Upvotes: 3

Related Questions