Emacs Lisp: evaluate variable in alist

不问归期 提交于 2019-11-26 19:36:37

问题


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...


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/1664202/emacs-lisp-evaluate-variable-in-alist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!