Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs: Universal argument (C-u) in a function

Tags:

I would like to use C-u in a function (for instance, regexp) where calling it with C-u has a different effect. How can I do this in Emacs? The documentation doesn't show how to do this with Emacs Lisp.

(defun test ()
  (interactive)
  (align-regexp)) ; I would like to add the C-u prefix to this.
like image 757
PascalVKooten Avatar asked Oct 10 '12 20:10

PascalVKooten


People also ask

What is universal argument Emacs?

Emacs has a mechanism for a command to have variant behavior if user calls universal-argument 【 Ctrl + u 】. The purpose of universal-argument is: A convenient way to let user pass numerical argument to a command. (What the command do with number argument depends on the command. Usually repeat the command and times.)

What is Emacs prefix argument?

The prefix argument is a pseudo-argument that is automatically available for each Emacs command. When you use a command, its behavior might differ, depending on the value of the prefix argument. You can use 'C-u' to set the prefix argument value to use, and thus affect the command's behavior.


2 Answers

(defun my/test ()
  (interactive)
  (let ((current-prefix-arg 4)) ;; emulate C-u
    (call-interactively 'align-regexp) ;; invoke align-regexp interactively
    )
  )

Hope that helps.

like image 91
Sean Perry Avatar answered Oct 25 '22 00:10

Sean Perry


I arrived here looking for a way to detect if my function had been called with C-u. This is how you do it:

(defun my-function ()
 (interactive)
  (if (equal current-prefix-arg nil) ; no C-u
   ;; then
    (message "my-function was called normally")
   ;; else
    (message "my-function was called with C-u")))

What the original poster was asking is how to call another function with C-u, from inside his/her function. I post this as a clarification to @codyChan's comment above, in the hope that it might help others.

like image 45
kotchwane Avatar answered Oct 25 '22 00:10

kotchwane