Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create interactive elisp function with optional arguments

Tags:

elisp

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)
like image 641
Dov Grobgeld Avatar asked Mar 24 '12 19:03

Dov Grobgeld


People also ask

How do I create a Python function with optional arguments?

You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.

How optional arguments can be used within a function?

Functions with optional arguments offer more flexibility in how you can use them. You can call the function with or without the argument, and if there is no argument in the function call, then a default value is used.

How do you make a function parameter optional?

You can make all the parameters optional in JavaScript by not passing any argument to the function call.

How would I skip optional arguments in a function call?

The only option is to look in the source for the function and replicate the default value. It's not possible to skip it, but you can pass the default argument using ReflectionFunction .


2 Answers

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)))
like image 168
François Févotte Avatar answered Oct 04 '22 06:10

François Févotte


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.

like image 27
Lindydancer Avatar answered Oct 04 '22 06:10

Lindydancer