Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs Lisp: evaluate variable in alist

Tags:

elisp

This is probably silly but I don't have enough Elisp knowledge to understand what is going on with respect to quoting and evaluation.

Suppose I have this Elisp code:

(add-to-list 'default-frame-alist '(width . 100))
(add-to-list 'default-frame-alist '(height . 50))

It will result in the expected default-frame-alist value:

((height 50)
 (width 100))

But now if I have this:

(setq my-frame-width 100)
(setq my-frame-height 50)
(add-to-list 'default-frame-alist '(width . my-frame-width))
(add-to-list 'default-frame-alist '(height . my-frame-height))

It will result in -

((height my-frame-height)
 (width my-frame-width))

and, judging from the frame geometry, never evaluates those variables. How do I make the actual values of my-frame-width and height appear in this alist? Do I have too many quotes? But I cannot remove any from the add-to-list evaluations...

like image 521
Laurynas Biveinis Avatar asked Nov 02 '09 22:11

Laurynas Biveinis


2 Answers

Try this:

(setq my-frame-width 100)
(setq my-frame-height 50)
(add-to-list 'default-frame-alist `(width . ,my-frame-width))
(add-to-list 'default-frame-alist `(height . ,my-frame-height))

Using backquote instead of quote allows you to use , to force the evaluation of a parameter.

See the Elisp reference manual. Type C-x info, search for the elisp reference manual, then search for backquote within that.

like image 148
mch Avatar answered Sep 23 '22 01:09

mch


As an alternative to the backquote operator in mch's answer, you can use the cons function. This function will build a cons cell with the first argument as its car and the second argument as its cdr. The dotted pair notation in your code is shorthand for this. So we could rewrite your code this way:

(setq my-frame-width 100)
(setq my-frame-height 50)
(add-to-list 'default-frame-alist (cons 'width my-frame-width))
(add-to-list 'default-frame-alist (cons 'height my-frame-height))

This way, you can quote the symbols you want to appear literally (like width and height) and evaluate the symbols whose values you need (like my-frame-width and my-frame-height). I prefer this method because it is more straight-forward. However, that is certainly a matter of opinion. Here is some more information on cons and list for future reference.

like image 14
A. Levy Avatar answered Sep 23 '22 01:09

A. Levy