In Emacs Lisp, is there a function to get the initial value of a symbol initilized by defvar
? Like the some-function
shown below:
(defvar var "initial value")
(setq var "changed value")
(some-function 'var)
=> "inital value"
This is generally not possible (Emacs does not remember the original value), but there are some exceptions.
defcustom
variablesVariables defined with defcustom
and modified with the customization system get the original value, saved value, and customized-but-not-yet-saved value as properties:
(defcustom foo 0 "testing")
(custom-set-variables '(foo 1))
(setq foo 2)
(customize-mark-as-set 'foo)
(setq foo 3)
(car (get 'foo 'standard-value)) ;; evaluates to 0
(car (get 'foo 'saved-value)) ;; evaluates to 1
(car (get 'foo 'customized-value)) ;; evaluates to 2
foo ;; evaluates to 3
See the Defining Customization Variables section in the elisp manual, specifically the discussion above the documentation for the custom-reevaluate-setting
function.
Buffer-local variables have a default (global) value and a buffer-local value that may differ from the global value. You can use the default-value
function to obtain the default value:
(setq indent-tabs-mode nil)
(default-value 'indent-tabs-mode) ;; evaluates to t
It is possible to change the default value, however, and Emacs won't remember the original default value:
(set-default 'indent-tabs-mode nil)
(default-value 'indent-tabs-mode) ;; evaluates to nil
See the Introduction to Buffer-Local Variables section in the elisp manual for more details.
Emacs doesn't remember the initial value. If you evaluate
(defvar var "initial value")
(setq var "changed value")
in the *scratch*
buffer, "initial value"
is no longer available, full stop.
If the defvar
was performed in a loaded file, Emacs remembers where it's loaded from; (symbol-file var 'defvar)
returns the file name, and you can get an the original expression that the variable was initialized with (but not the original value), assuming the file is still around. This is also available via the command M-x find-variable.
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