Emacs Find of the Day: Repeating Commands

One thing that I love about Emacs is that even after 20 years, I’m finding new (old, in actuality) functionality that makes my life better.

Today’s example is repeat-complex-command, which is normally bound to ctrl-x ESC ESC, as noted on the emacs wiki. The problem in my world is that I’m also using CUA mode, from the ergoemacs library, which redefines ctrl-x to do cuts (as in cut, copy, paste).

Normally that doesn’t cause an issue, since if you don’t have a region marked, then ctrl-x is apparently ignored by ergoemacs and is delegated to the default behavior, in which case ctrl-x ESC ESC brings up the previous command in the echo area, ready to be edited.

However, what has arisen as a nuisance in my experience is when I’ve done a search and replace in one region, then want to do a similar but not identical search and replace in a different region, such as renaming variables in two methods.

Normally I’d mark the first method, run search and replace (query-replace or query-replace-regexp), then go to the second method and mark it. At that point I’d like to bring up the previous search-and-replace and modify the command, but when I hit ctrl-x, the currently-marked region (the second method in this example) is cut, per behavior from ergoemacs.

The fix is to map a different key, in my case alt-j alt-j (the mnemonic being that the keys repeat) mapped to repeat-complex-command, per this snippet from my .emacs file(s):

(define-key global-map (kbd "M-j") jep:keymap)
(define-key global-map (kbd "C-j") jep:keymap)

;; CUA settings muck up ctrl-x, so use an alternative, alt-j alt-j:
(define-key jep:keymap (kbd "M-j") 'repeat-complex-command)

Yes, I map both alt-j and ctrl-j as equivalent keys that define my keymap, making it simpler when I have shortcuts that are prefixed with alt- and ctrl-. So alt-j alt-j flows better, as does ctrl-j ctrl-l (which inserts logging statements, if you’re wondering).

All of this is available at my github repository.

But wait — there’s more: the second nugget of the day is that after running repeat-complex-command, the echo area will display the previous command, of course. But then running alt-p will bring up the command prior to that, and alt-p the command prior to that one, etc. On the other hand, and in the opposite direction, alt-n moves forward through the list of commands.

I hope this helps, and I plan to post more about Emacs and what I find therein.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s