Emaximus Ep 1: Creative use of query-replace

When it comes to writing code, having the right tool for the job can enhance your productivity many times over. This is the first episode in a series on improving your fluency with the Emacs editor. This is NOT a post/series on why you should use Emacs over VIM, or why you should use Emacs over Eclipse / Visual Studio / Notepad / [your favorite editor].

This is also not a “Getting Started” guide for emacs. There are plenty of those already, so I’m not going to reinvent the wheel. Rather, this draws on my own personal experience with Emacs over the past 2 years of using it. I don’t claim to be an expert, and I’m always open for suggestions/alternatives/improvements regarding the material I post! That having been said, let’s dive in!

Today’s topic: Creative use of search and replace!

You already know M-% will invoke search and replace. You also know that C-q C-[some key representing a non-ascii character or control character] will insert characters that correspond to special keys/character codes (this is called “quoted-insert”).

Now, let’s say you are editing an HTML file, and it looks like the following:

<html><head><title>This is a web page!</title></head><body>Lorem ipsum text goes here!</body></html>

This is ugly, and furthermore, we can’t do automatic indenting (C-M-\) because the code is all on one line! What to do? Let’s combine our knowledge of search and replace with quoted-insert!

  1. Use M-< to go to the beginning of the file.
  2. M-% to enter search and replace.
  3. Use the < symbol for the search string.
  4. For the replace string, type C-q C-j (newline character), and then the < symbol.
  5. Now Emacs will step through each occurrence of < and ask you to replace. Press y or n where needed to put the appropriate tags on a new line!

Now we can run C-M-\ on the file, and (depending on your indentation settings) get the following result:

<html>
  <head>
    <title>This is a web page!</title>
  </head>
  <body>
    Lorem ipsum text goes here!
  </body>
</html>