5

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.

renick
  • 667
  • 1
  • 6
  • 16
  • 2
    How did you input ^M in `call setreg('g','^Mj')`? Did you use ctrl-v ctrl-m? Or just typed a caret and a M? – sidyll Dec 07 '11 at 15:21
  • caret M... ah... i had tried typing caret v caret m and that failed. I didn't realize you actually have to type ctrl-v ctrl-m in insert mode, not write the string "^V^M". Thanks for that! Actually hitting those keys worked. The register is set properly. I appreciate your help. – renick Dec 07 '11 at 15:52
  • ctrl-v is what I normally use to get `^M`. – overthink Dec 07 '11 at 16:35

3 Answers3

10

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-@
Peter Rincker
  • 39,385
  • 8
  • 64
  • 92
4

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.

Benoit
  • 70,220
  • 21
  • 189
  • 223
1

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.

eli
  • 1,516
  • 1
  • 17
  • 22
Aaron
  • 11
  • 1
  • \n actually saved me when I needed an enter hit at the end of my macro. \n at the end of macro gives you ^J . while \ and \ and \r all result in ^M^J – Possum Gallo Oct 07 '20 at 10:11