2022-04-04 Warning about trying to setq a non-existent variable

Some time ago I wrote about how I changed a value of one of Emacs’ internal variables to get the behavior I needed. As I mentioned, I submitted a bug report (apparently, I’m in a minority needing this, and I don’t expect it to be fixed in near future – but that doesn’t bother me much, since I have the workaround in place anyway).

There is one thing that does bother me, though. If this bug gets solved at some point in time, and the variable js--declaration-keyword-re disappears (and some other one – without the two dashes – is created in its place), how do I know that? I skim through the Emacs changelog when I compile a newer version, but I do not read it in all detail, so it would be easy to miss it. Then, my customization would stop working all of a sudden. How do I avoid that?

One way to do that would be to have something like setq, but reporting an error (or at least a warning) when the variable the user is trying to set doesn’t exist (or is not a special variable). I asked if there is such a feature in Emacs, and apparently there’s not. Elisp being a Lisp, though, adding it (as a macro) is easy.

(defmacro setq-if-exists (variable value)
  "Set VARIABLE to VALUE. Error out if VARIABLE is not special."
  `(if (special-variable-p ',variable)
       (setq ,variable ,value)
     (error (format "Variable %s does not exist" ',variable))))

As Michael Heerdegen pointed out in that thread, however, there is another way to solve this problem. You can byte-compile the file where you setq the variable, and if it is not defined earlier (e.g. using defvar or defcustom), you will get a warning like assignment to free variable `varname'.

Both approaches may be useful, I guess. I’d slightly prefer the macro, since it would warn me about a problem after installing a new Emacs version where js--declaration-keyword-re is no longer a thing without me doing anything (like recompiling my init.el). On the other hand, byte-compiling also catches other suspicious situations. Anyway, as usual, you have a lot of power at your fingertips, and you are free to choose how your tool will behave to best suit your needs. Emacs for the win!

CategoryEnglish, CategoryBlog, CategoryEmacs