Search code examples
elisp

Testing user-set variable for equality in ELisp


I am new to Emacs Lisp and changing some code in mu4e-send-delay. I want to test whether the user set a variable to a value, e.g. in the scratch buffer:

(setq mu4e-sent-messages-behavior 'delete)
delete

These three tests return false:

(eq 'mu4e-sent-messages-behavior 'delete)
nil
(equal 'mu4e-sent-messages-behavior 'delete)
nil
(equal 'mu4e-sent-messages-behavior "delete")
nil

And this one returns true, but with the member function for lists:

(if (member mu4e-sent-messages-behavior '(delete)) t nil)
t

If the user keeps the setting at the default set in the code:

(defcustom mu4e-sent-messages-behavior 'sent
...
)

then member also fails:

(when (member mu4e-sent-messages-behavior '(sent)) t nil)
nil

What is wrong with my tests, and how can I test for the value of a variable set by the user?


Solution

  • Don't quote the variable name when passing it to eq:

    (eq mu4e-sent-messages-behavior 'delete)
    

    The problem with this piece of code:

    (when (member mu4e-sent-messages-behavior '(sent)) t nil)
    

    is that when will either return nil (if the condition is false) or the last value of the body (if the condition is true), which in this case is nil - so this piece of code will always return nil. Use if instead of when, and you should see it returning t.