Setq Versus Setopt

Like most people, I use setq to set user options in my Emacs configuration. It’s the canonical way of setting a variable in just about any Lisp. But, as Bozhidar Batsov says, it’s not always the best way of setting a configuration variable in Emacs. He suggests using setopt instead.

It’s more than just a convention. The setopt macro does a bit more than setq. In particular, it can arrange to call a setter function when you set a configuration variable. This can be useful for checking the prospective value or for performing some system adjustment when a parameter changes.

I’ve known about this for a while but my problem has always been when you need to use setopt instead of setq. Batsov’s recommendation is to use setopt unless the variable is not defined in terms of defcustom. That’s all very well but how do you know which variables are which? The online documentation isn’t much help so the best policy is probably to assume that any variable in your configuration should be set with setopt unless you have reason to believe otherwise.

Batsov says that setopt will work with regular (non-defcustom variables) as well but that it won’t be as efficient as setq. Really, who cares? The setopt macro will almost certainly not be in a loop so any inefficiency won’t matter much. Plus, as I always say, if you’re using Emacs correctly, you won’t be restarting it very often in any event.

Take a look at Batsov’s post to get an idea of the difference between setq and setopt. It probably won’t help you decide which to use but at least you’ll know what each does.

Update [2025-04-07 Mon 13:42]: In the Emacs subreddit, Batsov notes that an easy way to discover which variables are customizable is to check the documentation with describe-variable. Variables that are customizable will have the notation “You can customize this variable.”

This entry was posted in General and tagged . Bookmark the permalink.