ELisp: Buffer Local Variable

By Xah Lee. Date: . Last updated: .

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 by make-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 use defvar-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

Reference

Emacs Lisp Variable