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