50

I want to call a function from some elisp code as if I had called it interactively with a prefix argument. Specifically, I want to call grep with a prefix.

The closest I've gotten to making it work is using execute-extended-command, but that still requires that I type in the command I want to call with a prefix...

;; calls command with a prefix, but I have to type the command to be called...
(global-set-key (kbd "C-c m g")
                (lambda () (interactive)
                  (execute-extended-command t)))

The documentation says that execute-extended-command uses command-execute to execute the command read from the minibuffer, but I haven't been able to make it work:

;; doesn't call with prefix...
(global-set-key (kbd "C-c m g")
                (lambda () (interactive)
                  (command-execute 'grep t [t] t)))

Is there any way to call a function with a prefix yet non-interactively?

2 Answers 2

80

If I'm understanding you right, you're trying to make a keybinding that will act like you typed C-u M-x grep <ENTER>. Try this:

(global-set-key (kbd "C-c m g")
                (lambda () (interactive)
                  (setq current-prefix-arg '(4)) ; C-u
                  (call-interactively 'grep)))

Although I would probably make a named function for this:

(defun grep-with-prefix-arg ()
  (interactive)
  (setq current-prefix-arg '(4)) ; C-u
  (call-interactively 'grep))

(global-set-key (kbd "C-c m g") 'grep-with-prefix-arg)
2
  • 47
    It doesn't matter in this particular case, but in general, I'd use (let ((current-prefix-arg '(4))) (call-interactively 'grep)) so that the behavior of subsequent functions called in the commands is not affected. May 27, 2011 at 19:43
  • @cjm why 4? C-u is 4?
    – eugene
    Aug 16 at 6:59
17

Or you could just use a keyboard macro

(global-set-key (kbd "s-l") (kbd "C-u C-SPC"))

In this example, the key combination "s-l" (s ("super") is the "windows logo" key on a PC keyboard) will go up the mark ring, just like you if typed "C-u C-SPC".

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.