Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

emacs lisp call function with prefix argument programmatically

Tags:

emacs

elisp

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?

like image 218
mgalgs Avatar asked May 27 '11 18:05

mgalgs


2 Answers

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) 
like image 125
cjm Avatar answered Oct 12 '22 18:10

cjm


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".

like image 24
yPhil Avatar answered Oct 12 '22 18:10

yPhil