Emacs Lisp: Buffer Local Variable
- Buffer-Local Variables are global variables but have their own independent values in each buffer.
- Every Buffer-Local Variable has a global Default Value. That is the value by befault in all buffers, if not changed.
- Many builtin variables in emacs are buffer-local. e.g. major-mode • default-directory • tab-width
- You can define a variable to be buffer local.
- You can make a normally non-buffer-local variable to have buffer local value.
Create Buffer-Local Variable
defvar-local
-
(defvar-local VAR VAL &optional DOCSTRING)
Define a buffer-local variable with a default value.
This is equivalent to calling
defvar
followed bymake-variable-buffer-local
.(defvar-local xx-format-style 1 "sample buffer-local variable.")
make-variable-buffer-local
-
(make-variable-buffer-local VARIABLE)
Make VARIABLE become buffer-local whenever it is set.
⚠ WARNING: this function create a Symbol as variable if the symbol does not already exist. In elisp package, you should declare a variable first by
defvar
etc. Or usedefvar-local
.(make-variable-buffer-local 'xx-a)
make-local-variable
-
(make-local-variable VARIABLE)
Make VARIABLE have a separate value in the current buffer. Other buffers will continue to share a common default value. (The buffer-local value of VARIABLE starts out as the same value VARIABLE previously had. If VARIABLE was void, it remains void.) Return VARIABLE.
(defvar xx-b 'long "sample variable.") (make-local-variable 'xx-b)
(make-local-variable 'xx-c) ;; warning: if symbol xx-c does not exist, this does not work. it does not create a symbol xx-c
Set Default Value to Buffer-Local Variable
setq-default
-
Make a value the default value for a buffer-local variable
(setq-default tab-width 4)
Set Value to Buffer-Local Variable
setq-local
-
(setq-local VAR1 VAL1 etc)
Set buffer-local values to variable.
(require 'newcomment) (setq-local comment-start "# ")
Other Functions on Buffer-Local Variable
- Command:
kill-local-variable
- Function:
local-variable-p
- Function:
local-variable-if-set-p
- Function:
buffer-local-value
- Function:
buffer-local-boundp
- Function:
buffer-local-variables
- Function:
kill-all-local-variables
- Variable: change-major-mode-hook
- Function:
default-value
- Function:
default-boundp
- Function:
set-default
- Function:
default-toplevel-value
- Function:
set-default-toplevel-value