vimtricks.wiki Concise Vim tricks, one at a time.

How do I insert an actual newline in a substitution replacement, and why does backslash-n not work?

Answer

s/pattern/\r/

Explanation

In Vim substitutions, \r in the replacement string inserts a line break, creating a new line. Many users try \n instead, which is surprising: in the replacement, \n inserts a literal NUL byte (displayed as ^@) rather than a line break. This is one of Vim's most common regex gotchas.

How it works

The asymmetry between the two sides of a substitution:

  • Search pattern (left side): \n matches a newline in the buffer
  • Replacement string (right side): \r inserts a line break; \n inserts a NUL character

This is counterintuitive because most tools use \n consistently for newlines. Vim's internal line representation is the source of this distinction.

Example

Split a comma-separated list onto separate lines:

apple,banana,cherry

Run:

:%s/,/\r/g

Result:

apple
banana
cherry

Tips

  • The reverse (joining lines) uses \n in the search side correctly: :%s/\n/,/g joins all lines with commas
  • To insert a newline before a matched word: :s/\<TODO\>/\r&/g& expands to the whole match, \r prepends a newline
  • To break a long line at each comma and keep the comma: :s/,/,\r/g
  • In Neovim and recent Vim, \n in the replacement may work on some platforms as a line break, but \r is the portable and reliable choice for all Vim versions

Next

How do I open the directory containing the current file in netrw from within Vim?