home *** CD-ROM | disk | FTP | other *** search
/ SGI Developer Toolbox 6.1 / SGI Developer Toolbox 6.1 - Disc 4.iso / public / GNU / emacs.inst / emacs19.idb / usr / gnu / info / elisp-9.z / elisp-9
Encoding:
GNU Info File  |  1994-08-02  |  50.0 KB  |  1,275 lines

  1. This is Info file elisp, produced by Makeinfo-1.55 from the input file
  2. elisp.texi.
  3.  
  4.    This version is newer than the second printed edition of the GNU
  5. Emacs Lisp Reference Manual.  It corresponds to Emacs Version 19.19.
  6.  
  7.    Published by the Free Software Foundation 675 Massachusetts Avenue
  8. Cambridge, MA 02139 USA
  9.  
  10.    Copyright (C) 1990, 1991, 1992, 1993 Free Software Foundation, Inc.
  11.  
  12.    Permission is granted to make and distribute verbatim copies of this
  13. manual provided the copyright notice and this permission notice are
  14. preserved on all copies.
  15.  
  16.    Permission is granted to copy and distribute modified versions of
  17. this manual under the conditions for verbatim copying, provided that
  18. the entire resulting derived work is distributed under the terms of a
  19. permission notice identical to this one.
  20.  
  21.    Permission is granted to copy and distribute translations of this
  22. manual into another language, under the above conditions for modified
  23. versions, except that this permission notice may be stated in a
  24. translation approved by the Foundation.
  25.  
  26.    Permission is granted to copy and distribute modified versions of
  27. this manual under the conditions for verbatim copying, provided also
  28. that the section entitled "GNU Emacs General Public License" is included
  29. exactly as in the original, and provided that the entire resulting
  30. derived work is distributed under the terms of a permission notice
  31. identical to this one.
  32.  
  33.    Permission is granted to copy and distribute translations of this
  34. manual into another language, under the above conditions for modified
  35. versions, except that the section entitled "GNU Emacs General Public
  36. License" may be included in a translation approved by the Free Software
  37. Foundation instead of in the original English.
  38.  
  39. 
  40. File: elisp,  Node: Calling Functions,  Next: Mapping Functions,  Prev: Defining Functions,  Up: Functions
  41.  
  42. Calling Functions
  43. =================
  44.  
  45.    Defining functions is only half the battle.  Functions don't do
  46. anything until you "call" them, i.e., tell them to run.  This process
  47. is also known as "invocation".
  48.  
  49.    The most common way of invoking a function is by evaluating a list.
  50. For example, evaluating the list `(concat "a" "b")' calls the function
  51. `concat'.  *Note Evaluation::, for a description of evaluation.
  52.  
  53.    When you write a list as an expression in your program, the function
  54. name is part of the program.  This means that the choice of which
  55. function to call is made when you write the program.  Usually that's
  56. just what you want.  Occasionally you need to decide at run time which
  57. function to call.  Then you can use the functions `funcall' and `apply'.
  58.  
  59.  - Function: funcall FUNCTION &rest ARGUMENTS
  60.      `funcall' calls FUNCTION with ARGUMENTS, and returns whatever
  61.      FUNCTION returns.
  62.  
  63.      Since `funcall' is a function, all of its arguments, including
  64.      FUNCTION, are evaluated before `funcall' is called.  This means
  65.      that you can use any expression to obtain the function to be
  66.      called.  It also means that `funcall' does not see the expressions
  67.      you write for the ARGUMENTS, only their values.  These values are
  68.      *not* evaluated a second time in the act of calling FUNCTION;
  69.      `funcall' enters the normal procedure for calling a function at the
  70.      place where the arguments have already been evaluated.
  71.  
  72.      The argument FUNCTION must be either a Lisp function or a
  73.      primitive function.  Special forms and macros are not allowed,
  74.      because they make sense only when given the "unevaluated" argument
  75.      expressions.  `funcall' cannot provide these because, as we saw
  76.      above, it never knows them in the first place.
  77.  
  78.           (setq f 'list)
  79.                => list
  80.           (funcall f 'x 'y 'z)
  81.                => (x y z)
  82.           (funcall f 'x 'y '(z))
  83.                => (x y (z))
  84.           (funcall 'and t nil)
  85.           error--> Invalid function: #<subr and>
  86.  
  87.      Compare this example with that of `apply'.
  88.  
  89.  - Function: apply FUNCTION &rest ARGUMENTS
  90.      `apply' calls FUNCTION with ARGUMENTS, just like `funcall' but
  91.      with one difference: the last of ARGUMENTS is a list of arguments
  92.      to give to FUNCTION, rather than a single argument.  We also say
  93.      that this list is "appended" to the other arguments.
  94.  
  95.      `apply' returns the result of calling FUNCTION.  As with
  96.      `funcall', FUNCTION must either be a Lisp function or a primitive
  97.      function; special forms and macros do not make sense in `apply'.
  98.  
  99.           (setq f 'list)
  100.                => list
  101.           (apply f 'x 'y 'z)
  102.           error--> Wrong type argument: listp, z
  103.           (apply '+ 1 2 '(3 4))
  104.                => 10
  105.           (apply '+ '(1 2 3 4))
  106.                => 10
  107.           
  108.           (apply 'append '((a b c) nil (x y z) nil))
  109.                => (a b c x y z)
  110.  
  111.      An interesting example of using `apply' is found in the description
  112.      of `mapcar'; see the following section.
  113.  
  114.    It is common for Lisp functions to accept functions as arguments or
  115. find them in data structures (especially in hook variables and property
  116. lists) and call them using `funcall' or `apply'.  Functions that accept
  117. function arguments are often called "functionals".
  118.  
  119.    Sometimes, when you call such a function, it is useful to supply a
  120. no-op function as the argument.  Here are two different kinds of no-op
  121. function:
  122.  
  123.  - Function: identity ARG
  124.      This function returns ARG and has no side effects.
  125.  
  126.  - Function: ignore &rest ARGS
  127.      This function ignores any arguments and returns `nil'.
  128.  
  129. 
  130. File: elisp,  Node: Mapping Functions,  Next: Anonymous Functions,  Prev: Calling Functions,  Up: Functions
  131.  
  132. Mapping Functions
  133. =================
  134.  
  135.    A "mapping function" applies a given function to each element of a
  136. list or other collection.  Emacs Lisp has three such functions;
  137. `mapcar' and `mapconcat', which scan a list, are described here.  For
  138. the third mapping function, `mapatoms', see *Note Creating Symbols::.
  139.  
  140.  - Function: mapcar FUNCTION SEQUENCE
  141.      `mapcar' applies FUNCTION to each element of SEQUENCE in turn.
  142.      The results are made into a `nil'-terminated list.
  143.  
  144.      The argument SEQUENCE may be a list, a vector or a string.  The
  145.      result is always a list.  The length of the result is the same as
  146.      the length of SEQUENCE.
  147.  
  148.      For example:
  149.  
  150.           (mapcar 'car '((a b) (c d) (e f)))
  151.                => (a c e)
  152.           (mapcar '1+ [1 2 3])
  153.                => (2 3 4)
  154.           (mapcar 'char-to-string "abc")
  155.                => ("a" "b" "c")
  156.  
  157.           ;; Call each function in `my-hooks'.
  158.           (mapcar 'funcall my-hooks)
  159.  
  160.           (defun mapcar* (f &rest args)
  161.             "Apply FUNCTION to successive cars of all ARGS, until one
  162.           ends.  Return the list of results."
  163.             ;; If no list is exhausted,
  164.             (if (not (memq 'nil args))
  165.                 ;; Apply function to CARs.
  166.                 (cons (apply f (mapcar 'car args))
  167.                       (apply 'mapcar* f
  168.                              ;; Recurse for rest of elements.
  169.                              (mapcar 'cdr args)))))
  170.  
  171.           (mapcar* 'cons '(a b c) '(1 2 3 4))
  172.                => ((a . 1) (b . 2) (c . 3))
  173.  
  174.  - Function: mapconcat FUNCTION SEQUENCE SEPARATOR
  175.      `mapconcat' applies FUNCTION to each element of SEQUENCE: the
  176.      results, which must be strings, are concatenated.  Between each
  177.      pair of result strings, `mapconcat' inserts the string SEPARATOR.
  178.      Usually SEPARATOR contains a space or comma or other suitable
  179.      punctuation.
  180.  
  181.      The argument FUNCTION must be a function that can take one
  182.      argument and returns a string.
  183.  
  184.           (mapconcat 'symbol-name
  185.                      '(The cat in the hat)
  186.                      " ")
  187.                => "The cat in the hat"
  188.  
  189.           (mapconcat (function (lambda (x) (format "%c" (1+ x))))
  190.                      "HAL-8000"
  191.                      "")
  192.                => "IBM.9111"
  193.  
  194. 
  195. File: elisp,  Node: Anonymous Functions,  Next: Function Cells,  Prev: Mapping Functions,  Up: Functions
  196.  
  197. Anonymous Functions
  198. ===================
  199.  
  200.    In Lisp, a function is a list that starts with `lambda' (or
  201. alternatively a primitive subr-object); names are "extra".  Although
  202. usually functions are defined with `defun' and given names at the same
  203. time, it is occasionally more concise to use an explicit lambda
  204. expression--an anonymous function.  Such a list is valid wherever a
  205. function name is.
  206.  
  207.    Any method of creating such a list makes a valid function.  Even
  208. this:
  209.  
  210.      (setq silly (append '(lambda (x)) (list (list '+ (* 3 4) 'x))))
  211.           => (lambda (x) (+ 12 x))
  212.  
  213. This computes a list that looks like `(lambda (x) (+ 12 x))' and makes
  214. it the value (*not* the function definition!) of `silly'.
  215.  
  216.    Here is how we might call this function:
  217.  
  218.      (funcall silly 1)
  219.           => 13
  220.  
  221. (It does *not* work to write `(silly 1)', because this function is not
  222. the *function definition* of `silly'.  We have not given `silly' any
  223. function definition, just a value as a variable.)
  224.  
  225.    Most of the time, anonymous functions are constants that appear in
  226. your program.  For example, you might want to pass one as an argument
  227. to the function `mapcar', which applies any given function to each
  228. element of a list.  Here we pass an anonymous function that multiplies
  229. a number by two:
  230.  
  231.      (defun double-each (list)
  232.        (mapcar '(lambda (x) (* 2 x)) list))
  233.           => double-each
  234.      (double-each '(2 11))
  235.           => (4 22)
  236.  
  237. In such cases, we usually use the special form `function' instead of
  238. simple quotation to quote the anonymous function.
  239.  
  240.  - Special Form: function FUNCTION-OBJECT
  241.      This special form returns FUNCTION-OBJECT without evaluating it.
  242.      In this, it is equivalent to `quote'.  However, it serves as a
  243.      note to the Emacs Lisp compiler that FUNCTION-OBJECT is intended
  244.      to be used only as a function, and therefore can safely be
  245.      compiled.  *Note Quoting::, for comparison.
  246.  
  247.    Using `function' instead of `quote' makes a difference inside a
  248. function or macro that you are going to compile.  For example:
  249.  
  250.      (defun double-each (list)
  251.        (mapcar (function (lambda (x) (* 2 x))) list))
  252.           => double-each
  253.      (double-each '(2 11))
  254.           => (4 22)
  255.  
  256. If this definition of `double-each' is compiled, the anonymous function
  257. is compiled as well.  By contrast, in the previous definition where
  258. ordinary `quote' is used, the argument passed to `mapcar' is the
  259. precise list shown:
  260.  
  261.      (lambda (arg) (+ arg 5))
  262.  
  263. The Lisp compiler cannot assume this list is a function, even though it
  264. looks like one, since it does not know what `mapcar' does with the
  265. list.  Perhaps `mapcar' will check that the CAR of the third element is
  266. the symbol `+'!  The advantage of `function' is that it tells the
  267. compiler to go ahead and compile the constant function.
  268.  
  269.    We sometimes write `function' instead of `quote' when quoting the
  270. name of a function, but this usage is just a sort of comment.
  271.  
  272.      (function SYMBOL) == (quote SYMBOL) == 'SYMBOL
  273.  
  274.    See `documentation' in *Note Accessing Documentation::, for a
  275. realistic example using `function' and an anonymous function.
  276.  
  277. 
  278. File: elisp,  Node: Function Cells,  Next: Inline Functions,  Prev: Anonymous Functions,  Up: Functions
  279.  
  280. Accessing Function Cell Contents
  281. ================================
  282.  
  283.    The "function definition" of a symbol is the object stored in the
  284. function cell of the symbol.  The functions described here access, test,
  285. and set the function cell of symbols.
  286.  
  287.  - Function: symbol-function SYMBOL
  288.      This returns the object in the function cell of SYMBOL.  If the
  289.      symbol's function cell is void, a `void-function' error is
  290.      signaled.
  291.  
  292.      This function does not check that the returned object is a
  293.      legitimate function.
  294.  
  295.           (defun bar (n) (+ n 2))
  296.                => bar
  297.           (symbol-function 'bar)
  298.                => (lambda (n) (+ n 2))
  299.           (fset 'baz 'bar)
  300.                => bar
  301.           (symbol-function 'baz)
  302.                => bar
  303.  
  304.    If you have never given a symbol any function definition, we say that
  305. that symbol's function cell is "void".  In other words, the function
  306. cell does not have any Lisp object in it.  If you try to call such a
  307. symbol as a function, it signals a `void-function' error.
  308.  
  309.    Note that void is not the same as `nil' or the symbol `void'.  The
  310. symbols `nil' and `void' are Lisp objects, and can be stored into a
  311. function cell just as any other object can be (and they can be valid
  312. functions if you define them in turn with `defun'); but `nil' or `void'
  313. is *an object*.  A void function cell contains no object whatsoever.
  314.  
  315.    You can test the voidness of a symbol's function definition with
  316. `fboundp'.  After you have given a symbol a function definition, you
  317. can make it void once more using `fmakunbound'.
  318.  
  319.  - Function: fboundp SYMBOL
  320.      Returns `t' if the symbol has an object in its function cell,
  321.      `nil' otherwise.  It does not check that the object is a legitimate
  322.      function.
  323.  
  324.  - Function: fmakunbound SYMBOL
  325.      This function makes SYMBOL's function cell void, so that a
  326.      subsequent attempt to access this cell will cause a `void-function'
  327.      error.  (See also `makunbound', in *Note Local Variables::.)
  328.  
  329.           (defun foo (x) x)
  330.                => x
  331.           (fmakunbound 'foo)
  332.                => x
  333.           (foo 1)
  334.           error--> Symbol's function definition is void: foo
  335.  
  336.  - Function: fset SYMBOL OBJECT
  337.      This function stores OBJECT in the function cell of SYMBOL.  The
  338.      result is OBJECT.  Normally OBJECT should be a function or the
  339.      name of a function, but this is not checked.
  340.  
  341.      There are three normal uses of this function:
  342.  
  343.         * Copying one symbol's function definition to another.  (In
  344.           other words, making an alternate name for a function.)
  345.  
  346.         * Giving a symbol a function definition that is not a list and
  347.           therefore cannot be made with `defun'.  *Note Classifying
  348.           Lists::, for an example of this usage.
  349.  
  350.         * In constructs for defining or altering functions.  If `defun'
  351.           were not a primitive, it could be written in Lisp (as a
  352.           macro) using `fset'.
  353.  
  354.      Here are examples of the first two uses:
  355.  
  356.           ;; Give `first' the same definition `car' has.
  357.           (fset 'first (symbol-function 'car))
  358.                => #<subr car>
  359.           (first '(1 2 3))
  360.                => 1
  361.           
  362.           ;; Make the symbol `car' the function definition of `xfirst'.
  363.           (fset 'xfirst 'car)
  364.                => car
  365.           (xfirst '(1 2 3))
  366.                => 1
  367.           (symbol-function 'xfirst)
  368.                => car
  369.           (symbol-function (symbol-function 'xfirst))
  370.                => #<subr car>
  371.           
  372.           ;; Define a named keyboard macro.
  373.           (fset 'kill-two-lines "\^u2\^k")
  374.                => "\^u2\^k"
  375.  
  376.    When writing a function that extends a previously defined function,
  377. the following idiom is often used:
  378.  
  379.      (fset 'old-foo (symbol-function 'foo))
  380.      
  381.      (defun foo ()
  382.        "Just like old-foo, except more so."
  383.        (old-foo)
  384.        (more-so))
  385.  
  386. This does not work properly if `foo' has been defined to autoload.  In
  387. such a case, when `foo' calls `old-foo', Lisp attempts to define
  388. `old-foo' by loading a file.  Since this presumably defines `foo'
  389. rather than `old-foo', it does not produce the proper results.  The
  390. only way to avoid this problem is to make sure the file is loaded
  391. before moving aside the old definition of `foo'.
  392.  
  393.    See also the function `indirect-function' in *Note Function
  394. Indirection::.
  395.  
  396. 
  397. File: elisp,  Node: Inline Functions,  Next: Related Topics,  Prev: Function Cells,  Up: Functions
  398.  
  399. Inline Functions
  400. ================
  401.  
  402.    You can define an "inline function" by using `defsubst' instead of
  403. `defun'.  An inline function works just like an ordinary function
  404. except for one thing: when you compile a call to the function, the
  405. function's definition is open-coded into the caller.
  406.  
  407.    Making a function inline makes explicit calls run faster.  But it
  408. also has disadvantages.  For one thing, it reduces flexibility; if you
  409. change the definition of the function, calls already inlined still use
  410. the old definition until you recompile them.
  411.  
  412.    Another disadvantage is that making a large function inline can
  413. increase the size of compiled code both in files and in memory.  Since
  414. the advantages of inline functions are greatest for small functions, you
  415. generally should not make large functions inline.
  416.  
  417.    It's possible to define a macro to expand into the same code that an
  418. inline function would execute.  But the macro would have a limitation:
  419. you can use it only explicitly--a macro cannot be called with `apply',
  420. `mapcar' and so on.  Also, it takes some work to convert an ordinary
  421. function into a macro.  (*Note Macros::.)  To convert it into an inline
  422. function is very easy; simply replace `defun' with `defsubst'.
  423.  
  424.    Inline functions can be used and open coded later on in the same
  425. file, following the definition, just like macros.
  426.  
  427.    Emacs versions prior to 19 did not have inline functions.
  428.  
  429. 
  430. File: elisp,  Node: Related Topics,  Prev: Inline Functions,  Up: Functions
  431.  
  432. Other Topics Related to Functions
  433. =================================
  434.  
  435.    Here is a table of several functions that do things related to
  436. function calling and function definitions.  They are documented
  437. elsewhere, but we provide cross references here.
  438.  
  439. `apply'
  440.      See *Note Calling Functions::.
  441.  
  442. `autoload'
  443.      See *Note Autoload::.
  444.  
  445. `call-interactively'
  446.      See *Note Interactive Call::.
  447.  
  448. `commandp'
  449.      See *Note Interactive Call::.
  450.  
  451. `documentation'
  452.      See *Note Accessing Documentation::.
  453.  
  454. `eval'
  455.      See *Note Eval::.
  456.  
  457. `funcall'
  458.      See *Note Calling Functions::.
  459.  
  460. `ignore'
  461.      See *Note Calling Functions::.
  462.  
  463. `indirect-function'
  464.      See *Note Function Indirection::.
  465.  
  466. `interactive'
  467.      See *Note Using Interactive::.
  468.  
  469. `interactive-p'
  470.      See *Note Interactive Call::.
  471.  
  472. `mapatoms'
  473.      See *Note Creating Symbols::.
  474.  
  475. `mapcar'
  476.      See *Note Mapping Functions::.
  477.  
  478. `mapconcat'
  479.      See *Note Mapping Functions::.
  480.  
  481. `undefined'
  482.      See *Note Key Lookup::.
  483.  
  484. 
  485. File: elisp,  Node: Macros,  Next: Loading,  Prev: Functions,  Up: Top
  486.  
  487. Macros
  488. ******
  489.  
  490.    "Macros" enable you to define new control constructs and other
  491. language features.  A macro is defined much like a function, but instead
  492. of telling how to compute a value, it tells how to compute another Lisp
  493. expression which will in turn compute the value.  We call this
  494. expression the "expansion" of the macro.
  495.  
  496.    Macros can do this because they operate on the unevaluated
  497. expressions for the arguments, not on the argument values as functions
  498. do.  They can therefore construct an expansion containing these
  499. argument expressions or parts of them.
  500.  
  501.    If you are using a macro to do something an ordinary function could
  502. do, just for the sake of speed, consider using an inline function
  503. instead.  *Note Inline Functions::.
  504.  
  505. * Menu:
  506.  
  507. * Simple Macro::            A basic example.
  508. * Expansion::               How, when and why macros are expanded.
  509. * Compiling Macros::        How macros are expanded by the compiler.
  510. * Defining Macros::         How to write a macro definition.
  511. * Backquote::               Easier construction of list structure.
  512. * Problems with Macros::    Don't evaluate the macro arguments too many times.
  513.                               Don't hide the user's variables.
  514.  
  515. 
  516. File: elisp,  Node: Simple Macro,  Next: Expansion,  Prev: Macros,  Up: Macros
  517.  
  518. A Simple Example of a Macro
  519. ===========================
  520.  
  521.    Suppose we would like to define a Lisp construct to increment a
  522. variable value, much like the `++' operator in C.  We would like to
  523. write `(inc x)' and have the effect of `(setq x (1+ x))'.  Here's a
  524. macro definition that does the job:
  525.  
  526.      (defmacro inc (var)
  527.         (list 'setq var (list '1+ var)))
  528.  
  529.    When this is called with `(inc x)', the argument `var' has the value
  530. `x'--*not* the *value* of `x'.  The body of the macro uses this to
  531. construct the expansion, which is `(setq x (1+ x))'.  Once the macro
  532. definition returns this expansion, Lisp proceeds to evaluate it, thus
  533. incrementing `x'.
  534.  
  535. 
  536. File: elisp,  Node: Expansion,  Next: Compiling Macros,  Prev: Simple Macro,  Up: Macros
  537.  
  538. Expansion of a Macro Call
  539. =========================
  540.  
  541.    A macro call looks just like a function call in that it is a list
  542. which starts with the name of the macro.  The rest of the elements of
  543. the list are the arguments of the macro.
  544.  
  545.    Evaluation of the macro call begins like evaluation of a function
  546. call except for one crucial difference: the macro arguments are the
  547. actual expressions appearing in the macro call.  They are not evaluated
  548. before they are given to the macro definition.  By contrast, the
  549. arguments of a function are results of evaluating the elements of the
  550. function call list.
  551.  
  552.    Having obtained the arguments, Lisp invokes the macro definition just
  553. as a function is invoked.  The argument variables of the macro are bound
  554. to the argument values from the macro call, or to a list of them in the
  555. case of a `&rest' argument.  And the macro body executes and returns
  556. its value just as a function body does.
  557.  
  558.    The second crucial difference between macros and functions is that
  559. the value returned by the macro body is not the value of the macro call.
  560. Instead, it is an alternate expression for computing that value, also
  561. known as the "expansion" of the macro.  The Lisp interpreter proceeds
  562. to evaluate the expansion as soon as it comes back from the macro.
  563.  
  564.    Since the expansion is evaluated in the normal manner, it may contain
  565. calls to other macros.  It may even be a call to the same macro, though
  566. this is unusual.
  567.  
  568.    You can see the expansion of a given macro call by calling
  569. `macroexpand'.
  570.  
  571.  - Function: macroexpand FORM &optional ENVIRONMENT
  572.      This function expands FORM, if it is a macro call.  If the result
  573.      is another macro call, it is expanded in turn, until something
  574.      which is not a macro call results.  That is the value returned by
  575.      `macroexpand'.  If FORM is not a macro call to begin with, it is
  576.      returned as given.
  577.  
  578.      Note that `macroexpand' does not look at the subexpressions of
  579.      FORM (although some macro definitions may do so).  Even if they
  580.      are macro calls themselves, `macroexpand' does not expand them.
  581.  
  582.      The function `macroexpand' does not expand calls to inline
  583.      functions.  Normally there is no need for that, since a call to an
  584.      inline function is no harder to understand than a call to an
  585.      ordinary function.
  586.  
  587.      If ENVIRONMENT is provided, it specifies an alist of macro
  588.      definitions that shadow the currently defined macros.  This is used
  589.      by byte compilation.
  590.  
  591.           (defmacro inc (var)
  592.               (list 'setq var (list '1+ var)))
  593.                => inc
  594.  
  595.           (macroexpand '(inc r))
  596.                => (setq r (1+ r))
  597.  
  598.           (defmacro inc2 (var1 var2)
  599.               (list 'progn (list 'inc var1) (list 'inc var2)))
  600.                => inc2
  601.  
  602.           (macroexpand '(inc2 r s))
  603.                => (progn (inc r) (inc s))  ; `inc' not expanded here.
  604.  
  605. 
  606. File: elisp,  Node: Compiling Macros,  Next: Defining Macros,  Prev: Expansion,  Up: Macros
  607.  
  608. Macros and Byte Compilation
  609. ===========================
  610.  
  611.    You might ask why we take the trouble to compute an expansion for a
  612. macro and then evaluate the expansion.  Why not have the macro body
  613. produce the desired results directly?  The reason has to do with
  614. compilation.
  615.  
  616.    When a macro call appears in a Lisp program being compiled, the Lisp
  617. compiler calls the macro definition just as the interpreter would, and
  618. receives an expansion.  But instead of evaluating this expansion, it
  619. compiles the expansion as if it had appeared directly in the program.
  620. As a result, the compiled code produces the value and side effects
  621. intended for the macro, but executes at full compiled speed.  This would
  622. not work if the macro body computed the value and side effects
  623. itself--they would be computed at compile time, which is not useful.
  624.  
  625.    In order for compilation of macro calls to work, the macros must be
  626. defined in Lisp when the calls to them are compiled.  The compiler has a
  627. special feature to help you do this: if a file being compiled contains a
  628. `defmacro' form, the macro is defined temporarily for the rest of the
  629. compilation of that file.  To use this feature, you must define the
  630. macro in the same file where it is used and before its first use.
  631.  
  632.    While byte-compiling a file, any `require' calls at top-level are
  633. executed.  One way to ensure that necessary macro definitions are
  634. available during compilation is to require the file that defines them.
  635. *Note Features::.
  636.  
  637. 
  638. File: elisp,  Node: Defining Macros,  Next: Backquote,  Prev: Compiling Macros,  Up: Macros
  639.  
  640. Defining Macros
  641. ===============
  642.  
  643.    A Lisp macro is a list whose CAR is `macro'.  Its CDR should be a
  644. function; expansion of the macro works by applying the function (with
  645. `apply') to the list of unevaluated argument-expressions from the macro
  646. call.
  647.  
  648.    It is possible to use an anonymous Lisp macro just like an anonymous
  649. function, but this is never done, because it does not make sense to pass
  650. an anonymous macro to mapping functions such as `mapcar'.  In practice,
  651. all Lisp macros have names, and they are usually defined with the
  652. special form `defmacro'.
  653.  
  654.  - Special Form: defmacro NAME ARGUMENT-LIST BODY-FORMS...
  655.      `defmacro' defines the symbol NAME as a macro that looks like this:
  656.  
  657.           (macro lambda ARGUMENT-LIST . BODY-FORMS)
  658.  
  659.      This macro object is stored in the function cell of NAME.  The
  660.      value returned by evaluating the `defmacro' form is NAME, but
  661.      usually we ignore this value.
  662.  
  663.      The shape and meaning of ARGUMENT-LIST is the same as in a
  664.      function, and the keywords `&rest' and `&optional' may be used
  665.      (*note Argument List::.).  Macros may have a documentation string,
  666.      but any `interactive' declaration is ignored since macros cannot be
  667.      called interactively.
  668.  
  669. 
  670. File: elisp,  Node: Backquote,  Next: Problems with Macros,  Prev: Defining Macros,  Up: Macros
  671.  
  672. Backquote
  673. =========
  674.  
  675.    It could prove rather awkward to write macros of significant size,
  676. simply due to the number of times the function `list' needs to be
  677. called.  To make writing these forms easier, a macro ``' (often called
  678. "backquote") exists.
  679.  
  680.    Backquote allows you to quote a list, but selectively evaluate
  681. elements of that list.  In the simplest case, it is identical to the
  682. special form `quote' (*note Quoting::.).  For example, these two forms
  683. yield identical results:
  684.  
  685.      (` (a list of (+ 2 3) elements))
  686.           => (a list of (+ 2 3) elements)
  687.      (quote (a list of (+ 2 3) elements))
  688.           => (a list of (+ 2 3) elements)
  689.  
  690.    By inserting a special marker, `,', inside of the argument to
  691. backquote, it is possible to evaluate desired portions of the argument:
  692.  
  693.      (list 'a 'list 'of (+ 2 3) 'elements)
  694.           => (a list of 5 elements)
  695.      (` (a list of (, (+ 2 3)) elements))
  696.           => (a list of 5 elements)
  697.  
  698.    It is also possible to have an evaluated list "spliced" into the
  699. resulting list by using the special marker `,@'.  The elements of the
  700. spliced list become elements at the same level as the other elements of
  701. the resulting list.  The equivalent code without using ``' is often
  702. unreadable.  Here are some examples:
  703.  
  704.      (setq some-list '(2 3))
  705.           => (2 3)
  706.      (cons 1 (append some-list '(4) some-list))
  707.           => (1 2 3 4 2 3)
  708.      (` (1 (,@ some-list) 4 (,@ some-list)))
  709.           => (1 2 3 4 2 3)
  710.      
  711.      (setq list '(hack foo bar))
  712.           => (hack foo bar)
  713.      (cons 'use
  714.        (cons 'the
  715.          (cons 'words (append (cdr list) '(as elements)))))
  716.           => (use the words foo bar as elements)
  717.      (` (use the words (,@ (cdr list)) as elements (,@ nil)))
  718.           => (use the words foo bar as elements)
  719.  
  720.    The reason for `(,@ nil)' is to avoid a bug in Emacs version 18.
  721. The bug occurs when a call to `,@' is followed only by constant
  722. elements.  Thus,
  723.  
  724.      (` (use the words (,@ (cdr list)) as elements))
  725.  
  726. would not work, though it really ought to.  `(,@ nil)' avoids the
  727. problem by being a nonconstant element that does not affect the result.
  728.  
  729.  - Macro: ` LIST
  730.      This macro returns LIST as `quote' would, except that the list is
  731.      copied each time this expression is evaluated, and any sublist of
  732.      the form `(, SUBEXP)' is replaced by the value of SUBEXP.  Any
  733.      sublist of the form `(,@ LISTEXP)' is replaced by evaluating
  734.      LISTEXP and splicing its elements into the containing list in
  735.      place of this sublist.  (A single sublist can in this way be
  736.      replaced by any number of new elements in the containing list.)
  737.  
  738.      There are certain contexts in which `,' would not be recognized and
  739.      should not be used:
  740.  
  741.           ;; Use of a `,' expression as the CDR of a list.
  742.           (` (a . (, 1)))                             ; Not `(a . 1)'
  743.                => (a \, 1)
  744.  
  745.           ;; Use of `,' in a vector.
  746.           (` [a (, 1) c])                             ; Not `[a 1 c]'
  747.                error--> Wrong type argument
  748.  
  749.           ;; Use of a `,' as the entire argument of ``'.
  750.           (` (, 2))                                   ; Not 2
  751.                => (\, 2)
  752.  
  753.      Common Lisp note: in Common Lisp, `,' and `,@' are implemented as
  754.      reader macros, so they do not require parentheses.  Emacs Lisp
  755.      implements them as functions because reader macros are not
  756.      supported (to save space).
  757.  
  758. 
  759. File: elisp,  Node: Problems with Macros,  Prev: Backquote,  Up: Macros
  760.  
  761. Common Problems Using Macros
  762. ============================
  763.  
  764.    The basic facts of macro expansion have all been described above, but
  765. there consequences are often counterintuitive.  This section describes
  766. some important consequences that can lead to trouble, and rules to
  767. follow to avoid trouble.
  768.  
  769. * Menu:
  770.  
  771. * Argument Evaluation::    The expansion should evaluate each macro arg once.
  772. * Surprising Local Vars::  Local variable bindings in the expansion
  773.                               require special care.
  774. * Eval During Expansion::  Don't evaluate them; put them in the expansion.
  775. * Repeated Expansion::     Avoid depending on how many times expansion is done.
  776.  
  777. 
  778. File: elisp,  Node: Argument Evaluation,  Next: Surprising Local Vars,  Prev: Problems with Macros,  Up: Problems with Macros
  779.  
  780. Evaluating Macro Arguments Too Many Times
  781. -----------------------------------------
  782.  
  783.    When defining a macro you must pay attention to the number of times
  784. the arguments will be evaluated when the expansion is executed.  The
  785. following macro (used to facilitate iteration) illustrates the problem.
  786. This macro allows us to write a simple "for" loop such as one might
  787. find in Pascal.
  788.  
  789.      (defmacro for (var from init to final do &rest body)
  790.        "Execute a simple \"for\" loop, e.g.,
  791.          (for i from 1 to 10 do (print i))."
  792.        (list 'let (list (list var init))
  793.              (cons 'while (cons (list '<= var final)
  794.                                 (append body (list (list 'inc var)))))))
  795.      => for
  796.      (for i from 1 to 3 do
  797.         (setq square (* i i))
  798.         (princ (format "\n%d %d" i square)))
  799.      ==>
  800.  
  801.      (let ((i 1))
  802.        (while (<= i 3)
  803.          (setq square (* i i))
  804.          (princ (format "%d      %d" i square))
  805.          (inc i)))
  806.  
  807.  
  808.      -|1       1
  809.           -|2       4
  810.           -|3       9
  811.      => nil
  812.  
  813. (The arguments `from', `to', and `do' in this macro are "syntactic
  814. sugar"; they are entirely ignored.  The idea is that you will write
  815. noise words (such as `from', `to', and `do') in those positions in the
  816. macro call.)
  817.  
  818.    This macro suffers from the defect that FINAL is evaluated on every
  819. iteration.  If FINAL is a constant, this is not a problem.  If it is a
  820. more complex form, say `(long-complex-calculation x)', this can slow
  821. down the execution significantly.  If FINAL has side effects, executing
  822. it more than once is probably incorrect.
  823.  
  824.    A well-designed macro definition takes steps to avoid this problem by
  825. producing an expansion that evaluates the argument expressions exactly
  826. once unless repeated evaluation is part of the intended purpose of the
  827. macro.  Here is a correct expansion for the `for' macro:
  828.  
  829.      (let ((i 1)
  830.            (max 3))
  831.        (while (<= i max)
  832.          (setq square (* i i))
  833.          (princ (format "%d      %d" i square))
  834.          (inc i)))
  835.  
  836.    Here is a macro definition that creates this expansion:
  837.  
  838.      (defmacro for (var from init to final do &rest body)
  839.        "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  840.        (` (let (((, var) (, init))
  841.                 (max (, final)))
  842.             (while (<= (, var) max)
  843.               (,@ body)
  844.               (inc (, var))))))
  845.  
  846.    Unfortunately, this introduces another problem.  Proceed to the
  847. following node.
  848.  
  849. 
  850. File: elisp,  Node: Surprising Local Vars,  Next: Eval During Expansion,  Prev: Argument Evaluation,  Up: Problems with Macros
  851.  
  852. Local Variables in Macro Expansions
  853. -----------------------------------
  854.  
  855.    In the previous section, the definition of `for' was fixed as
  856. follows to make the expansion evaluate the macro arguments the proper
  857. number of times:
  858.  
  859.      (defmacro for (var from init to final do &rest body)
  860.        "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  861.  
  862.      (` (let (((, var) (, init))
  863.                 (max (, final)))
  864.             (while (<= (, var) max)
  865.               (,@ body)
  866.               (inc (, var))))))
  867.  
  868.    The new definition of `for' has a new problem: it introduces a local
  869. variable named `max' which the user does not expect.  This causes
  870. trouble in examples such as the following:
  871.  
  872.      (let ((max 0))
  873.        (for x from 0 to 10 do
  874.          (let ((this (frob x)))
  875.            (if (< max this)
  876.                (setq max this)))))
  877.  
  878. The references to `max' inside the body of the `for', which are
  879. supposed to refer to the user's binding of `max', really access the
  880. binding made by `for'.
  881.  
  882.    The way to correct this is to use an uninterned symbol instead of
  883. `max' (*note Creating Symbols::.).  The uninterned symbol can be bound
  884. and referred to just like any other symbol, but since it is created by
  885. `for', we know that it cannot appear in the user's program.  Since it
  886. is not interned, there is no way the user can put it into the program
  887. later.  It will never appear anywhere except where put by `for'.  Here
  888. is a definition of `for' which works this way:
  889.  
  890.      (defmacro for (var from init to final do &rest body)
  891.        "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  892.        (let ((tempvar (make-symbol "max")))
  893.          (` (let (((, var) (, init))
  894.                   ((, tempvar) (, final)))
  895.               (while (<= (, var) (, tempvar))
  896.                      (,@ body)
  897.                      (inc (, var)))))))
  898.  
  899. This creates an uninterned symbol named `max' and puts it in the
  900. expansion instead of the usual interned symbol `max' that appears in
  901. expressions ordinarily.
  902.  
  903. 
  904. File: elisp,  Node: Eval During Expansion,  Next: Repeated Expansion,  Prev: Surprising Local Vars,  Up: Problems with Macros
  905.  
  906. Evaluating Macro Arguments in Expansion
  907. ---------------------------------------
  908.  
  909.    Another problem can happen if you evaluate any of the macro argument
  910. expressions during the computation of the expansion, such as by calling
  911. `eval' (*note Eval::.).  If the argument is supposed to refer to the
  912. user's variables, you may have trouble if the user happens to use a
  913. variable with the same name as one of the macro arguments.  Inside the
  914. macro body, the macro argument binding is the most local binding of this
  915. variable, so any references inside the form being evaluated do refer to
  916. it.  Here is an example:
  917.  
  918.      (defmacro foo (a)
  919.        (list 'setq (eval a) t))
  920.           => foo
  921.      (setq x 'b)
  922.      (foo x) ==> (setq b t)
  923.           => t                  ; and `b' has been set.
  924.      ;; but
  925.      (setq a 'b)
  926.      (foo a) ==> (setq 'b t)     ; invalid!
  927.      error--> Symbol's value is void: b
  928.  
  929.    It makes a difference whether the user types `a' or `x', because `a'
  930. conflicts with the macro argument variable `a'.
  931.  
  932.    In general it is best to avoid calling `eval' in a macro definition
  933. at all.
  934.  
  935. 
  936. File: elisp,  Node: Repeated Expansion,  Prev: Eval During Expansion,  Up: Problems with Macros
  937.  
  938. How Many Times is the Macro Expanded?
  939. -------------------------------------
  940.  
  941.    Occasionally problems result from the fact that a macro call is
  942. expanded each time it is evaluated in an interpreted function, but is
  943. expanded only once (during compilation) for a compiled function.  If the
  944. macro definition has side effects, they will work differently depending
  945. on how many times the macro is expanded.
  946.  
  947.    In particular, constructing objects is a kind of side effect.  If the
  948. macro is called once, then the objects are constructed only once.  In
  949. other words, the same structure of objects is used each time the macro
  950. call is executed.  In interpreted operation, the macro is reexpanded
  951. each time, producing a fresh collection of objects each time.  Usually
  952. this does not matter--the objects have the same contents whether they
  953. are shared or not.  But if the surrounding program does side effects on
  954. the objects, it makes a difference whether they are shared.  Here is an
  955. example:
  956.  
  957.      (defmacro new-object ()
  958.        (list 'quote (cons nil nil)))
  959.  
  960.      (defun initialize (condition)
  961.        (let ((object (new-object)))
  962.          (if condition
  963.          (setcar object condition))
  964.          object))
  965.  
  966. If `initialize' is interpreted, a new list `(nil)' is constructed each
  967. time `initialize' is called.  Thus, no side effect survives between
  968. calls.  If `initialize' is compiled, then the macro `new-object' is
  969. expanded during compilation, producing a single "constant" `(nil)' that
  970. is reused and altered each time `initialize' is called.
  971.  
  972. 
  973. File: elisp,  Node: Loading,  Next: Byte Compilation,  Prev: Macros,  Up: Top
  974.  
  975. Loading
  976. *******
  977.  
  978.    Loading a file of Lisp code means bringing its contents into the Lisp
  979. environment in the form of Lisp objects.  Emacs finds and opens the
  980. file, reads the text, evaluates each form, and then closes the file.
  981.  
  982.    The load functions evaluate all the expressions in a file just as
  983. the `eval-current-buffer' function evaluates all the expressions in a
  984. buffer.  The difference is that the load functions read and evaluate
  985. the text in the file as found on disk, not the text in an Emacs buffer.
  986.  
  987.    The loaded file must contain Lisp expressions, either as source code
  988. or, optionally, as byte-compiled code.  Each form in the file is called
  989. a "top-level form".  There is no special format for the forms in a
  990. loadable file; any form in a file may equally well be typed directly
  991. into a buffer and evaluated there.  (Indeed, most code is tested this
  992. way.)  Most often, the forms are function definitions and variable
  993. definitions.
  994.  
  995.    A file containing Lisp code is often called a "library".  Thus, the
  996. "Rmail library" is a file containing code for Rmail mode.  Similarly, a
  997. "Lisp library directory" is a directory of files containing Lisp code.
  998.  
  999. * Menu:
  1000.  
  1001. * How Programs Do Loading::     The `load' function and others.
  1002. * Autoload::                    Setting up a function to autoload.
  1003. * Repeated Loading::            Precautions about loading a file twice.
  1004. * Features::                    Loading a library if it isn't already loaded.
  1005. * Unloading::            How to "unload" a library that was loaded.
  1006. * Hooks for Loading::        Providing code to be run when
  1007.                   particular libraries are loaded.
  1008.  
  1009. 
  1010. File: elisp,  Node: How Programs Do Loading,  Next: Autoload,  Up: Loading
  1011.  
  1012. How Programs Do Loading
  1013. =======================
  1014.  
  1015.    There are several interface functions for loading.  For example, the
  1016. `autoload' function creates a Lisp object that loads a file when it is
  1017. evaluated (*note Autoload::.).  `require' also causes files to be
  1018. loaded (*note Features::.).  Ultimately, all these facilities call the
  1019. `load' function to do the work.
  1020.  
  1021.  - Function: load FILENAME &optional MISSING-OK NOMESSAGE NOSUFFIX
  1022.      This function finds and opens a file of Lisp code, evaluates all
  1023.      the forms in it, and closes the file.
  1024.  
  1025.      To find the file, `load' first looks for a file named
  1026.      `FILENAME.elc', that is, for a file whose name has `.elc'
  1027.      appended.  If such a file exists, it is loaded.  But if there is
  1028.      no file by that name, then `load' looks for a file whose name has
  1029.      `.el' appended.  If that file exists, it is loaded.  Finally, if
  1030.      there is no file by either name, `load' looks for a file named
  1031.      FILENAME with nothing appended, and loads it if it exists.  (The
  1032.      `load' function is not clever about looking at FILENAME.  In the
  1033.      perverse case of a file named `foo.el.el', evaluation of `(load
  1034.      "foo.el")' will indeed find it.)
  1035.  
  1036.      If the optional argument NOSUFFIX is non-`nil', then the suffixes
  1037.      `.elc' and `.el' are not tried.  In this case, you must specify
  1038.      the precise file name you want.
  1039.  
  1040.      If FILENAME is a relative file name, such as `foo' or
  1041.      `baz/foo.bar', `load' searches for the file using the variable
  1042.      `load-path'.  It appends FILENAME to each of the directories
  1043.      listed in `load-path', and loads the first file it finds whose
  1044.      name matches.  The current default directory is tried only if it is
  1045.      specified in `load-path', where it is represented as `nil'.  All
  1046.      three possible suffixes are tried in the first directory in
  1047.      `load-path', then all three in the second directory in
  1048.      `load-path', etc.
  1049.  
  1050.      If you get a warning that `foo.elc' is older than `foo.el', it
  1051.      means you should consider recompiling `foo.el'.  *Note Byte
  1052.      Compilation::.
  1053.  
  1054.      Messages like `Loading foo...' and `Loading foo...done' appear in
  1055.      the echo area during loading unless NOMESSAGE is non-`nil'.
  1056.  
  1057.      Any errors that are encountered while loading a file cause `load'
  1058.      to abort.  If the load was done for the sake of `autoload', certain
  1059.      kinds of top-level forms, those which define functions, are undone.
  1060.  
  1061.      The error `file-error' is signaled (with `Cannot open load file
  1062.      FILENAME') if no file is found.  No error is signaled if
  1063.      MISSING-OK is non-`nil'--then `load' just returns `nil'.
  1064.  
  1065.      `load' returns `t' if the file loads successfully.
  1066.  
  1067.  - User Option: load-path
  1068.      The value of this variable is a list of directories to search when
  1069.      loading files with `load'.  Each element is a string (which must be
  1070.      a directory name) or `nil' (which stands for the current working
  1071.      directory).  The value of `load-path' is initialized from the
  1072.      environment variable `EMACSLOADPATH', if it exists; otherwise it is
  1073.      set to the default specified in `emacs/src/paths.h' when Emacs is
  1074.      built.
  1075.  
  1076.      The syntax of `EMACSLOADPATH' is the same as that of `PATH';
  1077.      fields are separated by `:', and `.' is used for the current
  1078.      default directory.  Here is an example of how to set your
  1079.      `EMACSLOADPATH' variable from a `csh' `.login' file:
  1080.  
  1081.           setenv EMACSLOADPATH .:/user/bil/emacs:/usr/lib/emacs/lisp
  1082.  
  1083.      Here is how to set it using `sh':
  1084.  
  1085.           export EMACSLOADPATH
  1086.           EMACSLOADPATH=.:/user/bil/emacs:/usr/local/lib/emacs/lisp
  1087.  
  1088.      Here is an example of code you can place in a `.emacs' file to add
  1089.      several directories to the front of your default `load-path':
  1090.  
  1091.           (setq load-path
  1092.                 (append
  1093.                  (list nil
  1094.                        "/user/bil/emacs"
  1095.                        "/usr/local/lisplib")
  1096.                  load-path))
  1097.  
  1098.      In this example, the path searches the current working directory
  1099.      first, followed then by the `/user/bil/emacs' directory and then by
  1100.      the `/usr/local/lisplib' directory, which are then followed by the
  1101.      standard directories for Lisp code.
  1102.  
  1103.      When Emacs version 18 processes command options `-l' or `-load'
  1104.      which specify Lisp libraries to be loaded, it temporarily adds the
  1105.      current directory to the front of `load-path' so that files in the
  1106.      current directory can be specified easily.  Newer Emacs versions
  1107.      also find such files in the current directory, but without
  1108.      altering `load-path'.
  1109.  
  1110.  - Variable: load-in-progress
  1111.      This variable is non-`nil' if Emacs is in the process of loading a
  1112.      file, and it is `nil' otherwise.  This is how `defun' and
  1113.      `provide' determine whether a load is in progress, so that their
  1114.      effect can be undone if the load fails.
  1115.  
  1116.    To learn how `load' is used to build Emacs, see *Note Building
  1117. Emacs::.
  1118.  
  1119. 
  1120. File: elisp,  Node: Autoload,  Next: Repeated Loading,  Prev: How Programs Do Loading,  Up: Loading
  1121.  
  1122. Autoload
  1123. ========
  1124.  
  1125.    The "autoload" facility allows you to make a function or macro
  1126. available but put off loading its actual definition.  An attempt to call
  1127. a symbol whose definition is an autoload object automatically reads the
  1128. file to install the real definition and its other associated code, and
  1129. then calls the real definition.
  1130.  
  1131.    To prepare a function or macro for autoloading, you must call
  1132. `autoload', specifying the function name and the name of the file to be
  1133. loaded.  A file such as `emacs/lisp/loaddefs.el' usually does this when
  1134. Emacs is first built.
  1135.  
  1136.    The following example shows how `doctor' is prepared for autoloading
  1137. in `loaddefs.el':
  1138.  
  1139.      (autoload 'doctor "doctor"
  1140.        "\
  1141.      Switch to *doctor* buffer and start giving psychotherapy."
  1142.        t)
  1143.  
  1144. The backslash and newline immediately following the double-quote are a
  1145. convention used only in the preloaded Lisp files such as `loaddefs.el';
  1146. they cause the documentation string to be put in the `etc/DOC' file.
  1147. (*Note Building Emacs::.)  In any other source file, you would write
  1148. just this:
  1149.  
  1150.      (autoload 'doctor "doctor"
  1151.        "Switch to *doctor* buffer and start giving psychotherapy."
  1152.        t)
  1153.  
  1154.    Calling `autoload' creates an autoload object containing the name of
  1155. the file and some other information, and makes this the function
  1156. definition of the specified symbol.  When you later try to call that
  1157. symbol as a function or macro, the file is loaded; the loading should
  1158. redefine that symbol with its proper definition.  After the file
  1159. completes loading, the function or macro is called as if it had been
  1160. there originally.
  1161.  
  1162.    If, at the end of loading the file, the desired Lisp function or
  1163. macro has not been defined, then the error `error' is signaled (with
  1164. data `"Autoloading failed to define function FUNCTION-NAME"').
  1165.  
  1166.    The autoloaded file may, of course, contain other definitions and may
  1167. require or provide one or more features.  If the file is not completely
  1168. loaded (due to an error in the evaluation of the contents) any function
  1169. definitions or `provide' calls that occurred during the load are
  1170. undone.  This is to ensure that the next attempt to call any function
  1171. autoloading from this file will try again to load the file.  If not for
  1172. this, then some of the functions in the file might appear defined, but
  1173. they may fail to work properly for the lack of certain subroutines
  1174. defined later in the file and not loaded successfully.
  1175.  
  1176.    Emacs as distributed comes with many autoloaded functions.  The
  1177. calls to `autoload' are in the file `loaddefs.el'.  There is a
  1178. convenient way of updating them automatically.
  1179.  
  1180.    Write `;;;###autoload' on a line by itself before the real
  1181. definition of the function, in its autoloadable source file; then the
  1182. command `M-x update-file-autoloads' automatically puts the `autoload'
  1183. call into `loaddefs.el'.  `M-x update-directory-autoloads' is more
  1184. powerful; it updates autoloads for all files in the current directory.
  1185.  
  1186.    You can also put other kinds of forms into `loaddefs.el', by writing
  1187. `;;;###autoload' followed on the same line by the form.  `M-x
  1188. update-file-autoloads' copies the form from that line.
  1189.  
  1190.    The commands for updating autoloads work by visiting and editing the
  1191. file `loaddefs.el'.  To make the result take effect, you must save that
  1192. file's buffer.
  1193.  
  1194.  - Function: autoload SYMBOL FILENAME &optional DOCSTRING INTERACTIVE
  1195.           TYPE
  1196.      This function defines the function (or macro) named SYMBOL so as
  1197.      to load automatically from FILENAME.  The string FILENAME is a
  1198.      file name which will be passed to `load' when the function is
  1199.      called.
  1200.  
  1201.      The argument DOCSTRING is the documentation string for the
  1202.      function.  Normally, this is the same string that is in the
  1203.      function definition itself.  This makes it possible to look at the
  1204.      documentation without loading the real definition.
  1205.  
  1206.      If INTERACTIVE is non-`nil', then the function can be called
  1207.      interactively.  This lets completion in `M-x' work without loading
  1208.      the function's real definition.  The complete interactive
  1209.      specification need not be given here.  If TYPE is `macro', then
  1210.      the function is really a macro.  If TYPE is `keymap', then the
  1211.      function is really a keymap.
  1212.  
  1213.      If SYMBOL already has a non-`nil' function definition that is not
  1214.      an autoload object, `autoload' does nothing and returns `nil'.  If
  1215.      the function cell of SYMBOL is void, or is already an autoload
  1216.      object, then it is set to an autoload object that looks like this:
  1217.  
  1218.           (autoload FILENAME DOCSTRING INTERACTIVE TYPE)
  1219.  
  1220.      For example,
  1221.  
  1222.           (symbol-function 'run-prolog)
  1223.                => (autoload "prolog" 169681 t nil)
  1224.  
  1225.      In this case, `"prolog"' is the name of the file to load, 169681
  1226.      refers to the documentation string in the `emacs/etc/DOC' file
  1227.      (*note Documentation Basics::.), `t' means the function is
  1228.      interactive, and `nil' that it is not a macro.
  1229.  
  1230. 
  1231. File: elisp,  Node: Repeated Loading,  Next: Features,  Prev: Autoload,  Up: Loading
  1232.  
  1233. Repeated Loading
  1234. ================
  1235.  
  1236.    You may load a file more than once in an Emacs session.  For
  1237. example, after you have rewritten and reinstalled a function definition
  1238. by editing it in a buffer, you may wish to return to the original
  1239. version; you can do this by reloading the file in which it is located.
  1240.  
  1241.    When you load or reload files, bear in mind that the `load' and
  1242. `load-library' functions automatically load a byte-compiled file rather
  1243. than a non-compiled file of similar name.  If you rewrite a file that
  1244. you intend to save and reinstall, remember to byte-compile it if
  1245. necessary; otherwise you may find yourself inadvertently reloading the
  1246. older, byte-compiled file instead of your newer, non-compiled file!
  1247.  
  1248.    When writing the forms in a library, keep in mind that the library
  1249. might be loaded more than once.  For example, the choice of `defvar'
  1250. vs. `defconst' for defining a variable depends on whether it is
  1251. desirable to reinitialize the variable if the library is reloaded:
  1252. `defconst' does so, and `defvar' does not.  (*Note Defining
  1253. Variables::.)
  1254.  
  1255.    The simplest way to add an element to an alist is like this:
  1256.  
  1257.      (setq minor-mode-alist
  1258.            (cons '(leif-mode " Leif") minor-mode-alist))
  1259.  
  1260. But this would add multiple elements if the library is reloaded.  To
  1261. avoid the problem, write this:
  1262.  
  1263.      (or (assq 'leif-mode minor-mode-alist)
  1264.          (setq minor-mode-alist
  1265.                (cons '(leif-mode " Leif") minor-mode-alist)))
  1266.  
  1267.    Occasionally you will want to test explicitly whether a library has
  1268. already been loaded; you can do so as follows:
  1269.  
  1270.      (if (not (boundp 'foo-was-loaded))
  1271.          EXECUTE-FIRST-TIME-ONLY)
  1272.      
  1273.      (setq foo-was-loaded t)
  1274.  
  1275.