[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: (interactive) and &optional
From: |
Philip Kaludercic |
Subject: |
Re: (interactive) and &optional |
Date: |
Thu, 23 Mar 2023 19:20:29 +0000 |
Dr Rainer Woitok <rainer.woitok@gmail.com> writes:
> Greetings,
>
> In an attempt to write a function with and optional argument which is
> both, callable from Lisp and via "M-x", I ran into some unexpected (by
> me) problems. Consider the following function:
>
> (defun fun (&optional arg)
> (interactive "Sarg: ")
> (message "%s:%s.\n" 'val (symbol-name arg)))
This would have done the same thing:
(message "val: %s.\n" arg)
>
> Calling "M-: (fun 'a)" returns
>
> "val:a.
> "
>
> including the double quotes, while calling "M-x fun" and then typing "a
> RET" at the prompt returns
>
> val:a.\n
That is because `message' returns the message as a string when
evaluated, and using M-: you first have `message' do it's thing, then
return the string it printed (using the printed representation for a
string, which includes queotes). You can verify this by looking up the
message log using C-h e.
> without double quotes. Apart from perhaps the double quotes, this is
> what I had expected. Likewise, calling "M-: (fun)" returns
>
> "val:nil.
> "
>
> as expected, while calling "M-x fun" and then just typing "RET" at the
> prompt returns
>
> val:.\n
>
> that is, an empty symbol or string.
Right.
> Am I really expected in a function that is both, callable from Lisp and
> via "M-x", to code something along the lines of
>
> (cond ((or (null arg) (string-empty-p arg)) 'default-val)
> (arg))
>
> to check whether or not an optional argument has been passed? Are there
> any more elegant ways to achieve this?
The interactive spec can either take a string as you did here, or an
expression that will be evaluated to generate a list of arguments. So
the following will read a string (not a symbol), check if the string is
empty (I don't think the nil check is necessary) in which case the
symbol `default-var' is returned, otherwise we use `intern' to request a
symbol with the name of whatever we just queried the user:
--8<---------------cut here---------------start------------->8---
(defun fun (&optional arg)
(interactive (list (let ((name (read-string "arg: ")))
(if (string-empty-p name)
'default-val
(intern name)))))
(message "val: %s.\n" arg))
--8<---------------cut here---------------end--------------->8---
> Any pointers welcome :-)
>
> Sincerely,
> Rainer
--
Philip Kaludercic
Re: (interactive) and &optional, Emanuel Berg, 2023/03/23
Re: (interactive) and &optional, Jean Louis, 2023/03/24