elisp: Dynamic Binding Tips
11.9.2 Proper Use of Dynamic Binding
------------------------------------
Dynamic binding is a powerful feature, as it allows programs to refer to
variables that are not defined within their local textual scope.
However, if used without restraint, this can also make programs hard to
understand. There are two clean ways to use this technique:
• If a variable has no global definition, use it as a local variable
only within a binding construct, such as the body of the ‘let’ form
where the variable was bound. If this convention is followed
consistently throughout a program, the value of the variable will
not affect, nor be affected by, any uses of the same variable
symbol elsewhere in the program.
• Otherwise, define the variable with ‘defvar’, ‘defconst’, or
‘defcustom’. Defining Variables. Usually, the definition
should be at top-level in an Emacs Lisp file. As far as possible,
it should include a documentation string which explains the meaning
and purpose of the variable. You should also choose the variable’s
name to avoid name conflicts (Coding Conventions).
Then you can bind the variable anywhere in a program, knowing
reliably what the effect will be. Wherever you encounter the
variable, it will be easy to refer back to the definition, e.g.,
via the ‘C-h v’ command (provided the variable definition has been
loaded into Emacs). (emacs)Name Help.
For example, it is common to use local bindings for customizable
variables like ‘case-fold-search’:
(defun search-for-abc ()
"Search for the string \"abc\", ignoring case differences."
(let ((case-fold-search nil))
(re-search-forward "abc")))