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

2.2k Views Asked by At

I have this command in my .vimrc:

vip:normal @g<CR>

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

qg<CR>jq

If I type :registers, it shows:

--- Registers ---

"g   ^Mj

After that, typing @g results in a carriage return and then the cursor moves to the next line. The ^M appears in a 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

The ^M is not in a special color.

I have the following in my .vimrc:

map <CR> :call MyFunction<CR>

The carriage return I want to store in the register is to run MyFunction. MyFunction is called perfectly as long as I fill the buffer manually rather than using setreg.

Where have I gone wrong? My platform is Linux.

3

There are 3 best solutions below

0
Benoit On

In a general rule avoid ascii control characters (below 0x20) inside the lines of your vim scripts. When you read your vimrc again if it has not enough lines, vim could detect a bad line termination pattern (mac?)

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

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

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

0
Peter Rincker On

You are 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-@
1
Aaron On

The top answer doesn't always work.
Providing \n did the trick in my case.

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

Make sure to use double quotes.