Skip to content

Repeating Commands in Emacs

by mickey on July 15th, 2011

Repeating a command you just carried out is a surprisingly useful thing to do, yet most people are completely unaware that bound to C-x z is Emacs’s repeat command.

Like the . command in vi, the repeat command will repeat the last action, skipping any input events (like character input.)

To save you from press the rather awkward keybind every time you want to repeat something, you can repeatedly press z after your first invocation to call repeat. Of course, you can also use the universal argument to repeat the command N number of times.

As I mentioned in my article on Mastering Keybindings in Emacs, you can also repeat (and edit!) complex commands like query-replace-regexp by typing C-x M-: or C-x M-ESC.

4 Comments
  1. You’ve just made my day.

  2. jpkotta permalink

    I made this from an idea on an Emacs news group. The docstring explains what it is. I don’t use it too much yet, so there may be bugs. Hopefully the formatting doesn’t get messed up in this post.

    ;; From http://groups.google.com/group/gnu.emacs.help/browse_thread/thread/44728fda08f1ec8f?hl=en&tvc=2
    (defun make-repeatable-command (cmd)
      "Returns a new command that is a repeatable version of CMD.
    The new command is named CMD-repeat.  CMD should be a quoted
    command.
    
    This allows you to bind the command to a compound keystroke and
    repeat it with just the final key.  For example:
    
      (global-set-key (kbd \"C-c a\") (make-repeatable-command 'foo))
    
    will create a new command called foo-repeat.  Typing C-c a will
    just invoke foo.  Typing C-c a a a will invoke foo three times,
    and so on."
      (fset (intern (concat (symbol-name cmd) "-repeat"))
            `(lambda ,(help-function-arglist cmd) ;; arg list
               ,(format "A repeatable version of `%s'." (symbol-name cmd)) ;; doc string
               ,(interactive-form cmd) ;; interactive form
               ;; see also repeat-message-function
               (setq last-repeatable-command ',cmd)
               (repeat nil)))
      (intern (concat (symbol-name cmd) "-repeat")))
    
  3. jsled permalink

    Also, “C-x (“, and the macro stuff for more complex sequences.

    • mickey permalink

      Hi. Yeah, but macros sort of deserve their own post given how complex a subject it is.

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS