Thursday·22·September·2011
Emacs Macros: Repeat on Steroids //at 16:06 //by abe
vi users have their .
(dot) redo command for repeating
the last command. The article Repeating Commands in Emacs in Mickey Petersen’s blog Mastering Emacs explained
Emacs’ equivalent for that, namely the command repeat
, by
default bound to C-x z
.
I though seldomly use it as I mostly have to repeat a chain of commands. What I use are so called Keyboard Macros.
For example for the CVE-2011-3192 vulnerability in Apache I added a line like
Include /etc/apache2/sites-common/CVE-2011-3192.conf
to
all VirtualHosts.
So I started Emacs with all the relevant files: grep
CVE-2011-3192 -l /etc/apache2/sites-available/*[^~] | xargs emacs
&
To remove those “Include” lines again M-x flush-lines
is
probably the easiest way in Emacs. So for every file I had to call
flush-lines with always the same parameter, save the buffer and then
close the file or — in Emacsish — “kill” the buffer.
So while working on the first file I recorded my doing as a keyboard macro:
C-x (
- Start recording
M-x flush-lines<Enter>CVE-2011-3192<Enter>
- flush all lines which contain the string “CVE-2011-3192”
C-x C-s
- save the current buffer
C-x C-k<Enter>
- kill the current buffer, i.e. close the file
C-x )
- Stop recording
Then I just had to call the saved macro with C-x e
. It
flushed all lines, saved the changes and switched to the next
remaining file by closing the current file with three key-strokes. And
to make it even easier, from the second occasion on I only had to
press e
to call the macro directly again. So I just
pressed e
for a bunch of time and had all files edited.
(In this case I used git diff
afterwards to check that I
didn’t wreck anything by half-automating my editing. :-)
Of course there are other ways to do this, too, e.g. use
sed
or so, but I still think it’s a neat example for
showing the power of keyboard macros in Emacs. More things you can do
with Emacs Keyboard Macros are described in the EmacsWiki entry Keyboard Macros.
And if you still miss vi’s .
command in Emacs, you can
use the dot-mode, an Emacs mode currently maintained by Robert Wyrick
which more or less automatically defines keyboard macros and lets you
call them with C-.
.
Tagged as: Apache, CLI, CVE, CVE-2011-3192, dot-mode, Emacs, EmacsWiki, git, macro, Other Blogs, redo, repeat, vi, xargs
// write a comment // comments off