22

I have a function, and I want to execute a key command, but I get the error Trailing characters:

function! MyFunction()
  if condition
    <C-W><C-W>
  else
    :some_other_command
  endif
endfunction

It doesn't like the <C-W><C-W>

What can I use instead?

2 Answers 2

33

The general answer is to use the :normal command, like

:exe "normal \<C-W>\<C-w>"

The :execute approach is the readable way to get :normal to recognize special characters like control-key combinations. The other approach is

:normal ^W^W

where each^W is one character inserted by typing Ctrl-vCtrl-w.

1
  • If I use ^W in a script than it opens in binary mode. How to avoid that or should I prefer to use :exe? Commented Dec 24, 2019 at 15:04
3

Use feedkeys function. NOTE that ^W is NOT "^" + "W" but actually type "Ctrl-V Ctrl-W". It's a special character.

function! MyFunction()
  if condition
    call feedkeys("^W^W")  
  else
    :some_other_command
  endif
endfunction
1
  • 1
    This answer worked best for me. For some reason: execute "normal c5l" doesn't end up in insert mode. call feedkeys("c5l") does. Thanks man! Commented Oct 10, 2020 at 1:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .