Thursday, July 2, 2009

Search and replace line feeds using emacs

As an avid emacs user for a decade plus, I am a little embarrassed to confess that I did not know for the longest time how to search for or replace line feed (newline) characters.

If you are only searching for run-of-the-mill ASCII strings such as abc, you just type C-s (control-S), and then the characters, and hit return.

Unfortunately, if your search string includes a line feed character, e.g., abc followed by a newline, I have some good news and some bad news for you.

The good news is that you use the same shortcut (C-s) just like you would normally to search for anything else.

The bad news is that the representation of what emacs understands to be a newline is not that intuitive ... even to geeks. Instead of something like \n which may mean something to developers, you need to enter C-q C-j (Control-Q, Control-J) for each line feed in the search string.

C-q is the shortcut for the quoted-insert command. The character you type immediately after C-q is escaped, i.e., its normal function is suppressed. C-j is the line feed character. Why the letter j, you ask? It turns out that the line feed character is represented by the decimal value 10 in the ASCII table, and j is the 10th letter in the English alphabet. Similarly, if you are searching for the Tab instead of the newline character, use C-q C-i to denote the Tab character.

If you want to replace occurrences of a string that includes one or more line feeds, the method is similar. Use the usual command replace-string or query-replace(M-%). Enter C-q C-j where you would expect to type the new line.
M-x replace-string (Hit return) abcC-qC-j (Hit return) def (Hit return)


Anonymous said...

That's good to know...
I'll lookup that in VIM help immediately :)

btw: that "\n" in italics looks nearly as "|n".

Rajarshi Tiwari said...

good work was really interesting post.

keep it up.


Stephen said...

I didn't know you ran emacsOS. :)