← Back to Archives

Easy replacing of ^M in emacs

berkeley

Sorry to get all geeky on you, but...

Lately, I've had to do a lot of replacing ^M characters in files and pasted text in emacs. All seasoned emacs users know that this is easily done by doing the following at the beginning of a file:

M-x replace-string RET C-q C-m RET C-q C-j RET

However, that can get really tiring if you have to do it alot.

I looked for an alias, shortcut or something that would let me do this with fewer keys, but no luck. Finally, I realized that the term I was looking for in my search was a keyboard macro. That is, an emacs keyboard macro can be defined to do this and then I can set a key combination to do it. Here's how:

  1. To start recording a macro type C-x (
  2. Do the things you want to record in the macro... for example, I typed the key combination above including going to the beginning of the file. (which is: M-< M-x replace-string RET C-q C-m RET C-q C-j RET)
  3. To stop recording the macro type C-x )
  4. Give the macro a name by typing: M-x name-last-kbd-macro
  5. Open your .emacs file: C-x C-f ~/.emacs
  6. Insert the macro text into the file by typing the following followed by the name you gave the macro above: M-x insert-kbd-macro
  7. You can bind this to a key combination using a global-set-key definition right under the macro definition.

Here's what I added to my .emacs file to map C-c m to replacing all the ^M characters in the current buffer:

;;Replace all freakin' ^M chars in the current buffer (fset 'replace-ctrlms [escape ?< escape ?% ?\C-q ?\C-m return ?\C-q ?\C-j return ?!]) (global-set-key "\C-cm" 'replace-ctrlms)