What is the difference between setq and set-variable in emacs lisp. When should I use setq and when should I set-variable.
Also, as an added convenience, setq permits you to set several different variables to different values, all in one expression. This is exactly the same as using set except the first argument is automatically quoted by setq . (The ' q ' in setq means quote .)
(setq var1 form1 var2 form2 ...) is the simple variable assignment statement of Lisp. First form1 is evaluated and the result is stored in the variable var1, then form2 is evaluated and the result stored in var2, and so forth. setq may be used for assignment of both lexical and dynamic variables.
tab-width is a good example of a buffer-local variable. If a variable is buffer-local, then setq sets its local value in the current buffer and setq-default sets the global default value. If a variable is not buffer-local, then setq and setq-default do the same thing.
set-variable
is an interactive command, meaning that you can type M-x set-variable RET to be interactively prompted for a variable name and value. setq
is not an interactive command, meaning it's only suitable for writing in Emacs Lisp code. Personally, I never use set-variable
in my Lisp code, only interactively, when I want to give a value to a variable that has an immediate effect on my text editing, such as (for example) setting indent-tabs-mode
to t
or nil
.
Another difference is that setq
can set multiple variables at once. For example, in my .emacs file on OS X I have:
(setq mac-command-modifier 'meta mac-option-modifier 'super)
set-variable
can't do that.
setq
is a special form, while set-variable
is an interactive function.
From the docs:
For me, the major use of the
set-variable
command is to suggest variables that I might want to set in my.emacs
file. There are now more than 700 such variables -- far too many to remember readily. Fortunately, you can press<TAB>
after calling theM-x set-variable
command to see the list of variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With