Quick post today, so let's get to it - this will save you a bunch of work if you're doing something interesting with lines of text.
Often, I find myself with a short list of strings, maybe something like this:
Bilbo
Frodo
Gandalf
And I want to turn it into this:
case Person::Bilbo: return "Bilbo";
case Person::Frodo return "Frodo";
case Person::Gandalf: return "Gandalf";
There are many tools that can help. If you're already up and running in emacs, here are a couple.
In emacs, F3 and F4 can be used for keyboard macros. Basically recording and playback of keystrokes and commands.
Typically you would do something like this:
M-w
).C-v
).Now, keep pressing F4, and the lines will be touched up as you go.
These are very powerful and flexible, but unfortunately keyboard macros can run quite slowly sometimes. You might be fighting a specific mode's motion as well when you really cared for something different.
Another thing you might run into is pressing the wrong key in the middle of the macro and then having to undo and start over. For example, with my key bindings, C-c
for copy (instead of M-w
) will cause an error during playback, so I need to be careful and catch myself before doing that.
What else can we try?
Line replacement is very, very fast, but you need to use regular expressions for this sort of thing, and I'm not smart enough to have them memorized and too lazy to look at the reference.
Fear not! Here's a quick recipe. You need only change the
Alt+X toggle-case-fold-search
M-x replace-regexp
^.+$
case Person::\&: return "\&";
Alt+X toggle-case-fold-search
Note how I'm using \&
to replace each whole line. For simple lines, this works great.
You may want to touch up the regular expression for slightly different matches. It's not as flexible as keyboard macros, but it's pretty good.
Also, note that I invoke toggle-case-fold-search
before and after. If you don't do this, the regular expression is considered case insensitive (because there are no uppercase characters), and the replaced text will come out with unexpected case changes.
Enjoy your altered text!
Tags: emacs