12

How do you write an elisp function, that should be bound to a key-press, that works without prompting by default, but when preceeded by Ctrl-u prompts the user for an argument. Something similar to (which is wrong syntax, but I hope you get the idea)?

 (defun my-message (&optional (print-message "foo"))
   (interactive "P")
   (message print-message))
 (global-set-key "\C-c\C-m" 'my-message)

3 Answers 3

22

The following use a feature of interactive that allows you to use code instead of a string. This code will only be executed when the function is called interactively (which makes this a different answer compared to the earlier answer). The code should evaluate to a list where the elements are mapped to the parameters.

(defun my-test (&optional arg)
  (interactive (list (if current-prefix-arg
                         (read-from-minibuffer "MyPrompt: ")
                       nil)))
  (if arg
      (message arg)
    (message "NO ARG")))

By using this method, this function can be called from code like (my-test) or (my-test "X") without it prompting the user for input. For most situations, you would like to design functions so that they only prompt for input when called interactively.

Sign up to request clarification or add additional context in comments.

2 Comments

When using interactive you don't need the &optional
It is designed to work both when called interactively and from lisp. In the latter case &optional is needen.
5

Following the same kind of implementation as your example, you could do something like this:

(defun my-message (&optional arg)
  (interactive "P")
  (let ((msg "foo"))
    (when arg
      (setq msg (read-from-minibuffer "Message: ")))
    (message msg)))

Comments

4

If you just want to use the function as an interactive one, this code is all you need:

(defun my-message (&optional ask)
  (interactive "P")
  (message (if ask
               (read-from-minibuffer "Message: ")
             "foo")))

1 Comment

you don't need the &optional there, in fact I am not sure it is appropriate

Your Answer

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.