tags:

views:

511

answers:

3

Hello!

I am trying to have a dynamic prompt from my elisp function. I want something like replace-regexp where it will show you the last regexp entered. I tried (interactive (concat "sab" "bab"))) that doesnt work!

I also tried message like format (interactive "s %s" last-used-regexp)

and that doesn't work! Anyone know how to do this?

Thank you!

+8  A: 

M-x find-function is your friend. It will tell you how anything in emacs works by showing you the source code. Using it, I find that query-regexp-replace calls query-replace-read-args which calls query-replace-read-from which calls read-from-minibuffer using a prompt created from the last used regexp, which is saved in the dotted pair query-replace-defaults.

So:

(defun my-func ()
  "Do stuff..."
  (interactive)
  (read-from-minibuffer "Regexp? " (first query-replace-defaults)))

is a command that throws up a prompt with the last entered regexp as the default.

andrew
+2  A: 

Use a variable for input history, and interactive with a list:

(defvar my-func-history nil)

(defun my-func (str)
  (interactive (list (read-from-minibuffer "Input string: " (car my-func-history) nil nil 'my-func-history)))
  (insert str))

If you don't want the last value entered in there initially, change the (car my-func-history) to nil. You can of course up/down arrow to go through the history at the prompt.

scottfrazer
A: 

Funny how the answer that is most approve does not actually work: I get this error: read-from-minibuffer: Symbol's function definition is void: first.

The second, less popular answer actually worked, as well as being less condescending.

fvdfvfd
Yeah, the call to `first` needs a `(require 'cl)`, but the answer was hardly "condescending"! The error aside, it was appropriate to the question, and provided useful additional information to anyone reading this who wasn't aware of `find-function`.
phils
In fact `first` is just an alias for `car`, so simply use `(car query-replace-defaults)` instead to make that example work without loading `cl`. That said, scottfrazer's answer is still the better one for most purposes, as it shows how to generate a function argument interactively, which is usually what you would want to do here.
phils