25

Q: Using Elisp, how can I reset a variable to its default value without knowing what that value is?

I tried to figure out how to do this by bringing up the Customize interface for a variable I set to a non-default value in my init-file and pressing C-h k followed by a click on the "Revert..." button. That brought up the documentation for widget-button-click, which obviously didn't help much. (Similarly, C-h k RET with point on the button shows help for Custom-newline, which is also not what I am looking for.)

23

C-hig (elisp) Variable Definitions

Internally, defcustom uses the symbol property standard-value to record the expression for the standard value, saved-value to record the value saved by the user with the customization buffer, and customized-value to record the value set by the user with the customization buffer, but not saved. See Symbol Properties. These properties are lists, the car of which is an expression that evaluates to the value.

Hence:

(setq foo (eval (car (get 'foo 'standard-value))))

Note that this only applies to defcustom variables (i.e. "user options"). Emacs does not save the initial value of a defvar variable anywhere.

  • 3
    Actually, you need to evaluate the vale in the plist. Your example should be changed to: (setq foo (eval (car (get 'foo 'standard-value)))) The default value form generated by defcustom is a form with a funcall and a closure (this is possibly happening only when lexical binding is enabled) – Elias Mårtenson Nov 3 '14 at 10:23
  • You probably want to use setq-default rather than setq in this case. – sanityinc Nov 3 '14 at 17:56
11

Another, probably cleaner, way to reset the value of a variable:

custom-reevaluate-setting is a compiled Lisp function in custom.el.

(custom-reevaluate-setting SYMBOL)

Reset the value of SYMBOL by re-evaluating its saved or standard value. Use the :set function to do so. This is useful for customizable options that are defined before their standard value can really be computed. E.g. dumped variables whose default depends on run-time information.

So for example:

(custom-reevaluate-setting 'emms-player-next-function)

will replace the previous value with that symbol's standard-value.

EDIT

Read @phils comment below for a very important detail regarding this function.

  • 5
    Note "saved or standard value". In that order of precedence. If the user has customized and saved a value for the variable, this function resets it to its saved-value, not its standard-value. – phils Apr 20 '15 at 23:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.