Running execute g:xx doesn't work.

let g:str="move to right win\t<C-w>h"
let g:temp=escape(matchstr(g:str,'\(\t\)\@<=.*$'),'<')
let g:xx= "normal ".g:temp

execute g:xx

Can anyone explain why?

  • 2
    It's not clear what your question is. What are you expecting it to do?
    – Herb
    Jan 11, 2017 at 4:37
  • hi Herb Wolfe,first there is a mistake above:Move to left. As picture show above,two of three situations work fine(execute command),but execute g:xx is not work
    – tracyone
    Jan 11, 2017 at 4:59
  • Can you post the actual file, and not just a screen shot? It's difficult to tell if that's the entire file, and it's easier to copy and paste text for testing.
    – Herb
    Jan 11, 2017 at 5:03
  • sorry,i have posted the test code.
    – tracyone
    Jan 11, 2017 at 5:07

2 Answers 2

let g:temp=eval('"'. g:temp .'"')


let g:temp=escape(matchstr(g:str,'\(\t\)\@<=.*$'),'<')

Extracting this into a :function:

function! Literalize(string)
    " get already properly escaped sequences out of the way, so we don't double-escape them
    let s = eval('"'. a:string .'"')
    " escape remaining special key sequences
    let s = escape(s, '<')
    let s = eval('"'.   s      .'"')
    return s


The problem was that escape() handles its input° and output strings as a literal-string (as in single quotes ''). So escaping the < in "<C-w>" results in '\<C-w>', not the desired "\<C-w>"/'^W'.

° If the input is given as a double quoted "string", its escape sequences are evaluated by the vimscript parser, before it is passed to escape().


In your first line, the <C-w> is not escaped, so it appears to be matched as a literal string, and the escape function doesn't convert it to the ^W character.

So to get what you want, the first line should actually read

let g:str="move to right win\t\<C-w>h"

In addition, according to the documentation here at sourceforge, the escape command doesn't work how you appear to think. It's going to escape just the '<' character, which does nothing.

  • Is there a vim function can translate this keycode,I mean <c-w> to ^w.
    – tracyone
    Jan 11, 2017 at 6:11
  • Sorry, no idea.
    – Herb
    Jan 11, 2017 at 6:20
  • Yes, eval() can do that 'with a little help' – see my answer. Jan 11, 2017 at 10:35

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.