Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a variable's initial value in Elisp?

Tags:

emacs

elisp

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"
like image 913
Tao Peng Avatar asked Nov 27 '22 23:11

Tao Peng


2 Answers

This is generally not possible (Emacs does not remember the original value), but there are some exceptions.

defcustom variables

Variables 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

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.

like image 131
Richard Hansen Avatar answered Dec 06 '22 23:12

Richard Hansen


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.

like image 34
Gilles 'SO- stop being evil' Avatar answered Dec 07 '22 00:12

Gilles 'SO- stop being evil'