The Universal Argument

Over at Wisdom and Wonder, Grant tells us how to move forward several spaces in the minibuffer. That’s just 【Ctrl+u 1 0 0 Ctrl+f】, of course but Fuco (who wowed us by doing the last VimGolf in Emacs challenge in only 5 keystrokes) points out that really all you need is 【Ctrl+1+0+0+f】. I’ve been seeing this misunderstanding a lot lately, both in comments to my posts and in other Emacs-oriented blogs, so perhaps it’s worth mentioning how the Universal Argument works.

The most useful thing to know is that you can give numeric arguments to commands by holding down 【Ctrl】 or 【Meta】 and typing the digits. That’s why Fuco’s method works. Notice how much more convenient it is: you merely hold down the 【Ctrl】 key and type the numeric argument and command. The same thing works with the 【Meta】 key. To delete the next five words, type 【Meta+5+d】. Much easier than 【Ctrl+u 5 Meta+d

The next thing to know is that if you don’t type any digits after 【Ctrl+u】 the argument count is increased by a factor of 4. Thus 【Ctrl+u+p】 will move the point up four lines and 【Ctrl+u+u+p】 will move the point up 16 lines and so on.

Finally, the Universal Argument can act as a flag that tells the command to use an alternative behavior. Usually, the command will use

(interactive "P")

to get this behavior. Here’s an example from my init.el file:

(defun jcs-datetime (arg)
  "Without argument: insert date as yyyy-mm-dd
With C-u: insert time
With C-u C-u: insert date and time"
  (interactive "P")
  (cond ((equal arg '(4)) (insert (format-time-string "%T")))
        ((equal arg '(16)) (insert (format-time-string "%Y-%m-%d %T")))
        (t (insert (format-time-string "%Y-%m-%d")))))

Notice that in this case the function sees the argument as (4), (16), and so on. Of course, unless you’re writing Elisp code you don’t have to worry about this case—the function writer has taken care of it for you and you just need to know that you need one or more 【Ctrl+u】 to get the desired alternative behavior.

This entry was posted in General and tagged . Bookmark the permalink.