In vim, how can I add a carriage return to the register using setreg?

I have this command in my .vimrc:

vip:normal @g<CR> 

When I set the register 'g' by typing in a buffer like this, it works:

 qg<CR>jq 

If I type: registers, it shows:

 --- Registers --- "g ^Mj 

After that, entering @g causes the carriage to return, and then the cursor moves to the next line. ^ M appears in special color.

However, when I use the setreg command in my vimrc, if I type @g, nothing happens.

 call setreg('g','^Mj') 

If I type: registers, it shows:

 --- Registers --- "g ^Mj 

^ M has no special color.

I have the following in my .vimrc:

 map <CR> :call MyFunction<CR> 

The carriage return that I want to keep in register is to run MyFunction. MyFunction is called fine as long as I fill the buffer manually, and not using setreg.

Where am I wrong? My platform is Linux.

+4
source share
3 answers

Are you looking for "\<cr>" or "\r"

 call setreg('g',"\<cr>j") call setreg('g',"\rj") 

or more simply

 let @g = "\<cr>j" let @g = "\rj" 

For more help

 :h expr-quote :h let-@ 
+8
source

In general, avoid ascii control characters (below 0x20) inside the lines of your vim scripts. When you read your vimrc again if it doesn't have enough lines, vim might detect the wrong line termination pattern (mac?)

Use nr2char(13) to include ^M in the string literal.

 call setreg('g', nr2char(13).'j') 

Otherwise, as sidyll said in his comment, control characters can be entered using CTRL-V in insert mode.

+3
source

The top answer does not always work.
Giving \n did the trick in my case.

 :let @a="foo" :let @a="\nbar" 

Be sure to use double quotes.

0
source

Source: https://habr.com/ru/post/1385112/


All Articles