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?

asked May 27, 2011 at 18:30

2 Answers 2

81

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)
answered May 27, 2011 at 18:43
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@cjm why 4? C-u is 4?
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".

answered Jul 27, 2012 at 12:57

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.