coordinate
coordinate

Reputation: 16274

How to build list with defvar in emacs

I used code like this:

(defvar my-defvar "test")
(completing-read "input: " '("1" "2" my-defvar))

Then M-x eval-region. I got "1", "2", my-defvar in minibuffer.

My question is how to convert my-defvar to string in a list.

Upvotes: 6

Views: 1614

Answers (2)

MGwynne
MGwynne

Reputation: 3522

my-defvar isn't being evaluated as a variable, it's being interpreted as a symbol.

See Emacs Lisp: evaluate variable in alist.

So:

(defvar my-defvar "test")
(completing-read "input: " `("1" "2" ,my-defvar))

should work.

Update: A more appropriate solution is given in @Lindydancer's answer, but I leave this here for reference.

Upvotes: 6

Lindydancer
Lindydancer

Reputation: 26144

In Lisp, the ´-symbol will quote the rest of the expression. This means that the value will be the expression exactly as it is written, function calls are not evaluated, variables are not replaced with it's value etc.

The most straight-forward way is to use the function list that creates a list of elements, after evaluating it's arguments, for example:

(completing-read "input: " (list "1" "2" my-defvar))

Of course, you could also use the backquote syntax, as suggested in another answer. This allows you to quote a complex expression but unquote (i.e. evaluate) parts of it. However, in this simple case I don't think it's the right tool for the job.

Upvotes: 12

Related Questions