home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / prgramer / unix / info / elisp.i08 (.txt) < prev    next >
GNU Info File  |  1993-06-14  |  46KB  |  848 lines

  1. This is Info file elisp, produced by Makeinfo-1.47 from the input file
  2. elisp.texi.
  3.    This file documents GNU Emacs Lisp.
  4.    This is edition 1.03 of the GNU Emacs Lisp Reference Manual, for
  5. Emacs Version 18.
  6.    Published by the Free Software Foundation, 675 Massachusetts Avenue,
  7. Cambridge, MA 02139 USA
  8.    Copyright (C) 1990 Free Software Foundation, Inc.
  9.    Permission is granted to make and distribute verbatim copies of this
  10. manual provided the copyright notice and this permission notice are
  11. preserved on all copies.
  12.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided that
  14. the entire resulting derived work is distributed under the terms of a
  15. permission notice identical to this one.
  16.    Permission is granted to copy and distribute translations of this
  17. manual into another language, under the above conditions for modified
  18. versions, except that this permission notice may be stated in a
  19. translation approved by the Foundation.
  20. File: elisp,  Node: Related Topics,  Prev: Function Cells,  Up: Functions
  21. Other Topics Related to Functions
  22. =================================
  23.    Here is a table of several functions that do things related to
  24. function calling and function definitions.
  25. `apply'
  26.      *Note Calling Functions::.
  27. `autoload'
  28.      *Note Autoload::.
  29. `call-interactively'
  30.      *Note Interactive Call::.
  31. `commandp'
  32.      *Note Interactive Call::.
  33. `documentation'
  34.      *Note Accessing Documentation::.
  35. `eval'
  36.      *Note Eval::.
  37. `funcall'
  38.      *Note Calling Functions::.
  39. `ignore'
  40.      *Note Calling Functions::.
  41. `interactive'
  42.      *Note Using Interactive::.
  43. `interactive-p'
  44.      *Note Interactive Call::.
  45. `mapatoms'
  46.      *Note Creating Symbols::.
  47. `mapcar'
  48.      *Note Mapping Functions::.
  49. `mapconcat'
  50.      *Note Mapping Functions::.
  51. `undefined'
  52.      *Note Key Lookup::.
  53. File: elisp,  Node: Macros,  Next: Loading,  Prev: Functions,  Up: Top
  54. Macros
  55. ******
  56.    "Macros" enable you to define new control constructs and other
  57. language features.  A macro is defined much like a function, but instead
  58. of telling how to compute a value, it tells how to compute another Lisp
  59. expression which will in turn compute the value.  We call this
  60. expression the "expansion" of the macro.
  61.    Macros can do this because they operate on the unevaluated
  62. expressions for the arguments, not on the argument values as functions
  63. do.  They can therefore construct an expansion containing these
  64. argument expressions or parts of them.
  65. * Menu:
  66. * Simple Macro::            A basic example.
  67. * Expansion::               How, when and why macros are expanded.
  68. * Compiling Macros::        How macros are expanded by the compiler.
  69. * Defining Macros::         How to write a macro definition.
  70. * Backquote::               Easier construction of list structure.
  71. * Problems with Macros::    Don't evaluate the macro arguments too many times.
  72.                               Don't hide the user's variables.
  73. File: elisp,  Node: Simple Macro,  Next: Expansion,  Prev: Macros,  Up: Macros
  74. A Simple Example of a Macro
  75. ===========================
  76.    Suppose we would like to define a Lisp construct to increment a
  77. variable value, much like the `++' operator in C.  We would like to
  78. write `(inc x)' and have the effect of `(setq x (1+ x))'. Here's a
  79. macro definition that will do the job:
  80.      (defmacro inc (var)
  81.         (list 'setq var (list '1+ var)))
  82.    When this is called with `(inc x)', the argument `var' has the value
  83. `x'--*not* the *value* of `x'.  The body of the macro uses this to
  84. construct the expansion, which is `(setq x (1+ x))'.  Once the macro
  85. definition returns this expansion, Lisp proceeds to evaluate it, thus
  86. incrementing `x'.
  87. File: elisp,  Node: Expansion,  Next: Compiling Macros,  Prev: Simple Macro,  Up: Macros
  88. Expansion of a Macro Call
  89. =========================
  90.    A macro call looks just like a function call in that it is a list
  91. which starts with the name of the macro.  The rest of the elements of
  92. the list are the arguments of the macro.
  93.    Evaluation of the macro call begins like evaluation of a function
  94. call except for one crucial difference: the macro arguments are the
  95. actual expressions appearing in the macro call.  They are not evaluated
  96. before they are given to the macro definition.  By contrast, the
  97. arguments of a function are results of evaluating the elements of the
  98. function call list.
  99.    Having obtained the arguments, Lisp invokes the macro definition just
  100. as a function is invoked.  The argument variables of the macro are bound
  101. to the argument values from the macro call, or to a list of them in the
  102. case of a `&rest' argument.  And the macro body executes and returns
  103. its value just as a function body does.
  104.    The second crucial difference between macros and functions is that
  105. the value returned by the macro body is not the value of the macro call.
  106. Instead, it is an alternate expression for computing that value, also
  107. known as the "expansion" of the macro.  The Lisp interpreter proceeds
  108. to evaluate the expansion as soon as it comes back from the macro.
  109.    Since the expansion is evaluated in the normal manner, it may contain
  110. calls to other macros.  It may even be a call to the same macro, though
  111. this is unusual.
  112.    You can see the expansion of a given macro call by calling
  113. `macroexpand':
  114.  -- Function: macroexpand FORM &optional ENVIRONMENT
  115.      This function expands FORM, if it is a macro call.  If the result
  116.      is another macro call, it is expanded in turn, until something
  117.      which is not a macro call results.  That is the value returned by
  118.      `macroexpand'.  If FORM is not a macro call to begin with, it is
  119.      returned as given.
  120.      Note that `macroexpand' does not look at the subexpressions of
  121.      FORM (although some macro definitions may do so).  If they are
  122.      macro calls themselves, `macroexpand' will not expand them.
  123.      If ENVIRONMENT is provided, it specifies an alist of macro
  124.      definitions that shadow the currently defined macros.  This is used
  125.      by byte compilation.
  126.           (defmacro inc (var)
  127.               (list 'setq var (list '1+ var)))
  128.                => inc
  129.           
  130.           (macroexpand '(inc r))
  131.                => (setq r (1+ r))
  132.           
  133.           (defmacro inc2 (var1 var2)
  134.               (list 'progn (list 'inc var1) (list 'inc var2)))
  135.                => inc2
  136.           
  137.           (macroexpand '(inc2 r s))
  138.                => (progn (inc r) (inc s))        ; `inc' not expanded here.
  139. File: elisp,  Node: Compiling Macros,  Next: Defining Macros,  Prev: Expansion,  Up: Macros
  140. Macros and Byte Compilation
  141. ===========================
  142.    You might ask why we take the trouble to compute an expansion for a
  143. macro and then evaluate the expansion.  Why not have the macro body
  144. produce the desired results directly?  The reason has to do with
  145. compilation.
  146.    When a macro call appears in a Lisp program being compiled, the Lisp
  147. compiler calls the macro definition just as the interpreter would, and
  148. receives an expansion.  But instead of evaluating this expansion, it
  149. compiles expansion as if it had appeared directly in the program.  As a
  150. result, the compiled code produces the value and side effects intended
  151. for the macro, but executes at full compiled speed.  This would not work
  152. if the macro body computed the value and side effects itself--they
  153. would be computed at compile time, which is not useful.
  154.    In order for compilation of macro calls to work, the macros must be
  155. defined in Lisp when the calls to them are compiled.  The compiler has a
  156. special feature to help you do this: if a file being compiled contains a
  157. `defmacro' form, the macro is defined temporarily for the rest of the
  158. compilation of that file.  To use this feature, you must define the
  159. macro in the same file where it is used and before its first use.
  160.    While byte-compiling a file, any `require' calls at top-level are
  161. executed.  One way to ensure that necessary macro definitions are
  162. available during compilation is to require the file that defines them.
  163. *Note Features::.
  164. File: elisp,  Node: Defining Macros,  Next: Backquote,  Prev: Compiling Macros,  Up: Macros
  165. Defining Macros
  166. ===============
  167.    A Lisp macro is a list whose CAR is `macro'.  Its CDR should be a
  168. function; expansion of the macro works by applying the function (with
  169. `apply') to the list of unevaluated argument-expressions from the macro
  170. call.
  171.    It is possible to use an anonymous Lisp macro just like an anonymous
  172. function, but this is never done, because it does not make sense to pass
  173. an anonymous macro to mapping functions such as `mapcar'.  In practice,
  174. all Lisp macros have names, and they are usually defined with the
  175. special form `defmacro'.
  176.  -- Special Form: defmacro NAME ARGUMENT-LIST BODY-FORMS...
  177.      `defmacro' defines the symbol NAME as a macro that looks like this:
  178.           (macro lambda ARGUMENT-LIST . BODY-FORMS)
  179.      This macro object is stored in the function cell of NAME.  The
  180.      value returned by evaluating the `defmacro' form is NAME, but
  181.      usually we ignore this value.
  182.      The shape and meaning of ARGUMENT-LIST is the same as in a
  183.      function, and the keywords `&rest' and `&optional' may be used
  184.      (*note Argument List::.).  Macros may have a documentation string,
  185.      but any `interactive' declaration is ignored since macros cannot be
  186.      called interactively.
  187. File: elisp,  Node: Backquote,  Next: Problems with Macros,  Prev: Defining Macros,  Up: Macros
  188. Backquote
  189. =========
  190.    It could prove rather awkward to write macros of significant size,
  191. simply due to the number of times the function `list' needs to be
  192. called.  To make writing these forms easier, a macro ``' (often called
  193. "backquote") exists.
  194.    Backquote allows you to quote a list, but selectively evaluate
  195. elements of that list.  In the simplest case, it is identical to the
  196. special form `quote' (*note Quoting::.).  For example, these two forms
  197. yield identical results:
  198.      (` (a list of (+ 2 3) elements))
  199.           => (a list of (+ 2 3) elements)
  200.      (quote (a list of (+ 2 3) elements))
  201.           => (a list of (+ 2 3) elements)
  202.    By inserting a special marker, `,', inside of the argument to
  203. backquote, it is possible to evaluate desired portions of the argument:
  204.      (list 'a 'list 'of (+ 2 3) 'elements)
  205.           => (a list of 5 elements)
  206.      (` (a list of (, (+ 2 3)) elements))
  207.           => (a list of 5 elements)
  208.    It is also possible to have an evaluated list "spliced" into the
  209. resulting list by using the special marker `,@'.  The elements of the
  210. spliced list become elements at the same level as the other elements of
  211. the resulting list.  The equivalent code without using ``' is often
  212. unreadable.  Here are some examples:
  213.      (setq some-list '(2 3))
  214.           => (2 3)
  215.      (cons 1 (append some-list '(4) some-list))
  216.           => (1 2 3 4 2 3)
  217.      (` (1 (,@ some-list) 4 (,@ some-list)))
  218.           => (1 2 3 4 2 3)
  219.      
  220.      (setq list '(hack foo bar))
  221.           => (hack foo bar)
  222.      (cons 'use
  223.        (cons 'the
  224.          (cons 'words (append (cdr list) '(as elements)))))
  225.           => (use the words foo bar as elements)
  226.      (` (use the words (,@ (cdr list)) as elements (,@ nil)))
  227.           => (use the words foo bar as elements)
  228.    The reason for `(,@ nil)' is to avoid a bug in Emacs version 18. The
  229. bug occurs when a call to `,@' is followed only by constant elements. 
  230. Thus,
  231.      (` (use the words (,@ (cdr list)) as elements))
  232. would not work, though it really ought to.  `(,@ nil)' avoids the
  233. problem by being a nonconstant element that does not affect the result.
  234.  -- Macro: ` LIST
  235.      This macro returns LIST as `quote' would, except that the list is
  236.      copied each time this expression is evaluated, and any sublist of
  237.      the form `(, SUBEXP)' is replaced by the value of SUBEXP.  Any
  238.      sublist of the form `(,@ LISTEXP)' is replaced by evaluating
  239.      LISTEXP and splicing its elements into the containing list in
  240.      place of this sublist.  (A single sublist can in this way be
  241.      replaced by any number of new elements in the containing list.)
  242.      There are certain contexts in which `,' would not be recognized and
  243.      should not be used:
  244.           ;; Use of a `,' expression as the CDR of a list.
  245.           (` (a . (, 1)))                                 ; Not `(a . 1)'
  246.                => (a \, 1)
  247.           
  248.           ;; Use of `,' in a vector.
  249.           (` [a (, 1) c])                                 ; Not `[a 1 c]'
  250.                error--> Wrong type argument
  251.           
  252.           ;; Use of a `,' as the entire argument of ``'.
  253.           (` (, 2))                                       ; Not 2
  254.                => (\, 2)
  255.      Common Lisp note: in Common Lisp, `,' and `,@' are implemented as
  256.      reader macros, so they do not require parentheses.  Emacs Lisp
  257.      implements them as functions because reader macros are not
  258.      supported (to save space).
  259. File: elisp,  Node: Problems with Macros,  Prev: Backquote,  Up: Macros
  260. Common Problems Using Macros
  261. ============================
  262.    The basic facts of macro expansion have all been described above, but
  263. there consequences are often counterintuitive.  This section describes
  264. some important consequences that can lead to trouble, and rules to
  265. follow to avoid trouble.
  266. * Menu:
  267. * Argument Evaluation::    The expansion should evaluate each macro arg once.
  268. * Surprising Local Vars::  Local variable bindings in the expansion
  269.                               require special care.
  270. * Eval During Expansion::  Don't evaluate them; put them in the expansion.
  271. * Repeated Expansion::     Avoid depending on how many times expansion is done.
  272. File: elisp,  Node: Argument Evaluation,  Next: Surprising Local Vars,  Prev: Problems with Macros,  Up: Problems with Macros
  273. Evaluating Macro Arguments Too Many Times
  274. -----------------------------------------
  275.    When defining a macro you must pay attention to the number of times
  276. the arguments will be evaluated when the expansion is executed.  The
  277. following macro (used to facilitate iteration) illustrates the problem.
  278. This macro allows us to write a simple "for" loop such as one might
  279. find in Pascal.
  280.      (defmacro for (var from init to final do &rest body)
  281.        "Execute a simple \"for\" loop, e.g.,
  282.          (for i from 1 to 10 do (print i))."
  283.        (list 'let (list (list var init))
  284.              (cons 'while (cons (list '<= var final)
  285.                                 (append body (list (list 'inc var)))))))
  286.      => for
  287.      
  288.      (for i from 1 to 3 do
  289.         (setq square (* i i))
  290.         (princ (format "\n%d %d" i square)))
  291.      ==>
  292.      (let ((i 1))
  293.        (while (<= i 3)
  294.          (setq square (* i i))
  295.          (princ (format "%d      %d" i square))
  296.          (inc i)))
  297.      
  298.           -|1       1
  299.           -|2       4
  300.           -|3       9
  301.      => nil
  302. (The arguments `from', `to', and `do' in this macro are "syntactic
  303. sugar"; they are entirely ignored.  The idea is that you will write
  304. noise words (such as `from', `to', and `do') in those positions in the
  305. macro call.)
  306.    This macro suffers from the defect that FINAL is evaluated on every
  307. iteration.  If FINAL is a constant, this is not a problem. If it is a
  308. more complex form, say `(long-complex-calculation x)', this can slow
  309. down the execution significantly.  If FINAL has side effects, executing
  310. it more than once is probably incorrect.
  311.    A well-designed macro definition takes steps to avoid this problem by
  312. producing an expansion that evaluates the argument expressions exactly
  313. once unless repeated evaluation is part of the intended purpose of the
  314. macro.  Here is a correct expansion for the `for' macro:
  315.      (let ((i 1)
  316.            (max 3))
  317.        (while (<= i max)
  318.          (setq square (* i i))
  319.          (princ (format "%d      %d" i square))
  320.          (inc i)))
  321.    Here is a macro definition that creates this expansion:
  322.      (defmacro for (var from init to final do &rest body)
  323.        "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  324.        (` (let (((, var) (, init))
  325.                 (max (, final)))
  326.             (while (<= (, var) max)
  327.               (,@ body)
  328.               (inc (, var))))))
  329.    Unfortunately, this introduces another problem. Proceed to the
  330. following node.
  331. File: elisp,  Node: Surprising Local Vars,  Next: Eval During Expansion,  Prev: Argument Evaluation,  Up: Problems with Macros
  332. Local Variables in Macro Expansions
  333. -----------------------------------
  334.    In the previous section, the definition of `for' was fixed as
  335. follows to make the expansion evaluate the macro arguments the proper
  336. number of times:
  337.      (defmacro for (var from init to final do &rest body)
  338.        "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  339.        (` (let (((, var) (, init))
  340.                 (max (, final)))
  341.             (while (<= (, var) max)
  342.               (,@ body)
  343.               (inc (, var))))))
  344.    The new definition of `for' has a new problem: it introduces a local
  345. variable named `max' which the user does not expect.  This will cause
  346. trouble in examples such as the following:
  347.      (let ((max 0))
  348.        (for x from 0 to 10 do
  349.          (let ((this (frob x)))
  350.            (if (< max this)
  351.                (setq max this)))))
  352. The references to `max' inside the body of the `for', which are
  353. supposed to refer to the user's binding of `max', will instead access
  354. the binding made by `for'.
  355.    The way to correct this is to use an uninterned symbol instead of
  356. `max' (*note Creating Symbols::.).  The uninterned symbol can be bound
  357. and referred to just like any other symbol, but since it is created by
  358. `for', we know that it cannot appear in the user's program. Since it is
  359. not interned, there is no way the user can put it into the program
  360. later.  It will not appear anywhere except where put by `for'.  Here is
  361. a definition of `for' which works this way:
  362.      (defmacro for (var from init to final do &rest body)
  363.        "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  364.        (let ((tempvar (make-symbol "max")))
  365.          (` (let (((, var) (, init))
  366.                   ((, tempvar) (, final)))
  367.               (while (<= (, var) (, tempvar))
  368.                      (,@ body)
  369.                      (inc (, var)))))))
  370. This creates an uninterned symbol named `max' and puts it in the
  371. expansion instead of the usual interned symbol `max' that appears in
  372. expressions ordinarily.
  373. File: elisp,  Node: Eval During Expansion,  Next: Repeated Expansion,  Prev: Surprising Local Vars,  Up: Problems with Macros
  374. Evaluating Macro Arguments in Expansion
  375. ---------------------------------------
  376.    Another problem can happen if you evaluate any of the macro argument
  377. expressions during the computation of the expansion, such as by calling
  378. `eval' (*note Eval::.).  If the argument is supposed to refer to the
  379. user's variables, you may have trouble if the user happens to use a
  380. variable with the same name as one of the macro arguments.  Inside the
  381. macro body, the macro argument binding is the most local binding of this
  382. variable, so any references inside the form being evaluated will refer
  383. to it.  Here is an example:
  384.      (defmacro foo (a)
  385.        (list 'setq (eval a) t))
  386.           => foo
  387.      (setq x 'b)
  388.      (foo x) ==> (setq b t)
  389.           => t                  ; and `b' has been set.
  390.      ;; but
  391.      (setq a 'b)
  392.      (foo a) ==> (setq 'b t)     ; invalid!
  393.      error--> Symbol's value is void: b
  394.    It makes a difference whether the user types `a' or `x', because `a'
  395. conflicts with the macro argument variable `a'.
  396.    In general it is best to avoid calling `eval' in a macro definition
  397. at all.
  398. File: elisp,  Node: Repeated Expansion,  Prev: Eval During Expansion,  Up: Problems with Macros
  399. How Many Times is the Macro Expanded?
  400. -------------------------------------
  401.    Occasionally problems result from the fact that a macro call is
  402. expanded each time it is evaluated in an interpreted function, but is
  403. expanded only once (during compilation) for a compiled function.  If the
  404. macro definition has side effects, they will work differently depending
  405. on how many times the macro is expanded.
  406.    In particular, constructing objects is a kind of side effect.  If the
  407. macro is called once, then the objects are constructed only once.  In
  408. other words, the same structure of objects is used each time the macro
  409. call is executed.  In interpreted operation, the macro is reexpanded
  410. each time, producing a fresh collection of objects each time.  Usually
  411. this does not matter--the objects have the same contents whether they
  412. are shared or not.  But if the surrounding program does side effects on
  413. the objects, it makes a difference whether they are shared.  Here is an
  414. example:
  415.      (defmacro new-object ()
  416.        (list 'quote (cons nil nil)))
  417.      
  418.      (defun initialize (condition)
  419.        (let ((object (new-object)))
  420.          (if condition
  421.          (setcar object condition))
  422.          object))
  423. If `initialize' is interpreted, a new list `(nil)' is constructed each
  424. time `initialize' is called.  Thus, no side-effect survives between
  425. calls.  If `initialize' is compiled, then the macro `new-object' is
  426. expanded during compilation, producing a single "constant" `(nil)' that
  427. is reused and altered each time `initialize' is called.
  428. File: elisp,  Node: Loading,  Next: Byte Compilation,  Prev: Macros,  Up: Top
  429. Loading
  430. *******
  431.    Loading a file of Lisp code means bringing its contents into the Lisp
  432. environment in the form of Lisp objects.  Emacs finds and opens the
  433. file, reads the text, evaluates each form, and then closes the file.
  434.    The load functions evaluate all the expressions in a file just as
  435. the `eval-current-buffer' function evaluates all the expressions in a
  436. buffer.  The difference is that the load functions read and evaluate
  437. the text in the file as found on disk, not the text in an Emacs buffer.
  438.    The loaded file must contain Lisp expressions, either as source code
  439. or, optionally, as byte-compiled code.  Each form in the file is called
  440. a "top-level form".  There is no special format for the forms in a
  441. loadable file; any form in a file may equally well be typed directly
  442. into a buffer and evaluated there.  (Indeed, most code is tested this
  443. way.)  Most often, the forms are function definitions and variable
  444. definitions.
  445.    A file containing Lisp code is often called a "library".  Thus, the
  446. "Rmail library" is a file containing code for Rmail mode. Similarly, a
  447. "Lisp library directory" is a directory of files containing Lisp code.
  448. * Menu:
  449. * How Programs Do Loading::     The `load' function and others.
  450. * Autoload::                    Setting up a function to autoload.
  451. * Repeated Loading::            Precautions about loading a file twice.
  452. * Features::                    Loading a library if it isn't already loaded.
  453. File: elisp,  Node: How Programs Do Loading,  Next: Autoload,  Prev: Loading,  Up: Loading
  454. How Programs Do Loading
  455. =======================
  456.    There are several interface functions for loading.  For example, the
  457. `autoload' function creates a Lisp object that loads a file when it is
  458. evaluated (*note Autoload::.).  `require' also causes files to be
  459. loaded (*note Features::.).  Ultimately, all these facilities call the
  460. `load' function to do the work.
  461.  -- Function: load FILENAME &optional MISSING-OK NOMESSAGE NOSUFFIX
  462.      This function finds and opens a file of Lisp code, evaluates all
  463.      the forms in it, and closes the file.
  464.      To find the file, `load' first looks for a file named
  465.      `FILENAME.elc', that is, for a file whose name has `.elc'
  466.      appended.  If such a file exists, it is loaded.  But if there is
  467.      no file by that name, then `load' looks for a file whose name has
  468.      `.el' appended.  If that file exists, it is loaded. Finally, if
  469.      there is no file by either name, `load' looks for a file named
  470.      FILENAME with nothing appended, and loads it if it exists.  (The
  471.      `load' function is not clever about looking at FILENAME.  In the
  472.      perverse case of a file named `foo.el.el', evaluation of `(load
  473.      "foo.el")' will indeed find it.)
  474.      If the optional argument NOSUFFIX is non-`nil', then the suffixes
  475.      `.elc' and `.el' are not tried.  In this case, the file name must
  476.      be specified precisely.
  477.      If FILENAME is a relative file name, such as `foo.bar' or
  478.      `baz/foo.bar', Emacs searches for the file using the variable
  479.      `load-path'.  Emacs does this by appending FILENAME to each of the
  480.      directories listed in `load-path', and loading the first file it
  481.      finds whose name matches.  The current default directory is tried
  482.      only if it is specified in `load-path', where it is represented as
  483.      `nil'.  All three possible suffixes are tried in the first
  484.      directory in `load-path', then all three in the second directory
  485.      in `load-path', etc.
  486.      Messages like `Loading foo...' and `Loading foo...done' are
  487.      printed in the echo area while loading unless NOMESSAGE is
  488.      non-`nil'.
  489.      Any errors that are encountered while loading a file cause `load'
  490.      to abort.  If the load was done for the sake of `autoload', certain
  491.      kinds of top-level forms, those which define functions, are undone.
  492.      The error `file-error' is signaled (with `Cannot open load file
  493.      FILENAME') if no file is found.  No error is signaled if
  494.      MISSING-OK is non-`nil'--then `load' just returns `nil'.
  495.      `load' returns `t' if the file loads successfully.
  496.  -- User Option: load-path
  497.      The value of this variable is a list of directories to search when
  498.      loading files with `load'.  Each element is a string (which must be
  499.      a directory name) or `nil' (which stands for the current working
  500.      directory).  The value of `load-path' is initialized from the
  501.      environment variable `EMACSLOADPATH', if it exists; otherwise it is
  502.      set to the default specified in `emacs/src/paths.h' when Emacs is
  503.      built.
  504.      The syntax of `EMACSLOADPATH' is the same as that of `PATH';
  505.      fields are separated by `:', and `.' is used for the current
  506.      default directory.  Here is an example of how to set your
  507.      `EMACSLOADPATH' variable from a `csh' `.login' file:
  508.           setenv EMACSLOADPATH .:/user/liberte/emacs:/usr/local/lib/emacs/lisp
  509.      Here is how to set it using `sh':
  510.           export EMACSLOADPATH
  511.           EMACSLOADPATH=.:/user/liberte/emacs:/usr/local/lib/emacs/lisp
  512.      Here is an example of code you can place in a `.emacs' file to add
  513.      several directories to the front of your default `load-path':
  514.           (setq load-path
  515.                 (append
  516.                  (list nil
  517.                        "/user/liberte/emacs"
  518.                        "/usr/local/lisplib")
  519.                  load-path))
  520.      In this example, the path searches the current working directory
  521.      first, followed by `/user/liberte/emacs' and `/usr/local/lisplib',
  522.      which are then followed by the standard directories for Lisp code.
  523.      When Emacs 18 is processing command options `-l' or `-load' which
  524.      specify Lisp libraries to be loaded, it temporarily adds the
  525.      current directory to the front of `load-path' so that files in the
  526.      current directory can be specified easily.  Emacs version 19 will
  527.      also find such files in the current directory but without altering
  528.      `load-path'.
  529.  -- Variable: load-in-progress
  530.      This variable is non-`nil' if Emacs is in the process of loading a
  531.      file, and it is `nil' otherwise.  This is how `defun' and
  532.      `provide' determine whether a load is in progress, so that their
  533.      effect can be undone if the load fails.
  534.    To learn how `load' is used to build Emacs, see *Note Building
  535. Emacs::.
  536. File: elisp,  Node: Autoload,  Next: Repeated Loading,  Prev: How Programs Do Loading,  Up: Loading
  537. Autoload
  538. ========
  539.    The "autoload" facility allows you to make a function or macro
  540. available but put off loading its actual definition.  An attempt to call
  541. a symbol whose definition is an autoload object automatically reads the
  542. file to install the real definition and its other associated code, and
  543. then calls the real definition.
  544.    To prepare a function or macro for autoloading, you must call
  545. `autoload', specifying the function name and the name of the file to be
  546. loaded.  This is usually done when Emacs is first built, by files such
  547. as `emacs/lisp/loaddefs.el'.
  548.    The following example shows how `doctor' is prepared for autoloading
  549. in `loaddefs.el':
  550.      (autoload 'doctor "doctor"
  551.        "\
  552.      Switch to *doctor* buffer and start giving psychotherapy."
  553.        t)
  554. The backslash and newline immediately following the double-quote are a
  555. convention used only in the preloaded Lisp files such as `loaddefs.el';
  556. they cause the documentation string to be put in the `etc/DOC' file. 
  557. (*Note Building Emacs::.)  In any other source file, you would write
  558. just this:
  559.      (autoload 'doctor "doctor"
  560.        "Switch to *doctor* buffer and start giving psychotherapy."
  561.        t)
  562.    Calling `autoload' creates an autoload object containing the name of
  563. the file and some other information, and makes this the definition of
  564. the specified symbol.  When you later try to call that symbol as a
  565. function or macro, the file is loaded; the loading should redefine that
  566. symbol with its proper definition.  After the file completes loading,
  567. the function or macro is called as if it had been there originally.
  568.    If, at the end of loading the file, the desired Lisp function or
  569. macro has not been defined, then the error `error' is signaled (with
  570. data `"Autoloading failed to define function FUNCTION-NAME"').
  571.    The autoloaded file may, of course, contain other definitions and may
  572. require or provide one or more features.  If the file is not completely
  573. loaded (due to an error in the evaluation of the contents) any function
  574. definitions or `provide' calls that occurred during the load are
  575. undone.  This is to ensure that the next attempt to call any function
  576. autoloading from this file will try again to load the file.  If not for
  577. this, then some of the functions in the file might appear defined, but
  578. they may fail to work properly for the lack of certain subroutines
  579. defined later in the file and not loaded successfully.
  580.  -- Function: autoload SYMBOL FILENAME &optional DOCSTRING INTERACTIVE
  581.           MACRO
  582.      This function defines the function (or macro) named SYMBOL so as
  583.      to load automatically from FILENAME.  The string FILENAME is a
  584.      file name which will be passed to `load' when the function is
  585.      called.
  586.      The argument DOCSTRING is the documentation string for the
  587.      function.  Normally, this is the same string that is in the
  588.      function definition itself.  This makes it possible to look at the
  589.      documentation without loading the real definition.
  590.      If INTERACTIVE is non-`nil', then the function can be called
  591.      interactively.  This lets completion in `M-x' work without loading
  592.      the function's real definition.  The complete interactive
  593.      specification need not be given here.  If MACRO is non-`nil', then
  594.      the function is really a macro.
  595.      If SYMBOL already has a non-`nil' function definition that is not
  596.      an autoload object, `autoload' does nothing and returns `nil'.  If
  597.      the function cell of SYMBOL is void, or is already an autoload
  598.      object, then it is set to an autoload object that looks like this:
  599.           (autoload FILENAME DOCSTRING INTERACTIVE MACRO)
  600.      For example,
  601.           (symbol-function 'run-prolog)
  602.                => (autoload "prolog" 169681 t nil)
  603.      In this case, `"prolog"' is the name of the file to load, 169681 is
  604.      the reference to the documentation string in the `emacs/etc/DOC'
  605.      file (*note Documentation Basics::.), `t' means the function is
  606.      interactive, and `nil' that it is not a macro.
  607. File: elisp,  Node: Repeated Loading,  Next: Features,  Prev: Autoload,  Up: Loading
  608. Repeated Loading
  609. ================
  610.    You may load a file more than once in an Emacs session.  For
  611. example, after you have rewritten and reinstalled a function definition
  612. by editing it in a buffer, you may wish to return to the original
  613. version; you can do this by reloading the file in which it is located.
  614.    When you load or reload files, bear in mind that the `load' and
  615. `load-library' functions automatically load a byte-compiled file rather
  616. than a non-compiled file of similar name.  If you rewrite a file that
  617. you intend to save and reinstall, remember to byte-compile it if
  618. necessary; otherwise you may find yourself inadvertently reloading the
  619. older, byte-compiled file instead of your newer, non-compiled file!
  620.    When writing the forms in a library, keep in mind that the library
  621. might be loaded more than once.  For example, the choice of `defvar'
  622. vs. `defconst' for defining a variable depends on whether it is
  623. desirable to reinitialize the variable if the library is reloaded:
  624. `defconst' does so, and `defvar' does not. (*Note Defining Variables::.)
  625.    The simplest way to add an element to an alist is like this:
  626.      (setq minor-mode-alist (cons '(leif-mode " Leif") minor-mode-alist))
  627. But this would add multiple elements if the library is reloaded. To
  628. avoid the problem, write this:
  629.      (or (assq 'leif-mode minor-mode-alist)
  630.          (setq minor-mode-alist
  631.                (cons '(leif-mode " Leif") minor-mode-alist)))
  632.    Occasionally you will want to test explicitly whether a library has
  633. already been loaded; you can do so as follows:
  634.      (if (not (boundp 'foo-was-loaded))
  635.          EXECUTE-FIRST-TIME-ONLY)
  636.      
  637.      (setq foo-was-loaded t)
  638. File: elisp,  Node: Features,  Prev: Repeated Loading,  Up: Loading
  639. Features
  640. ========
  641.    `provide' and `require' are an alternative to `autoload' for loading
  642. files automatically.  They work in terms of named "features". 
  643. Autoloading is triggered by calling a specific function, but a feature
  644. is loaded the first time another program asks for it by name.
  645.    The use of named features simplifies the task of determining whether
  646. required definitions have been defined.  A feature name is a symbol that
  647. stands for a collection of functions, variables, etc.  A program that
  648. needs the collection may ensure that they are defined by "requiring"
  649. the feature.  If the file that contains the feature has not yet been
  650. loaded, then it will be loaded (or an error will be signaled if it
  651. cannot be loaded).  The file thus loaded must "provide" the required
  652. feature or an error will be signaled.
  653.    To require the presence of a feature, call `require' with the
  654. feature name as argument.  `require' looks in the global variable
  655. `features' to see whether the desired feature has been provided
  656. already.  If not, it loads the feature from the appropriate file.  This
  657. file should call `provide' at the top-level to add the feature to
  658. `features'.
  659.    Features are normally named after the files they are provided in so
  660. that `require' need not be given the file name.
  661.    For example, in `emacs/lisp/prolog.el', the definition for
  662. `run-prolog' includes the following code:
  663.      (interactive)
  664.      (require 'shell)
  665.      (switch-to-buffer (make-shell "prolog" "prolog"))
  666.      (inferior-prolog-mode))
  667. The expression `(require 'shell)' loads the file `shell.el' if it has
  668. not yet been loaded.  This ensures that `make-shell' is defined.
  669.    The `shell.el' file contains the following top-level expression:
  670.      (provide 'shell)
  671. This adds `shell' to the global `features' list when the `shell' file
  672. is loaded, so that `(require 'shell)' will henceforth know that nothing
  673. needs to be done.
  674.    When `require' is used at top-level in a file, it takes effect if
  675. you byte-compile that file (*note Byte Compilation::.).  This is in case
  676. the required package contains macros that the byte compiler must know
  677. about.
  678.    Although top-level calls to `require' are evaluated during byte
  679. compilation, `provide' calls are not.  Therefore, you can ensure that a
  680. file of definitions is loaded before it is byte-compiled by including a
  681. `provide' followed by a `require' for the same feature, as in the
  682. following example.
  683.      (provide 'my-feature)  ; Ignored by byte compiler, evaluated by `load'.
  684.      (require 'my-feature)  ; Evaluated by byte compiler.
  685.  -- Function: provide FEATURE
  686.      This function announces that FEATURE is now loaded, or being
  687.      loaded, into the current Emacs session.  This means that the
  688.      facilities associated with FEATURE are or will be available for
  689.      other Lisp programs.
  690.      The direct effect of calling `provide' is to add FEATURE to the
  691.      front of the list `features' if it is not already in the list. The
  692.      argument FEATURE must be a symbol.  `provide' returns FEATURE.
  693.           features
  694.                => (bar bish)
  695.           
  696.           (provide 'foo)
  697.                => foo
  698.           features
  699.                => (foo bar bish)
  700.      During autoloading, if the file is not completely loaded (due to an
  701.      error in the evaluation of the contents) any function definitions
  702.      or `provide' calls that occurred during the load are undone. *Note
  703.      Autoload::.
  704.  -- Function: require FEATURE &optional FILENAME
  705.      This function checks whether FEATURE is present in the current
  706.      Emacs session (using `(featurep FEATURE)'; see below).  If it is
  707.      not, then `require' loads FILENAME with `load'.  If FILENAME is
  708.      not supplied, then the name of the symbol FEATURE is used as the
  709.      file name to load.
  710.      If FEATURE is not provided after the file has been loaded, Emacs
  711.      will signal the error `error' (with data `Required feature FEATURE
  712.      was not provided').
  713.  -- Function: featurep FEATURE
  714.      This function returns `t' if FEATURE has been provided in the
  715.      current Emacs session (i.e., FEATURE is a member of `features'.)
  716.  -- Variable: features
  717.      The value of this variable is a list of symbols that are the
  718.      features loaded in the current Emacs session.  Each symbol was put
  719.      in this list with a call to `provide'.  The order of the elements
  720.      in the `features' list is not significant.
  721. File: elisp,  Node: Byte Compilation,  Next: Debugging,  Prev: Loading,  Up: Top
  722. Byte Compilation
  723. ****************
  724.    GNU Emacs Lisp has a "compiler" that translates functions written in
  725. Lisp into a special representation called "byte-code" that can be
  726. executed more efficiently.  The compiler replaces Lisp function
  727. definitions with byte-code.  When a byte-code function is called, its
  728. definition is evaluated by the "byte-code interpreter".
  729.    Because the byte-compiled code is evaluated by the byte-code
  730. interpreter, instead of being executed directly by the machine's
  731. hardware (as true compiled code is), byte-code is completely
  732. transportable from machine to machine without recompilation.  It is
  733. not, however, as fast as true compiled code.
  734.    *Note Compilation Errors::, for how to investigate errors occurring
  735. in byte compilation.
  736. * Menu:
  737. * Compilation Functions::       Byte compilation functions.
  738. * Disassembly::                 Disassembling byte-code; how to read byte-code.
  739. File: elisp,  Node: Compilation Functions,  Next: Disassembly,  Prev: Byte Compilation,  Up: Byte Compilation
  740. The Compilation Functions
  741. =========================
  742.    An individual function or macro definition may be byte-compiled with
  743. the `byte-compile' function.  A whole file may be byte-compiled with
  744. `byte-compile-file' and several files may be byte-compiled with
  745. `byte-recompile-directory' or `batch-byte-compile'. Only `defun' and
  746. `defmacro' forms in a file are byte-compiled; other top-level forms are
  747. not altered by byte compilation.
  748.    Be careful when byte-compiling code that uses macros.  Macro calls
  749. are expanded when they are compiled, so the macros must already be
  750. defined for proper compilation.  For more details, see *Note Compiling
  751. Macros::.
  752.    While byte-compiling a file, any `require' calls at top-level are
  753. executed.  One way to ensure that necessary macro definitions are
  754. available during compilation is to require the file that defines them.
  755. *Note Features::.
  756.    A byte-compiled function is not as efficient as a primitive function
  757. written in C, but will run much faster than the version written in Lisp.
  758. For a rough comparison, consider the example below:
  759.      (defun silly-loop (n)
  760.        "Return time before and after N iterations of a loop."
  761.        (let ((t1 (current-time-string)))
  762.          (while (> (setq n (1- n))
  763.                    0))
  764.          (list t1 (current-time-string))))
  765.      => silly-loop
  766.      
  767.      (silly-loop 100000)
  768.      => ("Thu Jan 12 20:18:38 1989"
  769.          "Thu Jan 12 20:19:29 1989")  ; 51 seconds
  770.      
  771.      (byte-compile 'silly-loop)
  772.      => [Compiled code not shown]
  773.      
  774.      (silly-loop 100000)
  775.      => ("Thu Jan 12 20:21:04 1989"
  776.          "Thu Jan 12 20:21:17 1989")  ; 13 seconds
  777.    In this example, the interpreted code required 51 seconds to run,
  778. whereas the byte-compiled code required 13 seconds.  These results are
  779. representative, but actual results will vary greatly.
  780.  -- Function: byte-compile SYMBOL
  781.      This function byte-compiles the function definition of SYMBOL,
  782.      replacing the previous definition with the compiled one.  The
  783.      function definition of SYMBOL must be the actual code for the
  784.      function; i.e., the compiler will not follow indirection to
  785.      another symbol. `byte-compile' does not compile macros. 
  786.      `byte-compile' returns the new, compiled definition of SYMBOL.
  787.           (defun factorial (integer)
  788.             "Compute factorial of INTEGER."
  789.             (if (= 1 integer) 1
  790.               (* integer (factorial (1- integer)))))
  791.                => factorial
  792.           
  793.           (byte-compile 'factorial)
  794.                => (lambda (integer)
  795.                            "Compute factorial of INTEGER."
  796.                            (byte-code "\301^HU\203
  797.           ^@\301\202^Q^@\302^H\303^HS!\"\207"
  798.                                       [integer 1 * factorial] 4))
  799.      The string that is the first argument of `byte-code' is the actual
  800.      byte-code.  Each character in it is an instruction.  The vector
  801.      contains all the constants, variable names and function names used
  802.      by the function, except for certain primitives that are coded as
  803.      special instructions.
  804.      The `byte-compile' function is not autoloaded as are
  805.      `byte-compile-file' and `byte-recompile-directory'.
  806.  -- Command: byte-compile-file FILENAME
  807.      This function compiles a file of Lisp code named FILENAME into a
  808.      file of byte-code.  The output file's name is made by appending
  809.      `c' to the end of FILENAME.
  810.      Compilation works by reading the input file one form at a time. 
  811.      If it is a definition of a function or macro, the compiled
  812.      function or macro definition is written out.  Other forms are
  813.      copied out unchanged.  All comments are discarded when the input
  814.      file is read.
  815.      This command returns `t'.  When called interactively, it prompts
  816.      for the file name.
  817.           % ls -l push*
  818.           -rw-r--r--  1 lewis             791 Oct  5 20:31 push.el
  819.           
  820.           (byte-compile-file "~/emacs/push.el")
  821.                => t
  822.           
  823.           % ls -l push*
  824.           -rw-r--r--  1 lewis             791 Oct  5 20:31 push.el
  825.           -rw-rw-rw-  1 lewis             638 Oct  8 20:25 push.elc
  826.  -- Command: byte-recompile-directory DIRECTORY FLAG
  827.      This function recompiles every `.el' file in DIRECTORY that needs
  828.      recompilation.  A file needs recompilation if a `.elc' file exists
  829.      but is older than the `.el' file.
  830.      If a `.el' file exists, but there is no corresponding `.elc' file,
  831.      then FLAG is examined.  If it is `nil', the file is ignored.  If
  832.      it is non-`nil', the user is asked whether the file should be
  833.      compiled.
  834.      The returned value of this command is unpredictable.
  835.  -- Function: batch-byte-compile
  836.      This function runs `byte-compile-file' on the files remaining on
  837.      the command line.  This function must be used only in a batch
  838.      execution of Emacs, as it kills Emacs on completion.  Each file
  839.      will be processed, even if an error occurs while compiling a
  840.      previous file.  (The file with the error will not, of course,
  841.      produce any compiled code.)
  842.           % emacs -batch -f batch-byte-compile *.el
  843.  -- Function: byte-code CODE-STRING DATA-VECTOR MAX-STACK
  844.      This is the function that actually interprets byte-code.  A
  845.      byte-compiled function is actually defined with a body that calls
  846.      `byte-code'.  Don't call this function yourself.  Only the byte
  847.      compiler knows how to generate valid calls to this function.
  848.