Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why :execute is not working as expected in Vim: LearnVimscriptTheHardWay

Tags:

vim

I am trying to learn Vimscript from LearnVimscriptTHW and I came across the use of :execute and :normal.

Example from LVSTHW:

:normal! gg/a<cr>

From book: The problem is that normal! doesn't recognize "special characters" like <cr>. There are a number of ways around this, but the easiest to use and read is execute.

Now when I use :execute "normal! gg/a<cr>" it doesn't work for me. It doesn't search for a(char) in my current file instead of that it just executes gg and than do nothing but if is use :execute "normal! gg/a\r" it works and successfully highlights the char a in my file.

I also tried the below following ways but none of them worked.

:execute "normal! gg/a"<cr>
:execute normal! gg/a<cr>
:execute "normal! gg/a<cr>"<cr>

From the book it seems that execute internally converts <cr> to \r. So, why it is not happening in my case.

like image 320
RanRag Avatar asked Aug 24 '12 19:08

RanRag


2 Answers

You need to escape the <cr> with a backslash: exe "norm! iHello\<cr>World"

like image 115
Conner Avatar answered Oct 02 '22 22:10

Conner


A look at :help :execute may be useful, here. You must escape any <CR> or <ESC> with a backslash when you use them in an expression: \<CR>, \<Esc>… These notations are valid only in mappings, if I understand correctly.

Another option is to input the key "literally":

  • i get into insert mode, unneeded if yoou are on the command line
  • <C-v>
  • <CR>

You'll obtain a single character that looks like ^M and doesn't need to be escaped.

like image 23
romainl Avatar answered Oct 02 '22 21:10

romainl