]> code.delx.au - gnu-emacs/blob - doc/lispref/loading.texi
Empty elements in EMACSLOADPATH now stand for the default
[gnu-emacs] / doc / lispref / loading.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1995, 1998-1999, 2001-2013 Free Software
4 @c Foundation, Inc.
5 @c See the file elisp.texi for copying conditions.
6 @node Loading
7 @chapter Loading
8 @cindex loading
9 @cindex library
10 @cindex Lisp library
11
12 Loading a file of Lisp code means bringing its contents into the
13 Lisp environment in the form of Lisp objects. Emacs finds and opens
14 the file, reads the text, evaluates each form, and then closes the
15 file. Such a file is also called a @dfn{Lisp library}.
16
17 The load functions evaluate all the expressions in a file just
18 as the @code{eval-buffer} function evaluates all the
19 expressions in a buffer. The difference is that the load functions
20 read and evaluate the text in the file as found on disk, not the text
21 in an Emacs buffer.
22
23 @cindex top-level form
24 The loaded file must contain Lisp expressions, either as source code
25 or as byte-compiled code. Each form in the file is called a
26 @dfn{top-level form}. There is no special format for the forms in a
27 loadable file; any form in a file may equally well be typed directly
28 into a buffer and evaluated there. (Indeed, most code is tested this
29 way.) Most often, the forms are function definitions and variable
30 definitions.
31
32 For on-demand loading of external libraries, @pxref{Dynamic Libraries}.
33
34 @menu
35 * How Programs Do Loading:: The @code{load} function and others.
36 * Load Suffixes:: Details about the suffixes that @code{load} tries.
37 * Library Search:: Finding a library to load.
38 * Loading Non-ASCII:: Non-@acronym{ASCII} characters in Emacs Lisp files.
39 * Autoload:: Setting up a function to autoload.
40 * Repeated Loading:: Precautions about loading a file twice.
41 * Named Features:: Loading a library if it isn't already loaded.
42 * Where Defined:: Finding which file defined a certain symbol.
43 * Unloading:: How to "unload" a library that was loaded.
44 * Hooks for Loading:: Providing code to be run when
45 particular libraries are loaded.
46 @end menu
47
48 @node How Programs Do Loading
49 @section How Programs Do Loading
50
51 Emacs Lisp has several interfaces for loading. For example,
52 @code{autoload} creates a placeholder object for a function defined in a
53 file; trying to call the autoloading function loads the file to get the
54 function's real definition (@pxref{Autoload}). @code{require} loads a
55 file if it isn't already loaded (@pxref{Named Features}). Ultimately,
56 all these facilities call the @code{load} function to do the work.
57
58 @defun load filename &optional missing-ok nomessage nosuffix must-suffix
59 This function finds and opens a file of Lisp code, evaluates all the
60 forms in it, and closes the file.
61
62 To find the file, @code{load} first looks for a file named
63 @file{@var{filename}.elc}, that is, for a file whose name is
64 @var{filename} with the extension @samp{.elc} appended. If such a
65 file exists, it is loaded. If there is no file by that name, then
66 @code{load} looks for a file named @file{@var{filename}.el}. If that
67 file exists, it is loaded. Finally, if neither of those names is
68 found, @code{load} looks for a file named @var{filename} with nothing
69 appended, and loads it if it exists. (The @code{load} function is not
70 clever about looking at @var{filename}. In the perverse case of a
71 file named @file{foo.el.el}, evaluation of @code{(load "foo.el")} will
72 indeed find it.)
73
74 If Auto Compression mode is enabled, as it is by default, then if
75 @code{load} can not find a file, it searches for a compressed version
76 of the file before trying other file names. It decompresses and loads
77 it if it exists. It looks for compressed versions by appending each
78 of the suffixes in @code{jka-compr-load-suffixes} to the file name.
79 The value of this variable must be a list of strings. Its standard
80 value is @code{(".gz")}.
81
82 If the optional argument @var{nosuffix} is non-@code{nil}, then
83 @code{load} does not try the suffixes @samp{.elc} and @samp{.el}. In
84 this case, you must specify the precise file name you want, except
85 that, if Auto Compression mode is enabled, @code{load} will still use
86 @code{jka-compr-load-suffixes} to find compressed versions. By
87 specifying the precise file name and using @code{t} for
88 @var{nosuffix}, you can prevent file names like @file{foo.el.el} from
89 being tried.
90
91 If the optional argument @var{must-suffix} is non-@code{nil}, then
92 @code{load} insists that the file name used must end in either
93 @samp{.el} or @samp{.elc} (possibly extended with a compression
94 suffix), unless it contains an explicit directory name.
95
96 If @var{filename} is a relative file name, such as @file{foo} or
97 @file{baz/foo.bar}, @code{load} searches for the file using the variable
98 @code{load-path}. It appends @var{filename} to each of the directories
99 listed in @code{load-path}, and loads the first file it finds whose name
100 matches. The current default directory is tried only if it is specified
101 in @code{load-path}, where @code{nil} stands for the default directory.
102 @code{load} tries all three possible suffixes in the first directory in
103 @code{load-path}, then all three suffixes in the second directory, and
104 so on. @xref{Library Search}.
105
106 Whatever the name under which the file is eventually found, and the
107 directory where Emacs found it, Emacs sets the value of the variable
108 @code{load-file-name} to that file's name.
109
110 If you get a warning that @file{foo.elc} is older than @file{foo.el}, it
111 means you should consider recompiling @file{foo.el}. @xref{Byte
112 Compilation}.
113
114 When loading a source file (not compiled), @code{load} performs
115 character set translation just as Emacs would do when visiting the file.
116 @xref{Coding Systems}.
117
118 @c This is referred to from the Macros chapter.
119 @c Not sure if it should be the other way round.
120 @cindex eager macro expansion
121 When loading an uncompiled file, Emacs tries to expand any macros
122 that the file contains (@pxref{Macros}). We refer to this as
123 @dfn{eager macro expansion}. Doing this (rather than deferring
124 the expansion until the relevant code runs) can significantly speed
125 up the execution of uncompiled code. Sometimes, this macro expansion
126 cannot be done, owing to a cyclic dependency. In the simplest
127 example of this, the file you are loading refers to a macro defined
128 in another file, and that file in turn requires the file you are
129 loading. This is generally harmless. Emacs prints a warning
130 (@samp{Eager macro-expansion skipped due to cycle@dots{}})
131 giving details of the problem, but it still loads the file, just
132 leaving the macro unexpanded for now. You may wish to restructure
133 your code so that this does not happen. Loading a compiled file does
134 not cause macroexpansion, because this should already have happened
135 during compilation. @xref{Compiling Macros}.
136
137 Messages like @samp{Loading foo...} and @samp{Loading foo...done} appear
138 in the echo area during loading unless @var{nomessage} is
139 non-@code{nil}.
140
141 @cindex load errors
142 Any unhandled errors while loading a file terminate loading. If the
143 load was done for the sake of @code{autoload}, any function definitions
144 made during the loading are undone.
145
146 @kindex file-error
147 If @code{load} can't find the file to load, then normally it signals the
148 error @code{file-error} (with @samp{Cannot open load file
149 @var{filename}}). But if @var{missing-ok} is non-@code{nil}, then
150 @code{load} just returns @code{nil}.
151
152 You can use the variable @code{load-read-function} to specify a function
153 for @code{load} to use instead of @code{read} for reading expressions.
154 See below.
155
156 @code{load} returns @code{t} if the file loads successfully.
157 @end defun
158
159 @deffn Command load-file filename
160 This command loads the file @var{filename}. If @var{filename} is a
161 relative file name, then the current default directory is assumed.
162 This command does not use @code{load-path}, and does not append
163 suffixes. However, it does look for compressed versions (if Auto
164 Compression Mode is enabled). Use this command if you wish to specify
165 precisely the file name to load.
166 @end deffn
167
168 @deffn Command load-library library
169 This command loads the library named @var{library}. It is equivalent to
170 @code{load}, except for the way it reads its argument interactively.
171 @xref{Lisp Libraries,,,emacs, The GNU Emacs Manual}.
172 @end deffn
173
174 @defvar load-in-progress
175 This variable is non-@code{nil} if Emacs is in the process of loading a
176 file, and it is @code{nil} otherwise.
177 @end defvar
178
179 @defvar load-file-name
180 When Emacs is in the process of loading a file, this variable's value
181 is the name of that file, as Emacs found it during the search
182 described earlier in this section.
183 @end defvar
184
185 @defvar load-read-function
186 @anchor{Definition of load-read-function}
187 @c do not allow page break at anchor; work around Texinfo deficiency.
188 This variable specifies an alternate expression-reading function for
189 @code{load} and @code{eval-region} to use instead of @code{read}.
190 The function should accept one argument, just as @code{read} does.
191
192 Normally, the variable's value is @code{nil}, which means those
193 functions should use @code{read}.
194
195 Instead of using this variable, it is cleaner to use another, newer
196 feature: to pass the function as the @var{read-function} argument to
197 @code{eval-region}. @xref{Definition of eval-region,, Eval}.
198 @end defvar
199
200 For information about how @code{load} is used in building Emacs, see
201 @ref{Building Emacs}.
202
203 @node Load Suffixes
204 @section Load Suffixes
205 We now describe some technical details about the exact suffixes that
206 @code{load} tries.
207
208 @defvar load-suffixes
209 This is a list of suffixes indicating (compiled or source) Emacs Lisp
210 files. It should not include the empty string. @code{load} uses
211 these suffixes in order when it appends Lisp suffixes to the specified
212 file name. The standard value is @code{(".elc" ".el")} which produces
213 the behavior described in the previous section.
214 @end defvar
215
216 @defvar load-file-rep-suffixes
217 This is a list of suffixes that indicate representations of the same
218 file. This list should normally start with the empty string.
219 When @code{load} searches for a file it appends the suffixes in this
220 list, in order, to the file name, before searching for another file.
221
222 Enabling Auto Compression mode appends the suffixes in
223 @code{jka-compr-load-suffixes} to this list and disabling Auto
224 Compression mode removes them again. The standard value of
225 @code{load-file-rep-suffixes} if Auto Compression mode is disabled is
226 @code{("")}. Given that the standard value of
227 @code{jka-compr-load-suffixes} is @code{(".gz")}, the standard value
228 of @code{load-file-rep-suffixes} if Auto Compression mode is enabled
229 is @code{("" ".gz")}.
230 @end defvar
231
232 @defun get-load-suffixes
233 This function returns the list of all suffixes that @code{load} should
234 try, in order, when its @var{must-suffix} argument is non-@code{nil}.
235 This takes both @code{load-suffixes} and @code{load-file-rep-suffixes}
236 into account. If @code{load-suffixes}, @code{jka-compr-load-suffixes}
237 and @code{load-file-rep-suffixes} all have their standard values, this
238 function returns @code{(".elc" ".elc.gz" ".el" ".el.gz")} if Auto
239 Compression mode is enabled and @code{(".elc" ".el")} if Auto
240 Compression mode is disabled.
241 @end defun
242
243 To summarize, @code{load} normally first tries the suffixes in the
244 value of @code{(get-load-suffixes)} and then those in
245 @code{load-file-rep-suffixes}. If @var{nosuffix} is non-@code{nil},
246 it skips the former group, and if @var{must-suffix} is non-@code{nil},
247 it skips the latter group.
248
249 @node Library Search
250 @section Library Search
251 @cindex library search
252 @cindex find library
253
254 When Emacs loads a Lisp library, it searches for the library
255 in a list of directories specified by the variable @code{load-path}.
256
257 @defvar load-path
258 The value of this variable is a list of directories to search when
259 loading files with @code{load}. Each element is a string (which must be
260 a directory name) or @code{nil} (which stands for the current working
261 directory).
262 @end defvar
263
264 When Emacs starts up, it sets up the value of @code{load-path}
265 in several steps. First, it initializes @code{load-path} using
266 default locations set when Emacs was compiled. Normally, this
267 is a directory something like
268
269 @example
270 "/usr/local/share/emacs/@var{version}/lisp"
271 @end example
272
273 followed by a similarly named @file{leim} directory.
274 (In this and the following examples, replace @file{/usr/local} with
275 the installation prefix appropriate for your Emacs.)
276 These directories contain the standard Lisp files that come with
277 Emacs. If Emacs cannot find them, it will not start correctly.
278
279 If you run Emacs from the directory where it was built---that is, an
280 executable that has not been formally installed---Emacs instead
281 initializes @code{load-path} using the @file{lisp} and @file{leim}
282 directories in the directory containing the sources from which it
283 was built. If you built Emacs in a separate directory from the
284 sources, it also adds those directories from the build directory.
285 (In all cases, elements are represented as absolute file names.)
286
287 @cindex site-lisp directories
288 Unless you start Emacs with the @option{--no-site-lisp} option,
289 it then adds two more @file{site-lisp} directories to the front of
290 @code{load-path}. These are intended for locally installed Lisp files,
291 and are normally of the form:
292
293 @example
294 "/usr/local/share/emacs/@var{version}/site-lisp"
295 @end example
296
297 @noindent
298 and
299
300 @example
301 "/usr/local/share/emacs/site-lisp"
302 @end example
303
304 @noindent
305 The first one is for locally installed files for a specific Emacs
306 version; the second is for locally installed files meant for use
307 with all installed Emacs versions. (If Emacs is running uninstalled,
308 it also adds @file{site-lisp} directories from the source and build
309 directories, if they exist. Normally these directories do not contain
310 @file{site-lisp} directories.)
311
312 @cindex @env{EMACSLOADPATH} environment variable
313 If the environment variable @env{EMACSLOADPATH} is set, it modifies
314 the above initialization procedure. Emacs initializes
315 @code{load-path} based on the value of the environment variable.
316
317 The syntax of @env{EMACSLOADPATH} is the same as used for @code{PATH};
318 directory names are separated by @samp{:} (or @samp{;}, on some
319 operating systems).
320 @ignore
321 @c AFAICS, does not (yet) work right to specify non-absolute elements.
322 and @samp{.} stands for the current default directory.
323 @end ignore
324 Here is an example of how to set @env{EMACSLOADPATH} variable (from a
325 @command{sh}-style shell):
326
327 @example
328 export EMACSLOADPATH=/home/foo/.emacs.d/lisp:
329 @end example
330
331 An empty element in the value of the environment variable, whether
332 trailing (as in the above example), leading, or embedded, is replaced
333 by the default value of @code{load-path} as determined by the standard
334 initialization procedure. If there are no such empty elements, then
335 @env{EMACSLOADPATH} specifies the entire @code{load-path}. You must
336 include either an empty element, or the explicit path to the directory
337 containing the standard Lisp files, else Emacs will not function.
338 (Another way to modify @code{load-path} is to use the @option{-L}
339 command-line option when starting Emacs; see below.)
340
341 For each directory in @code{load-path}, Emacs then checks to see if
342 it contains a file @file{subdirs.el}, and if so, loads it. The
343 @file{subdirs.el} file is created when Emacs is built/installed,
344 and contains code that causes Emacs to add any subdirectories of those
345 directories to @code{load-path}. Both immediate subdirectories and
346 subdirectories multiple levels down are added. But it excludes
347 subdirectories whose names do not start with a letter or digit, and
348 subdirectories named @file{RCS} or @file{CVS}, and subdirectories
349 containing a file named @file{.nosearch}.
350
351 Next, Emacs adds any extra load directories that you specify using the
352 @option{-L} command-line option (@pxref{Action Arguments,,,emacs, The
353 GNU Emacs Manual}). It also adds the directories where optional
354 packages are installed, if any (@pxref{Packaging Basics}).
355
356 It is common to add code to one's init file (@pxref{Init File}) to
357 add one or more directories to @code{load-path}. For example:
358
359 @example
360 (push "~/.emacs.d/lisp" load-path)
361 @end example
362
363 Dumping Emacs uses a special value of @code{load-path}. If the
364 value of @code{load-path} at the end of dumping is unchanged (that is,
365 still the same special value), the dumped Emacs switches to the
366 ordinary @code{load-path} value when it starts up, as described above.
367 But if @code{load-path} has any other value at the end of dumping,
368 that value is used for execution of the dumped Emacs also.
369
370 @deffn Command locate-library library &optional nosuffix path interactive-call
371 This command finds the precise file name for library @var{library}. It
372 searches for the library in the same way @code{load} does, and the
373 argument @var{nosuffix} has the same meaning as in @code{load}: don't
374 add suffixes @samp{.elc} or @samp{.el} to the specified name
375 @var{library}.
376
377 If the @var{path} is non-@code{nil}, that list of directories is used
378 instead of @code{load-path}.
379
380 When @code{locate-library} is called from a program, it returns the file
381 name as a string. When the user runs @code{locate-library}
382 interactively, the argument @var{interactive-call} is @code{t}, and this
383 tells @code{locate-library} to display the file name in the echo area.
384 @end deffn
385
386 @cindex shadowed Lisp files
387 @deffn Command list-load-path-shadows &optional stringp
388 This command shows a list of @dfn{shadowed} Emacs Lisp files. A
389 shadowed file is one that will not normally be loaded, despite being
390 in a directory on @code{load-path}, due to the existence of another
391 similarly-named file in a directory earlier on @code{load-path}.
392
393 For instance, suppose @code{load-path} is set to
394
395 @example
396 ("/opt/emacs/site-lisp" "/usr/share/emacs/23.3/lisp")
397 @end example
398
399 @noindent
400 and that both these directories contain a file named @file{foo.el}.
401 Then @code{(require 'foo)} never loads the file in the second
402 directory. Such a situation might indicate a problem in the way Emacs
403 was installed.
404
405 When called from Lisp, this function prints a message listing the
406 shadowed files, instead of displaying them in a buffer. If the
407 optional argument @code{stringp} is non-@code{nil}, it instead returns
408 the shadowed files as a string.
409 @end deffn
410
411 @node Loading Non-ASCII
412 @section Loading Non-@acronym{ASCII} Characters
413
414 When Emacs Lisp programs contain string constants with non-@acronym{ASCII}
415 characters, these can be represented within Emacs either as unibyte
416 strings or as multibyte strings (@pxref{Text Representations}). Which
417 representation is used depends on how the file is read into Emacs. If
418 it is read with decoding into multibyte representation, the text of the
419 Lisp program will be multibyte text, and its string constants will be
420 multibyte strings. If a file containing Latin-1 characters (for
421 example) is read without decoding, the text of the program will be
422 unibyte text, and its string constants will be unibyte strings.
423 @xref{Coding Systems}.
424
425 In most Emacs Lisp programs, the fact that non-@acronym{ASCII}
426 strings are multibyte strings should not be noticeable, since
427 inserting them in unibyte buffers converts them to unibyte
428 automatically. However, if this does make a difference, you can force
429 a particular Lisp file to be interpreted as unibyte by writing
430 @samp{coding: raw-text} in a local variables section. With
431 that designator, the file will unconditionally be interpreted as
432 unibyte. This can matter when making keybindings to
433 non-@acronym{ASCII} characters written as @code{?v@var{literal}}.
434
435 @node Autoload
436 @section Autoload
437 @cindex autoload
438
439 The @dfn{autoload} facility lets you register the existence of a
440 function or macro, but put off loading the file that defines it. The
441 first call to the function automatically loads the proper library, in
442 order to install the real definition and other associated code, then
443 runs the real definition as if it had been loaded all along.
444 Autoloading can also be triggered by looking up the documentation of
445 the function or macro (@pxref{Documentation Basics}).
446
447 There are two ways to set up an autoloaded function: by calling
448 @code{autoload}, and by writing a special ``magic'' comment in the
449 source before the real definition. @code{autoload} is the low-level
450 primitive for autoloading; any Lisp program can call @code{autoload} at
451 any time. Magic comments are the most convenient way to make a function
452 autoload, for packages installed along with Emacs. These comments do
453 nothing on their own, but they serve as a guide for the command
454 @code{update-file-autoloads}, which constructs calls to @code{autoload}
455 and arranges to execute them when Emacs is built.
456
457 @defun autoload function filename &optional docstring interactive type
458 This function defines the function (or macro) named @var{function} so as
459 to load automatically from @var{filename}. The string @var{filename}
460 specifies the file to load to get the real definition of @var{function}.
461
462 If @var{filename} does not contain either a directory name, or the
463 suffix @code{.el} or @code{.elc}, this function insists on adding one
464 of these suffixes, and it will not load from a file whose name is just
465 @var{filename} with no added suffix. (The variable
466 @code{load-suffixes} specifies the exact required suffixes.)
467
468 The argument @var{docstring} is the documentation string for the
469 function. Specifying the documentation string in the call to
470 @code{autoload} makes it possible to look at the documentation without
471 loading the function's real definition. Normally, this should be
472 identical to the documentation string in the function definition
473 itself. If it isn't, the function definition's documentation string
474 takes effect when it is loaded.
475
476 If @var{interactive} is non-@code{nil}, that says @var{function} can be
477 called interactively. This lets completion in @kbd{M-x} work without
478 loading @var{function}'s real definition. The complete interactive
479 specification is not given here; it's not needed unless the user
480 actually calls @var{function}, and when that happens, it's time to load
481 the real definition.
482
483 You can autoload macros and keymaps as well as ordinary functions.
484 Specify @var{type} as @code{macro} if @var{function} is really a macro.
485 Specify @var{type} as @code{keymap} if @var{function} is really a
486 keymap. Various parts of Emacs need to know this information without
487 loading the real definition.
488
489 An autoloaded keymap loads automatically during key lookup when a prefix
490 key's binding is the symbol @var{function}. Autoloading does not occur
491 for other kinds of access to the keymap. In particular, it does not
492 happen when a Lisp program gets the keymap from the value of a variable
493 and calls @code{define-key}; not even if the variable name is the same
494 symbol @var{function}.
495
496 @cindex function cell in autoload
497 If @var{function} already has a non-void function definition that is not
498 an autoload object, this function does nothing and returns @code{nil}.
499 Otherwise, it constructs an autoload object (@pxref{Autoload Type}),
500 and stores it as the function definition for @var{function}. The
501 autoload object has this form:
502
503 @example
504 (autoload @var{filename} @var{docstring} @var{interactive} @var{type})
505 @end example
506
507 For example,
508
509 @example
510 @group
511 (symbol-function 'run-prolog)
512 @result{} (autoload "prolog" 169681 t nil)
513 @end group
514 @end example
515
516 @noindent
517 In this case, @code{"prolog"} is the name of the file to load, 169681
518 refers to the documentation string in the
519 @file{emacs/etc/DOC} file (@pxref{Documentation Basics}),
520 @code{t} means the function is interactive, and @code{nil} that it is
521 not a macro or a keymap.
522 @end defun
523
524 @defun autoloadp object
525 This function returns non-@code{nil} if @var{object} is an autoload
526 object. For example, to check if @code{run-prolog} is defined as an
527 autoloaded function, evaluate
528
529 @smallexample
530 (autoloadp (symbol-function 'run-prolog))
531 @end smallexample
532 @end defun
533
534 @cindex autoload errors
535 The autoloaded file usually contains other definitions and may require
536 or provide one or more features. If the file is not completely loaded
537 (due to an error in the evaluation of its contents), any function
538 definitions or @code{provide} calls that occurred during the load are
539 undone. This is to ensure that the next attempt to call any function
540 autoloading from this file will try again to load the file. If not for
541 this, then some of the functions in the file might be defined by the
542 aborted load, but fail to work properly for the lack of certain
543 subroutines not loaded successfully because they come later in the file.
544
545 If the autoloaded file fails to define the desired Lisp function or
546 macro, then an error is signaled with data @code{"Autoloading failed to
547 define function @var{function-name}"}.
548
549 @findex update-file-autoloads
550 @findex update-directory-autoloads
551 @cindex magic autoload comment
552 @cindex autoload cookie
553 @anchor{autoload cookie}
554 A magic autoload comment (often called an @dfn{autoload cookie})
555 consists of @samp{;;;###autoload}, on a line by itself,
556 just before the real definition of the function in its
557 autoloadable source file. The command @kbd{M-x update-file-autoloads}
558 writes a corresponding @code{autoload} call into @file{loaddefs.el}.
559 (The string that serves as the autoload cookie and the name of the
560 file generated by @code{update-file-autoloads} can be changed from the
561 above defaults, see below.)
562 Building Emacs loads @file{loaddefs.el} and thus calls @code{autoload}.
563 @kbd{M-x update-directory-autoloads} is even more powerful; it updates
564 autoloads for all files in the current directory.
565
566 The same magic comment can copy any kind of form into
567 @file{loaddefs.el}. The form following the magic comment is copied
568 verbatim, @emph{except} if it is one of the forms which the autoload
569 facility handles specially (e.g., by conversion into an
570 @code{autoload} call). The forms which are not copied verbatim are
571 the following:
572
573 @table @asis
574 @item Definitions for function or function-like objects:
575 @code{defun} and @code{defmacro}; also @code{cl-defun} and
576 @code{cl-defmacro} (@pxref{Argument Lists,,,cl,Common Lisp Extensions}),
577 and @code{define-overloadable-function} (see the commentary in
578 @file{mode-local.el}).
579
580 @item Definitions for major or minor modes:
581 @code{define-minor-mode}, @code{define-globalized-minor-mode},
582 @code{define-generic-mode}, @code{define-derived-mode},
583 @code{easy-mmode-define-minor-mode},
584 @code{easy-mmode-define-global-mode}, @code{define-compilation-mode},
585 and @code{define-global-minor-mode}.
586
587 @item Other definition types:
588 @code{defcustom}, @code{defgroup}, @code{defclass}
589 (@pxref{Top,EIEIO,,eieio,EIEIO}), and @code{define-skeleton} (see the
590 commentary in @file{skeleton.el}).
591 @end table
592
593 You can also use a magic comment to execute a form at build time
594 @emph{without} executing it when the file itself is loaded. To do this,
595 write the form @emph{on the same line} as the magic comment. Since it
596 is in a comment, it does nothing when you load the source file; but
597 @kbd{M-x update-file-autoloads} copies it to @file{loaddefs.el}, where
598 it is executed while building Emacs.
599
600 The following example shows how @code{doctor} is prepared for
601 autoloading with a magic comment:
602
603 @example
604 ;;;###autoload
605 (defun doctor ()
606 "Switch to *doctor* buffer and start giving psychotherapy."
607 (interactive)
608 (switch-to-buffer "*doctor*")
609 (doctor-mode))
610 @end example
611
612 @noindent
613 Here's what that produces in @file{loaddefs.el}:
614
615 @example
616 (autoload (quote doctor) "doctor" "\
617 Switch to *doctor* buffer and start giving psychotherapy.
618
619 \(fn)" t nil)
620 @end example
621
622 @noindent
623 @cindex @code{fn} in function's documentation string
624 The backslash and newline immediately following the double-quote are a
625 convention used only in the preloaded uncompiled Lisp files such as
626 @file{loaddefs.el}; they tell @code{make-docfile} to put the
627 documentation string in the @file{etc/DOC} file. @xref{Building Emacs}.
628 See also the commentary in @file{lib-src/make-docfile.c}. @samp{(fn)}
629 in the usage part of the documentation string is replaced with the
630 function's name when the various help functions (@pxref{Help
631 Functions}) display it.
632
633 If you write a function definition with an unusual macro that is not
634 one of the known and recognized function definition methods, use of an
635 ordinary magic autoload comment would copy the whole definition into
636 @code{loaddefs.el}. That is not desirable. You can put the desired
637 @code{autoload} call into @code{loaddefs.el} instead by writing this:
638
639 @example
640 ;;;###autoload (autoload 'foo "myfile")
641 (mydefunmacro foo
642 ...)
643 @end example
644
645 You can use a non-default string as the autoload cookie and have the
646 corresponding autoload calls written into a file whose name is
647 different from the default @file{loaddefs.el}. Emacs provides two
648 variables to control this:
649
650 @defvar generate-autoload-cookie
651 The value of this variable should be a string whose syntax is a Lisp
652 comment. @kbd{M-x update-file-autoloads} copies the Lisp form that
653 follows the cookie into the autoload file it generates. The default
654 value of this variable is @code{";;;###autoload"}.
655 @end defvar
656
657 @defvar generated-autoload-file
658 The value of this variable names an Emacs Lisp file where the autoload
659 calls should go. The default value is @file{loaddefs.el}, but you can
660 override that, e.g., in the ``Local Variables'' section of a
661 @file{.el} file (@pxref{File Local Variables}). The autoload file is
662 assumed to contain a trailer starting with a formfeed character.
663 @end defvar
664
665 The following function may be used to explicitly load the library
666 specified by an autoload object:
667
668 @defun autoload-do-load autoload &optional name macro-only
669 This function performs the loading specified by @var{autoload}, which
670 should be an autoload object. The optional argument @var{name}, if
671 non-@code{nil}, should be a symbol whose function value is
672 @var{autoload}; in that case, the return value of this function is the
673 symbol's new function value. If the value of the optional argument
674 @var{macro-only} is @code{macro}, this function avoids loading a
675 function, only a macro.
676 @end defun
677
678 @node Repeated Loading
679 @section Repeated Loading
680 @cindex repeated loading
681
682 You can load a given file more than once in an Emacs session. For
683 example, after you have rewritten and reinstalled a function definition
684 by editing it in a buffer, you may wish to return to the original
685 version; you can do this by reloading the file it came from.
686
687 When you load or reload files, bear in mind that the @code{load} and
688 @code{load-library} functions automatically load a byte-compiled file
689 rather than a non-compiled file of similar name. If you rewrite a file
690 that you intend to save and reinstall, you need to byte-compile the new
691 version; otherwise Emacs will load the older, byte-compiled file instead
692 of your newer, non-compiled file! If that happens, the message
693 displayed when loading the file includes, @samp{(compiled; note, source is
694 newer)}, to remind you to recompile it.
695
696 When writing the forms in a Lisp library file, keep in mind that the
697 file might be loaded more than once. For example, think about whether
698 each variable should be reinitialized when you reload the library;
699 @code{defvar} does not change the value if the variable is already
700 initialized. (@xref{Defining Variables}.)
701
702 The simplest way to add an element to an alist is like this:
703
704 @example
705 (push '(leif-mode " Leif") minor-mode-alist)
706 @end example
707
708 @noindent
709 But this would add multiple elements if the library is reloaded. To
710 avoid the problem, use @code{add-to-list} (@pxref{List Variables}):
711
712 @example
713 (add-to-list 'minor-mode-alist '(leif-mode " Leif"))
714 @end example
715
716 Occasionally you will want to test explicitly whether a library has
717 already been loaded. If the library uses @code{provide} to provide a
718 named feature, you can use @code{featurep} earlier in the file to test
719 whether the @code{provide} call has been executed before (@pxref{Named
720 Features}). Alternatively, you could use something like this:
721
722 @example
723 (defvar foo-was-loaded nil)
724
725 (unless foo-was-loaded
726 @var{execute-first-time-only}
727 (setq foo-was-loaded t))
728 @end example
729
730 @noindent
731
732 @node Named Features
733 @section Features
734 @cindex features
735 @cindex requiring features
736 @cindex providing features
737
738 @code{provide} and @code{require} are an alternative to
739 @code{autoload} for loading files automatically. They work in terms of
740 named @dfn{features}. Autoloading is triggered by calling a specific
741 function, but a feature is loaded the first time another program asks
742 for it by name.
743
744 A feature name is a symbol that stands for a collection of functions,
745 variables, etc. The file that defines them should @dfn{provide} the
746 feature. Another program that uses them may ensure they are defined by
747 @dfn{requiring} the feature. This loads the file of definitions if it
748 hasn't been loaded already.
749
750 @cindex load error with require
751 To require the presence of a feature, call @code{require} with the
752 feature name as argument. @code{require} looks in the global variable
753 @code{features} to see whether the desired feature has been provided
754 already. If not, it loads the feature from the appropriate file. This
755 file should call @code{provide} at the top level to add the feature to
756 @code{features}; if it fails to do so, @code{require} signals an error.
757
758 For example, in @file{idlwave.el}, the definition for
759 @code{idlwave-complete-filename} includes the following code:
760
761 @example
762 (defun idlwave-complete-filename ()
763 "Use the comint stuff to complete a file name."
764 (require 'comint)
765 (let* ((comint-file-name-chars "~/A-Za-z0-9+@@:_.$#%=@{@}\\-")
766 (comint-completion-addsuffix nil)
767 ...)
768 (comint-dynamic-complete-filename)))
769 @end example
770
771 @noindent
772 The expression @code{(require 'comint)} loads the file @file{comint.el}
773 if it has not yet been loaded, ensuring that
774 @code{comint-dynamic-complete-filename} is defined. Features are
775 normally named after the files that provide them, so that
776 @code{require} need not be given the file name. (Note that it is
777 important that the @code{require} statement be outside the body of the
778 @code{let}. Loading a library while its variables are let-bound can
779 have unintended consequences, namely the variables becoming unbound
780 after the let exits.)
781
782 The @file{comint.el} file contains the following top-level expression:
783
784 @example
785 (provide 'comint)
786 @end example
787
788 @noindent
789 This adds @code{comint} to the global @code{features} list, so that
790 @code{(require 'comint)} will henceforth know that nothing needs to be
791 done.
792
793 @cindex byte-compiling @code{require}
794 When @code{require} is used at top level in a file, it takes effect
795 when you byte-compile that file (@pxref{Byte Compilation}) as well as
796 when you load it. This is in case the required package contains macros
797 that the byte compiler must know about. It also avoids byte compiler
798 warnings for functions and variables defined in the file loaded with
799 @code{require}.
800
801 Although top-level calls to @code{require} are evaluated during
802 byte compilation, @code{provide} calls are not. Therefore, you can
803 ensure that a file of definitions is loaded before it is byte-compiled
804 by including a @code{provide} followed by a @code{require} for the same
805 feature, as in the following example.
806
807 @example
808 @group
809 (provide 'my-feature) ; @r{Ignored by byte compiler,}
810 ; @r{evaluated by @code{load}.}
811 (require 'my-feature) ; @r{Evaluated by byte compiler.}
812 @end group
813 @end example
814
815 @noindent
816 The compiler ignores the @code{provide}, then processes the
817 @code{require} by loading the file in question. Loading the file does
818 execute the @code{provide} call, so the subsequent @code{require} call
819 does nothing when the file is loaded.
820
821 @defun provide feature &optional subfeatures
822 This function announces that @var{feature} is now loaded, or being
823 loaded, into the current Emacs session. This means that the facilities
824 associated with @var{feature} are or will be available for other Lisp
825 programs.
826
827 The direct effect of calling @code{provide} is if not already in
828 @var{features} then to add @var{feature} to the front of that list and
829 call any @code{eval-after-load} code waiting for it (@pxref{Hooks for
830 Loading}). The argument @var{feature} must be a symbol.
831 @code{provide} returns @var{feature}.
832
833 If provided, @var{subfeatures} should be a list of symbols indicating
834 a set of specific subfeatures provided by this version of
835 @var{feature}. You can test the presence of a subfeature using
836 @code{featurep}. The idea of subfeatures is that you use them when a
837 package (which is one @var{feature}) is complex enough to make it
838 useful to give names to various parts or functionalities of the
839 package, which might or might not be loaded, or might or might not be
840 present in a given version. @xref{Network Feature Testing}, for
841 an example.
842
843 @example
844 features
845 @result{} (bar bish)
846
847 (provide 'foo)
848 @result{} foo
849 features
850 @result{} (foo bar bish)
851 @end example
852
853 When a file is loaded to satisfy an autoload, and it stops due to an
854 error in the evaluation of its contents, any function definitions or
855 @code{provide} calls that occurred during the load are undone.
856 @xref{Autoload}.
857 @end defun
858
859 @defun require feature &optional filename noerror
860 This function checks whether @var{feature} is present in the current
861 Emacs session (using @code{(featurep @var{feature})}; see below). The
862 argument @var{feature} must be a symbol.
863
864 If the feature is not present, then @code{require} loads @var{filename}
865 with @code{load}. If @var{filename} is not supplied, then the name of
866 the symbol @var{feature} is used as the base file name to load.
867 However, in this case, @code{require} insists on finding @var{feature}
868 with an added @samp{.el} or @samp{.elc} suffix (possibly extended with
869 a compression suffix); a file whose name is just @var{feature} won't
870 be used. (The variable @code{load-suffixes} specifies the exact
871 required Lisp suffixes.)
872
873 If @var{noerror} is non-@code{nil}, that suppresses errors from actual
874 loading of the file. In that case, @code{require} returns @code{nil}
875 if loading the file fails. Normally, @code{require} returns
876 @var{feature}.
877
878 If loading the file succeeds but does not provide @var{feature},
879 @code{require} signals an error, @samp{Required feature @var{feature}
880 was not provided}.
881 @end defun
882
883 @defun featurep feature &optional subfeature
884 This function returns @code{t} if @var{feature} has been provided in
885 the current Emacs session (i.e., if @var{feature} is a member of
886 @code{features}.) If @var{subfeature} is non-@code{nil}, then the
887 function returns @code{t} only if that subfeature is provided as well
888 (i.e., if @var{subfeature} is a member of the @code{subfeature}
889 property of the @var{feature} symbol.)
890 @end defun
891
892 @defvar features
893 The value of this variable is a list of symbols that are the features
894 loaded in the current Emacs session. Each symbol was put in this list
895 with a call to @code{provide}. The order of the elements in the
896 @code{features} list is not significant.
897 @end defvar
898
899 @node Where Defined
900 @section Which File Defined a Certain Symbol
901
902 @defun symbol-file symbol &optional type
903 This function returns the name of the file that defined @var{symbol}.
904 If @var{type} is @code{nil}, then any kind of definition is acceptable.
905 If @var{type} is @code{defun}, @code{defvar}, or @code{defface}, that
906 specifies function definition, variable definition, or face definition
907 only.
908
909 The value is normally an absolute file name. It can also be @code{nil},
910 if the definition is not associated with any file. If @var{symbol}
911 specifies an autoloaded function, the value can be a relative file name
912 without extension.
913 @end defun
914
915 The basis for @code{symbol-file} is the data in the variable
916 @code{load-history}.
917
918 @defvar load-history
919 The value of this variable is an alist that associates the names of
920 loaded library files with the names of the functions and variables
921 they defined, as well as the features they provided or required.
922
923 Each element in this alist describes one loaded library (including
924 libraries that are preloaded at startup). It is a list whose @sc{car}
925 is the absolute file name of the library (a string). The rest of the
926 list elements have these forms:
927
928 @table @code
929 @item @var{var}
930 The symbol @var{var} was defined as a variable.
931 @item (defun . @var{fun})
932 The function @var{fun} was defined.
933 @item (t . @var{fun})
934 The function @var{fun} was previously an autoload before this library
935 redefined it as a function. The following element is always
936 @code{(defun . @var{fun})}, which represents defining @var{fun} as a
937 function.
938 @item (autoload . @var{fun})
939 The function @var{fun} was defined as an autoload.
940 @item (defface . @var{face})
941 The face @var{face} was defined.
942 @item (require . @var{feature})
943 The feature @var{feature} was required.
944 @item (provide . @var{feature})
945 The feature @var{feature} was provided.
946 @end table
947
948 The value of @code{load-history} may have one element whose @sc{car} is
949 @code{nil}. This element describes definitions made with
950 @code{eval-buffer} on a buffer that is not visiting a file.
951 @end defvar
952
953 The command @code{eval-region} updates @code{load-history}, but does so
954 by adding the symbols defined to the element for the file being visited,
955 rather than replacing that element. @xref{Eval}.
956
957 @node Unloading
958 @section Unloading
959 @cindex unloading packages
960
961 @c Emacs 19 feature
962 You can discard the functions and variables loaded by a library to
963 reclaim memory for other Lisp objects. To do this, use the function
964 @code{unload-feature}:
965
966 @deffn Command unload-feature feature &optional force
967 This command unloads the library that provided feature @var{feature}.
968 It undefines all functions, macros, and variables defined in that
969 library with @code{defun}, @code{defalias}, @code{defsubst},
970 @code{defmacro}, @code{defconst}, @code{defvar}, and @code{defcustom}.
971 It then restores any autoloads formerly associated with those symbols.
972 (Loading saves these in the @code{autoload} property of the symbol.)
973
974 Before restoring the previous definitions, @code{unload-feature} runs
975 @code{remove-hook} to remove functions in the library from certain
976 hooks. These hooks include variables whose names end in @samp{-hook}
977 (or the deprecated suffix @samp{-hooks}), plus those listed in
978 @code{unload-feature-special-hooks}, as well as
979 @code{auto-mode-alist}. This is to prevent Emacs from ceasing to
980 function because important hooks refer to functions that are no longer
981 defined.
982
983 Standard unloading activities also undoes ELP profiling of functions
984 in that library, unprovides any features provided by the library, and
985 cancels timers held in variables defined by the library.
986
987 @vindex @var{feature}-unload-function
988 If these measures are not sufficient to prevent malfunction, a library
989 can define an explicit unloader named @code{@var{feature}-unload-function}.
990 If that symbol is defined as a function, @code{unload-feature} calls
991 it with no arguments before doing anything else. It can do whatever
992 is appropriate to unload the library. If it returns @code{nil},
993 @code{unload-feature} proceeds to take the normal unload actions.
994 Otherwise it considers the job to be done.
995
996 Ordinarily, @code{unload-feature} refuses to unload a library on which
997 other loaded libraries depend. (A library @var{a} depends on library
998 @var{b} if @var{a} contains a @code{require} for @var{b}.) If the
999 optional argument @var{force} is non-@code{nil}, dependencies are
1000 ignored and you can unload any library.
1001 @end deffn
1002
1003 The @code{unload-feature} function is written in Lisp; its actions are
1004 based on the variable @code{load-history}.
1005
1006 @defvar unload-feature-special-hooks
1007 This variable holds a list of hooks to be scanned before unloading a
1008 library, to remove functions defined in the library.
1009 @end defvar
1010
1011 @node Hooks for Loading
1012 @section Hooks for Loading
1013 @cindex loading hooks
1014 @cindex hooks for loading
1015
1016 You can ask for code to be executed each time Emacs loads a library,
1017 by using the variable @code{after-load-functions}:
1018
1019 @defvar after-load-functions
1020 This abnormal hook is run after loading a file. Each function in the
1021 hook is called with a single argument, the absolute filename of the
1022 file that was just loaded.
1023 @end defvar
1024
1025 If you want code to be executed when a @emph{particular} library is
1026 loaded, use the macro @code{with-eval-after-load}:
1027
1028 @defmac with-eval-after-load library body@dots{}
1029 This macro arranges to evaluate @var{body} at the end of loading
1030 the file @var{library}, each time @var{library} is loaded. If
1031 @var{library} is already loaded, it evaluates @var{body} right away.
1032
1033 You don't need to give a directory or extension in the file name
1034 @var{library}. Normally, you just give a bare file name, like this:
1035
1036 @example
1037 (with-eval-after-load "edebug" (def-edebug-spec c-point t))
1038 @end example
1039
1040 To restrict which files can trigger the evaluation, include a
1041 directory or an extension or both in @var{library}. Only a file whose
1042 absolute true name (i.e., the name with all symbolic links chased out)
1043 matches all the given name components will match. In the following
1044 example, @file{my_inst.elc} or @file{my_inst.elc.gz} in some directory
1045 @code{..../foo/bar} will trigger the evaluation, but not
1046 @file{my_inst.el}:
1047
1048 @example
1049 (with-eval-after-load "foo/bar/my_inst.elc" @dots{})
1050 @end example
1051
1052 @var{library} can also be a feature (i.e., a symbol), in which case
1053 @var{body} is evaluated at the end of any file where
1054 @code{(provide @var{library})} is called.
1055
1056 An error in @var{body} does not undo the load, but does prevent
1057 execution of the rest of @var{body}.
1058 @end defmac
1059
1060 Normally, well-designed Lisp programs should not use
1061 @code{eval-after-load}. If you need to examine and set the variables
1062 defined in another library (those meant for outside use), you can do
1063 it immediately---there is no need to wait until the library is loaded.
1064 If you need to call functions defined by that library, you should load
1065 the library, preferably with @code{require} (@pxref{Named Features}).