The Curious Case of Newline in Vim

Ankur Gupta
Jul 24, 2017 · 2 min read

There is a myriad of text editors out there. There are editors for people who love to live in the terminal, and for those who (for some reason) find joy in using GUI. For the former category, Vim remains the most popular text editor. (Don’t believe me! Believe this annual worldwide developer survey by Stack Overflow).

The more you work in Vim, the more interesting bits it keeps throwing at you. I encountered one such interesting use case in Vim recently.

Vim offers very powerful search and replace commands even without any customization. You can replace a single match, all matches in a line, all matches in a range of lines, or all matches in the entire document. There’s just so much that you can do with the single :%s/foo/bar/g command.

But what is interesting here is that you have to use different characters for searching a newline and for replacing a character with a newline. That means that a newline is represented by different characters depending on if you want to use it in foo or in bar in the reference of the above command.

While searching, the newline is represented by \n, but while replacing, a newline is represented by a \r. Even numerous Google searches don’t give you any meaningful info on the reasons of this behaviour. Most of the people just tell you that this happens — they fail to explain why.

But a user in this SO answer very modestly points to the reason.

The characters in the foo part, i.e., while searching work the same way that they are expected to:

\0 — Null character

\n — New Line

\r — Carriage Return.

However, \0 already had a reserved use in regex replacements — it means “the whole matched pattern”. So you cannot use \0 to mean a null character, hence \n was used in it’s place. Now something had to represent the newline character, so \r was used in it’s place.

As for carriage return, I guess it wasn’t taken care of. Who would anyway want to insert just a carriage return intentionally?

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade