Next: , Previous: , Up: Variable Scoping   [Contents][Index]

12.10.4 Using Lexical Binding

When loading an Emacs Lisp file or evaluating a Lisp buffer, lexical binding is enabled if the buffer-local variable lexical-binding is non-nil:

Variable: lexical-binding

If this buffer-local variable is non-nil, Emacs Lisp files and buffers are evaluated using lexical binding instead of dynamic binding. (However, special variables are still dynamically bound; see below.) If nil, dynamic binding is used for all local variables. This variable is typically set for a whole Emacs Lisp file, as a file local variable (see File Local Variables). Note that unlike other such variables, this one must be set in the first line of a file.

When evaluating Emacs Lisp code directly using an eval call, lexical binding is enabled if the lexical argument to eval is non-nil. See Eval.

Lexical binding is also enabled in Lisp Interaction and IELM mode, used in the *scratch* and *ielm* buffers, and also when evaluating expressions via M-: (eval-expression) and when processing the --eval command-line options of Emacs (see Action Arguments in The GNU Emacs Manual) and emacsclient (see emacsclient Options in The GNU Emacs Manual).

Even when lexical binding is enabled, certain variables will continue to be dynamically bound. These are called special variables. Every variable that has been defined with defvar, defcustom or defconst is a special variable (see Defining Variables). All other variables are subject to lexical binding.

Using defvar without a value, it is possible to bind a variable dynamically just in one file, or in just one part of a file while still binding it lexically elsewhere. For example:

(let (_)
  (defvar x)      ; Let-bindings of x will be dynamic within this let.
  (let ((x -99))  ; This is a dynamic binding of x.
    (defun get-dynamic-x ()

(let ((x 'lexical)) ; This is a lexical binding of x.
  (defun get-lexical-x ()

(let (_)
  (defvar x)
  (let ((x 'dynamic))
    (list (get-lexical-x)
    ⇒ (lexical dynamic)
Function: special-variable-p symbol

This function returns non-nil if symbol is a special variable (i.e., it has a defvar, defcustom, or defconst variable definition). Otherwise, the return value is nil.

Note that since this is a function, it can only return non-nil for variables which are permanently special, but not for those that are only special in the current lexical scope.

The use of a special variable as a formal argument in a function is not supported.

Next: , Previous: , Up: Variable Scoping   [Contents][Index]