Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs Lisp: How to use interactive (for conditional arguments)?

Tags:

elisp

I want to ask a second question to the user depending on the answer to the first one.

(defun something (a b)
  (interactive
   (list
    (read-number "First num: ")
    (read-number "Second num: ")))
  (message "a is %s and b is %s" a b))

So I need a way to test the entry values :

(defun something-else (a &optional b)
  (interactive
   (list
    (read-number "First num: ")
    (if (< a 2)
        (read-number "Second num: "))))
  (message "a is %s" a))

But

if: Symbol's value as variable is void: a

Question : How can I use interactive in a really interactive way?

like image 978
yPhil Avatar asked Oct 27 '25 06:10

yPhil


2 Answers

Interpret the form in interactive as kind of subprogram which delivers the list of argument values as return value. You can have local variables there with the help of a let-like form.

(defun something-else (a &optional b)
  (interactive
   (let* ((a-local (read-number "First num: "))
          (b-local (when (< a-local 2)
             (read-number "Second num: "))))
     (list a-local b-local)))
  (message "a is %s, b is %s" a b))

In the above example a-local and b-local are variables with names of your choice wich are local to the enclosing let*-form. The star in let* means that the evaluated expression (read-number "First num: ") for a-local is assigned to a-local before the expression (when (< a-local 2) (read-number "Second num: ")) for b-local is evaluated.

like image 124
Tobias Avatar answered Oct 30 '25 06:10

Tobias


(defun xtest (a &optional b)
  (interactive
   (let (a b)
     (setq a (read-number "First: "))
     (if (< a 2)
         (setq b (read-number "Second: ")))
     (list a b)))

  (message "a is %s b is %s" a b))
like image 26
knarf Avatar answered Oct 30 '25 06:10

knarf