1

Recently I found this question: Is it possible to map one key to two commands, doing 2nd command only if first fails

It's working well, but I'd like it to work this way: when Alt-l is pressed, do ctrl-w l, but only when there is another window to the right. Otherwise, do gt. Same applies to alt-h.

enter image description here

Is this even possible? I can't find any {expr}'s that would could allow me to do such things

1

You can use winnr() function to get the current window number and then try to execute your mapping <c-w>l in this case. If the window number doesn't change then execute your other mapping, gt.

function! s:trywincmd(win, other)
  let winnr = winnr()
  execute 'silent! normal! ' . a:win
  if winnr() == winnr
    execute 'silent! normal! ' . a:other
  endif
endfunction

nnoremap <silent> <c-w>l :call <SID>trywincmd("\<lt>c-w>l", "gt\<lt>c-w>t")<cr>
nnoremap <silent> <c-w>h :call <SID>trywincmd("\<lt>c-w>h", "gT\<lt>c-w>t")<cr>

Note: Because this is a mapping we need escape < as the <lt> key-code.

For more help see:

:h keycodes
:h winnr()
:h execute
:h :normal
  • Works wonders, thanks! One improvement I'd make: nnoremap <silent> <c-w>h :call <SID>trywincmd("\<lt>c-w>h", "gT\<lt>c-w>b")<cr> so that when going left cursor starts from window to the right – BPawelski Sep 9 '17 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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