home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / prgramer / unix / info / elisp.i08 < prev    next >
Encoding:
GNU Info File  |  1993-06-14  |  44.5 KB  |  1,095 lines

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