Merge r21-2-24-utf-2000-0_13-0.
[chise/xemacs-chise.git-] / info / lispref.info-16
1 This is ../info/lispref.info, produced by makeinfo version 3.12s from
2 lispref/lispref.texi.
3
4 INFO-DIR-SECTION XEmacs Editor
5 START-INFO-DIR-ENTRY
6 * Lispref: (lispref).           XEmacs Lisp Reference Manual.
7 END-INFO-DIR-ENTRY
8
9    Edition History:
10
11    GNU Emacs Lisp Reference Manual Second Edition (v2.01), May 1993 GNU
12 Emacs Lisp Reference Manual Further Revised (v2.02), August 1993 Lucid
13 Emacs Lisp Reference Manual (for 19.10) First Edition, March 1994
14 XEmacs Lisp Programmer's Manual (for 19.12) Second Edition, April 1995
15 GNU Emacs Lisp Reference Manual v2.4, June 1995 XEmacs Lisp
16 Programmer's Manual (for 19.13) Third Edition, July 1995 XEmacs Lisp
17 Reference Manual (for 19.14 and 20.0) v3.1, March 1996 XEmacs Lisp
18 Reference Manual (for 19.15 and 20.1, 20.2, 20.3) v3.2, April, May,
19 November 1997 XEmacs Lisp Reference Manual (for 21.0) v3.3, April 1998
20
21    Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995 Free Software
22 Foundation, Inc.  Copyright (C) 1994, 1995 Sun Microsystems, Inc.
23 Copyright (C) 1995, 1996 Ben Wing.
24
25    Permission is granted to make and distribute verbatim copies of this
26 manual provided the copyright notice and this permission notice are
27 preserved on all copies.
28
29    Permission is granted to copy and distribute modified versions of
30 this manual under the conditions for verbatim copying, provided that the
31 entire resulting derived work is distributed under the terms of a
32 permission notice identical to this one.
33
34    Permission is granted to copy and distribute translations of this
35 manual into another language, under the above conditions for modified
36 versions, except that this permission notice may be stated in a
37 translation approved by the Foundation.
38
39    Permission is granted to copy and distribute modified versions of
40 this manual under the conditions for verbatim copying, provided also
41 that the section entitled "GNU General Public License" is included
42 exactly as in the original, and provided that the entire resulting
43 derived work is distributed under the terms of a permission notice
44 identical to this one.
45
46    Permission is granted to copy and distribute translations of this
47 manual into another language, under the above conditions for modified
48 versions, except that the section entitled "GNU General Public License"
49 may be included in a translation approved by the Free Software
50 Foundation instead of in the original English.
51
52 \1f
53 File: lispref.info,  Node: High-Level Completion,  Next: Reading File Names,  Prev: Completion Commands,  Up: Completion
54
55 High-Level Completion  Functions
56 --------------------------------
57
58    This section describes the higher-level convenient functions for
59 reading certain sorts of names with completion.
60
61    In most cases, you should not call these functions in the middle of a
62 Lisp function.  When possible, do all minibuffer input as part of
63 reading the arguments for a command, in the `interactive' spec.  *Note
64 Defining Commands::.
65
66  - Function: read-buffer prompt &optional default existing
67      This function reads the name of a buffer and returns it as a
68      string.  The argument DEFAULT is the default name to use, the
69      value to return if the user exits with an empty minibuffer.  If
70      non-`nil', it should be a string or a buffer.  It is mentioned in
71      the prompt, but is not inserted in the minibuffer as initial input.
72
73      If EXISTING is non-`nil', then the name specified must be that of
74      an existing buffer.  The usual commands to exit the minibuffer do
75      not exit if the text is not valid, and <RET> does completion to
76      attempt to find a valid name.  (However, DEFAULT is not checked
77      for validity; it is returned, whatever it is, if the user exits
78      with the minibuffer empty.)
79
80      In the following example, the user enters `minibuffer.t', and then
81      types <RET>.  The argument EXISTING is `t', and the only buffer
82      name starting with the given input is `minibuffer.texi', so that
83      name is the value.
84
85           (read-buffer "Buffer name? " "foo" t)
86           ;; After evaluation of the preceding expression,
87           ;;   the following prompt appears,
88           ;;   with an empty minibuffer:
89           
90           ---------- Buffer: Minibuffer ----------
91           Buffer name? (default foo) -!-
92           ---------- Buffer: Minibuffer ----------
93           
94           ;; The user types `minibuffer.t <RET>'.
95                => "minibuffer.texi"
96
97  - Function: read-command prompt
98      This function reads the name of a command and returns it as a Lisp
99      symbol.  The argument PROMPT is used as in `read-from-minibuffer'.
100      Recall that a command is anything for which `commandp' returns
101      `t', and a command name is a symbol for which `commandp' returns
102      `t'.  *Note Interactive Call::.
103
104           (read-command "Command name? ")
105           
106           ;; After evaluation of the preceding expression,
107           ;;   the following prompt appears with an empty minibuffer:
108           
109           ---------- Buffer: Minibuffer ----------
110           Command name?
111           ---------- Buffer: Minibuffer ----------
112
113      If the user types `forward-c <RET>', then this function returns
114      `forward-char'.
115
116      The `read-command' function is a simplified interface to the
117      function `completing-read'.  It uses the variable `obarray' so as
118      to complete in the set of extant Lisp symbols, and it uses the
119      `commandp' predicate so as to accept only command names:
120
121           (read-command PROMPT)
122           ==
123           (intern (completing-read PROMPT obarray
124                                    'commandp t nil))
125
126  - Function: read-variable prompt
127      This function reads the name of a user variable and returns it as a
128      symbol.
129
130           (read-variable "Variable name? ")
131           
132           ;; After evaluation of the preceding expression,
133           ;;   the following prompt appears,
134           ;;   with an empty minibuffer:
135           
136           ---------- Buffer: Minibuffer ----------
137           Variable name? -!-
138           ---------- Buffer: Minibuffer ----------
139
140      If the user then types `fill-p <RET>', `read-variable' returns
141      `fill-prefix'.
142
143      This function is similar to `read-command', but uses the predicate
144      `user-variable-p' instead of `commandp':
145
146           (read-variable PROMPT)
147           ==
148           (intern
149            (completing-read PROMPT obarray
150                             'user-variable-p t nil))
151
152 \1f
153 File: lispref.info,  Node: Reading File Names,  Next: Programmed Completion,  Prev: High-Level Completion,  Up: Completion
154
155 Reading File Names
156 ------------------
157
158    Here is another high-level completion function, designed for reading
159 a file name.  It provides special features including automatic insertion
160 of the default directory.
161
162  - Function: read-file-name prompt &optional directory default existing
163           initial
164      This function reads a file name in the minibuffer, prompting with
165      PROMPT and providing completion.  If DEFAULT is non-`nil', then
166      the function returns DEFAULT if the user just types <RET>.
167      DEFAULT is not checked for validity; it is returned, whatever it
168      is, if the user exits with the minibuffer empty.
169
170      If EXISTING is non-`nil', then the user must specify the name of
171      an existing file; <RET> performs completion to make the name valid
172      if possible, and then refuses to exit if it is not valid.  If the
173      value of EXISTING is neither `nil' nor `t', then <RET> also
174      requires confirmation after completion.  If EXISTING is `nil',
175      then the name of a nonexistent file is acceptable.
176
177      The argument DIRECTORY specifies the directory to use for
178      completion of relative file names.  If `insert-default-directory'
179      is non-`nil', DIRECTORY is also inserted in the minibuffer as
180      initial input.  It defaults to the current buffer's value of
181      `default-directory'.
182
183      If you specify INITIAL, that is an initial file name to insert in
184      the buffer (after with DIRECTORY, if that is inserted).  In this
185      case, point goes at the beginning of INITIAL.  The default for
186      INITIAL is `nil'--don't insert any file name.  To see what INITIAL
187      does, try the command `C-x C-v'.
188
189      Here is an example:
190
191           (read-file-name "The file is ")
192           
193           ;; After evaluation of the preceding expression,
194           ;;   the following appears in the minibuffer:
195           
196           ---------- Buffer: Minibuffer ----------
197           The file is /gp/gnu/elisp/-!-
198           ---------- Buffer: Minibuffer ----------
199
200      Typing `manual <TAB>' results in the following:
201
202           ---------- Buffer: Minibuffer ----------
203           The file is /gp/gnu/elisp/manual.texi-!-
204           ---------- Buffer: Minibuffer ----------
205
206      If the user types <RET>, `read-file-name' returns the file name as
207      the string `"/gp/gnu/elisp/manual.texi"'.
208
209  - User Option: insert-default-directory
210      This variable is used by `read-file-name'.  Its value controls
211      whether `read-file-name' starts by placing the name of the default
212      directory in the minibuffer, plus the initial file name if any.
213      If the value of this variable is `nil', then `read-file-name' does
214      not place any initial input in the minibuffer (unless you specify
215      initial input with the INITIAL argument).  In that case, the
216      default directory is still used for completion of relative file
217      names, but is not displayed.
218
219      For example:
220
221           ;; Here the minibuffer starts out with the default directory.
222           (let ((insert-default-directory t))
223             (read-file-name "The file is "))
224           
225           ---------- Buffer: Minibuffer ----------
226           The file is ~lewis/manual/-!-
227           ---------- Buffer: Minibuffer ----------
228           
229           ;; Here the minibuffer is empty and only the prompt
230           ;;   appears on its line.
231           (let ((insert-default-directory nil))
232             (read-file-name "The file is "))
233           
234           ---------- Buffer: Minibuffer ----------
235           The file is -!-
236           ---------- Buffer: Minibuffer ----------
237
238 \1f
239 File: lispref.info,  Node: Programmed Completion,  Prev: Reading File Names,  Up: Completion
240
241 Programmed Completion
242 ---------------------
243
244    Sometimes it is not possible to create an alist or an obarray
245 containing all the intended possible completions.  In such a case, you
246 can supply your own function to compute the completion of a given
247 string.  This is called "programmed completion".
248
249    To use this feature, pass a symbol with a function definition as the
250 COLLECTION argument to `completing-read'.  The function
251 `completing-read' arranges to pass your completion function along to
252 `try-completion' and `all-completions', which will then let your
253 function do all the work.
254
255    The completion function should accept three arguments:
256
257    * The string to be completed.
258
259    * The predicate function to filter possible matches, or `nil' if
260      none.  Your function should call the predicate for each possible
261      match, and ignore the possible match if the predicate returns
262      `nil'.
263
264    * A flag specifying the type of operation.
265
266    There are three flag values for three operations:
267
268    * `nil' specifies `try-completion'.  The completion function should
269      return the completion of the specified string, or `t' if the
270      string is an exact match already, or `nil' if the string matches no
271      possibility.
272
273    * `t' specifies `all-completions'.  The completion function should
274      return a list of all possible completions of the specified string.
275
276    * `lambda' specifies a test for an exact match.  The completion
277      function should return `t' if the specified string is an exact
278      match for some possibility; `nil' otherwise.
279
280    It would be consistent and clean for completion functions to allow
281 lambda expressions (lists that are functions) as well as function
282 symbols as COLLECTION, but this is impossible.  Lists as completion
283 tables are already assigned another meaning--as alists.  It would be
284 unreliable to fail to handle an alist normally because it is also a
285 possible function.  So you must arrange for any function you wish to
286 use for completion to be encapsulated in a symbol.
287
288    Emacs uses programmed completion when completing file names.  *Note
289 File Name Completion::.
290
291 \1f
292 File: lispref.info,  Node: Yes-or-No Queries,  Next: Multiple Queries,  Prev: Completion,  Up: Minibuffers
293
294 Yes-or-No Queries
295 =================
296
297    This section describes functions used to ask the user a yes-or-no
298 question.  The function `y-or-n-p' can be answered with a single
299 character; it is useful for questions where an inadvertent wrong answer
300 will not have serious consequences.  `yes-or-no-p' is suitable for more
301 momentous questions, since it requires three or four characters to
302 answer.  Variations of these functions can be used to ask a yes-or-no
303 question using a dialog box, or optionally using one.
304
305    If either of these functions is called in a command that was invoked
306 using the mouse, then it uses a dialog box or pop-up menu to ask the
307 question.  Otherwise, it uses keyboard input.
308
309    Strictly speaking, `yes-or-no-p' uses the minibuffer and `y-or-n-p'
310 does not; but it seems best to describe them together.
311
312  - Function: y-or-n-p prompt
313      This function asks the user a question, expecting input in the echo
314      area.  It returns `t' if the user types `y', `nil' if the user
315      types `n'.  This function also accepts <SPC> to mean yes and <DEL>
316      to mean no.  It accepts `C-]' to mean "quit", like `C-g', because
317      the question might look like a minibuffer and for that reason the
318      user might try to use `C-]' to get out.  The answer is a single
319      character, with no <RET> needed to terminate it.  Upper and lower
320      case are equivalent.
321
322      "Asking the question" means printing PROMPT in the echo area,
323      followed by the string `(y or n) '.  If the input is not one of
324      the expected answers (`y', `n', `<SPC>', `<DEL>', or something
325      that quits), the function responds `Please answer y or n.', and
326      repeats the request.
327
328      This function does not actually use the minibuffer, since it does
329      not allow editing of the answer.  It actually uses the echo area
330      (*note The Echo Area::), which uses the same screen space as the
331      minibuffer.  The cursor moves to the echo area while the question
332      is being asked.
333
334      The answers and their meanings, even `y' and `n', are not
335      hardwired.  The keymap `query-replace-map' specifies them.  *Note
336      Search and Replace::.
337
338      In the following example, the user first types `q', which is
339      invalid.  At the next prompt the user types `y'.
340
341           (y-or-n-p "Do you need a lift? ")
342           
343           ;; After evaluation of the preceding expression,
344           ;;   the following prompt appears in the echo area:
345           
346           ---------- Echo area ----------
347           Do you need a lift? (y or n)
348           ---------- Echo area ----------
349           
350           ;; If the user then types `q', the following appears:
351           
352           ---------- Echo area ----------
353           Please answer y or n.  Do you need a lift? (y or n)
354           ---------- Echo area ----------
355           
356           ;; When the user types a valid answer,
357           ;;   it is displayed after the question:
358           
359           ---------- Echo area ----------
360           Do you need a lift? (y or n) y
361           ---------- Echo area ----------
362
363      We show successive lines of echo area messages, but only one
364      actually appears on the screen at a time.
365
366  - Function: yes-or-no-p prompt
367      This function asks the user a question, expecting input in the
368      minibuffer.  It returns `t' if the user enters `yes', `nil' if the
369      user types `no'.  The user must type <RET> to finalize the
370      response.  Upper and lower case are equivalent.
371
372      `yes-or-no-p' starts by displaying PROMPT in the echo area,
373      followed by `(yes or no) '.  The user must type one of the
374      expected responses; otherwise, the function responds `Please answer
375      yes or no.', waits about two seconds and repeats the request.
376
377      `yes-or-no-p' requires more work from the user than `y-or-n-p' and
378      is appropriate for more crucial decisions.
379
380      Here is an example:
381
382           (yes-or-no-p "Do you really want to remove everything? ")
383           
384           ;; After evaluation of the preceding expression,
385           ;;   the following prompt appears,
386           ;;   with an empty minibuffer:
387           
388           ---------- Buffer: minibuffer ----------
389           Do you really want to remove everything? (yes or no)
390           ---------- Buffer: minibuffer ----------
391
392      If the user first types `y <RET>', which is invalid because this
393      function demands the entire word `yes', it responds by displaying
394      these prompts, with a brief pause between them:
395
396           ---------- Buffer: minibuffer ----------
397           Please answer yes or no.
398           Do you really want to remove everything? (yes or no)
399           ---------- Buffer: minibuffer ----------
400
401  - Function: yes-or-no-p-dialog-box prompt
402      This function asks the user a "y or n" question with a popup dialog
403      box.  It returns `t' if the answer is "yes".  PROMPT is the string
404      to display to ask the question.
405
406    The following functions ask a question either in the minibuffer or a
407 dialog box, depending on whether the last user event (which presumably
408 invoked this command) was a keyboard or mouse event.  When XEmacs is
409 running on a window system, the functions `y-or-n-p' and `yes-or-no-p'
410 are replaced with the following functions, so that menu items bring up
411 dialog boxes instead of minibuffer questions.
412
413  - Function: y-or-n-p-maybe-dialog-box prompt
414      This function asks user a "y or n" question, using either a dialog
415      box or the minibuffer, as appropriate.
416
417  - Function: yes-or-no-p-maybe-dialog-box prompt
418      This function asks user a "yes or no" question, using either a
419      dialog box or the minibuffer, as appropriate.
420
421 \1f
422 File: lispref.info,  Node: Multiple Queries,  Next: Minibuffer Misc,  Prev: Yes-or-No Queries,  Up: Minibuffers
423
424 Asking Multiple Y-or-N Questions
425 ================================
426
427    When you have a series of similar questions to ask, such as "Do you
428 want to save this buffer" for each buffer in turn, you should use
429 `map-y-or-n-p' to ask the collection of questions, rather than asking
430 each question individually.  This gives the user certain convenient
431 facilities such as the ability to answer the whole series at once.
432
433  - Function: map-y-or-n-p prompter actor list &optional help
434           action-alist
435      This function, new in Emacs 19, asks the user a series of
436      questions, reading a single-character answer in the echo area for
437      each one.
438
439      The value of LIST specifies the objects to ask questions about.
440      It should be either a list of objects or a generator function.  If
441      it is a function, it should expect no arguments, and should return
442      either the next object to ask about, or `nil' meaning stop asking
443      questions.
444
445      The argument PROMPTER specifies how to ask each question.  If
446      PROMPTER is a string, the question text is computed like this:
447
448           (format PROMPTER OBJECT)
449
450      where OBJECT is the next object to ask about (as obtained from
451      LIST).
452
453      If not a string, PROMPTER should be a function of one argument
454      (the next object to ask about) and should return the question
455      text.  If the value is a string, that is the question to ask the
456      user.  The function can also return `t' meaning do act on this
457      object (and don't ask the user), or `nil' meaning ignore this
458      object (and don't ask the user).
459
460      The argument ACTOR says how to act on the answers that the user
461      gives.  It should be a function of one argument, and it is called
462      with each object that the user says yes for.  Its argument is
463      always an object obtained from LIST.
464
465      If the argument HELP is given, it should be a list of this form:
466
467           (SINGULAR PLURAL ACTION)
468
469      where SINGULAR is a string containing a singular noun that
470      describes the objects conceptually being acted on, PLURAL is the
471      corresponding plural noun, and ACTION is a transitive verb
472      describing what ACTOR does.
473
474      If you don't specify HELP, the default is `("object" "objects"
475      "act on")'.
476
477      Each time a question is asked, the user may enter `y', `Y', or
478      <SPC> to act on that object; `n', `N', or <DEL> to skip that
479      object; `!' to act on all following objects; <ESC> or `q' to exit
480      (skip all following objects); `.' (period) to act on the current
481      object and then exit; or `C-h' to get help.  These are the same
482      answers that `query-replace' accepts.  The keymap
483      `query-replace-map' defines their meaning for `map-y-or-n-p' as
484      well as for `query-replace'; see *Note Search and Replace::.
485
486      You can use ACTION-ALIST to specify additional possible answers
487      and what they mean.  It is an alist of elements of the form `(CHAR
488      FUNCTION HELP)', each of which defines one additional answer.  In
489      this element, CHAR is a character (the answer); FUNCTION is a
490      function of one argument (an object from LIST); HELP is a string.
491
492      When the user responds with CHAR, `map-y-or-n-p' calls FUNCTION.
493      If it returns non-`nil', the object is considered "acted upon",
494      and `map-y-or-n-p' advances to the next object in LIST.  If it
495      returns `nil', the prompt is repeated for the same object.
496
497      If `map-y-or-n-p' is called in a command that was invoked using the
498      mouse--more precisely, if `last-nonmenu-event' (*note Command Loop
499      Info::) is either `nil' or a list--then it uses a dialog box or
500      pop-up menu to ask the question.  In this case, it does not use
501      keyboard input or the echo area.  You can force use of the mouse
502      or use of keyboard input by binding `last-nonmenu-event' to a
503      suitable value around the call.
504
505      The return value of `map-y-or-n-p' is the number of objects acted
506      on.
507
508 \1f
509 File: lispref.info,  Node: Minibuffer Misc,  Prev: Multiple Queries,  Up: Minibuffers
510
511 Minibuffer Miscellany
512 =====================
513
514    This section describes some basic functions and variables related to
515 minibuffers.
516
517  - Command: exit-minibuffer
518      This command exits the active minibuffer.  It is normally bound to
519      keys in minibuffer local keymaps.
520
521  - Command: self-insert-and-exit
522      This command exits the active minibuffer after inserting the last
523      character typed on the keyboard (found in `last-command-char';
524      *note Command Loop Info::).
525
526  - Command: previous-history-element n
527      This command replaces the minibuffer contents with the value of the
528      Nth previous (older) history element.
529
530  - Command: next-history-element n
531      This command replaces the minibuffer contents with the value of the
532      Nth more recent history element.
533
534  - Command: previous-matching-history-element pattern
535      This command replaces the minibuffer contents with the value of the
536      previous (older) history element that matches PATTERN (a regular
537      expression).
538
539  - Command: next-matching-history-element pattern
540      This command replaces the minibuffer contents with the value of
541      the next (newer) history element that matches PATTERN (a regular
542      expression).
543
544  - Function: minibuffer-prompt
545      This function returns the prompt string of the currently active
546      minibuffer.  If no minibuffer is active, it returns `nil'.
547
548  - Function: minibuffer-prompt-width
549      This function returns the display width of the prompt string of the
550      currently active minibuffer.  If no minibuffer is active, it
551      returns 0.
552
553  - Variable: minibuffer-setup-hook
554      This is a normal hook that is run whenever the minibuffer is
555      entered.  *Note Hooks::.
556
557  - Variable: minibuffer-exit-hook
558      This is a normal hook that is run whenever the minibuffer is
559      exited.  *Note Hooks::.
560
561  - Variable: minibuffer-help-form
562      The current value of this variable is used to rebind `help-form'
563      locally inside the minibuffer (*note Help Functions::).
564
565  - Function: active-minibuffer-window
566      This function returns the currently active minibuffer window, or
567      `nil' if none is currently active.
568
569  - Function: minibuffer-window &optional frame
570      This function returns the minibuffer window used for frame FRAME.
571      If FRAME is `nil', that stands for the current frame.  Note that
572      the minibuffer window used by a frame need not be part of that
573      frame--a frame that has no minibuffer of its own necessarily uses
574      some other frame's minibuffer window.
575
576  - Function: window-minibuffer-p window
577      This function returns non-`nil' if WINDOW is a minibuffer window.
578
579    It is not correct to determine whether a given window is a
580 minibuffer by comparing it with the result of `(minibuffer-window)',
581 because there can be more than one minibuffer window if there is more
582 than one frame.
583
584  - Function: minibuffer-window-active-p window
585      This function returns non-`nil' if WINDOW, assumed to be a
586      minibuffer window, is currently active.
587
588  - Variable: minibuffer-scroll-window
589      If the value of this variable is non-`nil', it should be a window
590      object.  When the function `scroll-other-window' is called in the
591      minibuffer, it scrolls this window.
592
593    Finally, some functions and variables deal with recursive minibuffers
594 (*note Recursive Editing::):
595
596  - Function: minibuffer-depth
597      This function returns the current depth of activations of the
598      minibuffer, a nonnegative integer.  If no minibuffers are active,
599      it returns zero.
600
601  - User Option: enable-recursive-minibuffers
602      If this variable is non-`nil', you can invoke commands (such as
603      `find-file') that use minibuffers even while in the minibuffer
604      window.  Such invocation produces a recursive editing level for a
605      new minibuffer.  The outer-level minibuffer is invisible while you
606      are editing the inner one.
607
608      This variable only affects invoking the minibuffer while the
609      minibuffer window is selected.   If you switch windows while in the
610      minibuffer, you can always invoke minibuffer commands while some
611      other window is selected.
612
613    In FSF Emacs 19, if a command name has a property
614 `enable-recursive-minibuffers' that is non-`nil', then the command can
615 use the minibuffer to read arguments even if it is invoked from the
616 minibuffer.  The minibuffer command `next-matching-history-element'
617 (normally `M-s' in the minibuffer) uses this feature.
618
619    This is not implemented in XEmacs because it is a kludge.  If you
620 want to explicitly set the value of `enable-recursive-minibuffers' in
621 this fashion, just use an evaluated interactive spec and bind
622 `enable-recursive-minibuffers' while reading from the minibuffer.  See
623 the definition of `next-matching-history-element' in
624 `lisp/prim/minibuf.el'.
625
626 \1f
627 File: lispref.info,  Node: Command Loop,  Next: Keymaps,  Prev: Minibuffers,  Up: Top
628
629 Command Loop
630 ************
631
632    When you run XEmacs, it enters the "editor command loop" almost
633 immediately.  This loop reads events, executes their definitions, and
634 displays the results.  In this chapter, we describe how these things
635 are done, and the subroutines that allow Lisp programs to do them.
636
637 * Menu:
638
639 * Command Overview::    How the command loop reads commands.
640 * Defining Commands::   Specifying how a function should read arguments.
641 * Interactive Call::    Calling a command, so that it will read arguments.
642 * Command Loop Info::   Variables set by the command loop for you to examine.
643 * Events::              What input looks like when you read it.
644 * Reading Input::       How to read input events from the keyboard or mouse.
645 * Waiting::             Waiting for user input or elapsed time.
646 * Quitting::            How C-g works.  How to catch or defer quitting.
647 * Prefix Command Arguments::    How the commands to set prefix args work.
648 * Recursive Editing::   Entering a recursive edit,
649                           and why you usually shouldn't.
650 * Disabling Commands::  How the command loop handles disabled commands.
651 * Command History::     How the command history is set up, and how accessed.
652 * Keyboard Macros::     How keyboard macros are implemented.
653
654 \1f
655 File: lispref.info,  Node: Command Overview,  Next: Defining Commands,  Up: Command Loop
656
657 Command Loop Overview
658 =====================
659
660    The command loop in XEmacs is a standard event loop, reading events
661 one at a time with `next-event' and handling them with
662 `dispatch-event'.  An event is typically a single user action, such as
663 a keypress, mouse movement, or menu selection; but they can also be
664 notifications from the window system, informing XEmacs that (for
665 example) part of its window was just uncovered and needs to be redrawn.
666 *Note Events::.  Pending events are held in a first-in, first-out list
667 called the "event queue": events are read from the head of the list,
668 and newly arriving events are added to the tail.  In this way, events
669 are always processed in the order in which they arrive.
670
671    `dispatch-event' does most of the work of handling user actions.
672 The first thing it must do is put the events together into a key
673 sequence, which is a sequence of events that translates into a command.
674 It does this by consulting the active keymaps, which specify what the
675 valid key sequences are and how to translate them into commands.  *Note
676 Key Lookup::, for information on how this is done.  The result of the
677 translation should be a keyboard macro or an interactively callable
678 function.  If the key is `M-x', then it reads the name of another
679 command, which it then calls.  This is done by the command
680 `execute-extended-command' (*note Interactive Call::).
681
682    To execute a command requires first reading the arguments for it.
683 This is done by calling `command-execute' (*note Interactive Call::).
684 For commands written in Lisp, the `interactive' specification says how
685 to read the arguments.  This may use the prefix argument (*note Prefix
686 Command Arguments::) or may read with prompting in the minibuffer
687 (*note Minibuffers::).  For example, the command `find-file' has an
688 `interactive' specification which says to read a file name using the
689 minibuffer.  The command's function body does not use the minibuffer;
690 if you call this command from Lisp code as a function, you must supply
691 the file name string as an ordinary Lisp function argument.
692
693    If the command is a string or vector (i.e., a keyboard macro) then
694 `execute-kbd-macro' is used to execute it.  You can call this function
695 yourself (*note Keyboard Macros::).
696
697    To terminate the execution of a running command, type `C-g'.  This
698 character causes "quitting" (*note Quitting::).
699
700  - Variable: pre-command-hook
701      The editor command loop runs this normal hook before each command.
702      At that time, `this-command' contains the command that is about to
703      run, and `last-command' describes the previous command.  *Note
704      Hooks::.
705
706  - Variable: post-command-hook
707      The editor command loop runs this normal hook after each command.
708      (In FSF Emacs, it is also run when the command loop is entered, or
709      reentered after an error or quit.)  At that time, `this-command'
710      describes the command that just ran, and `last-command' describes
711      the command before that.  *Note Hooks::.
712
713    Quitting is suppressed while running `pre-command-hook' and
714 `post-command-hook'.  If an error happens while executing one of these
715 hooks, it terminates execution of the hook, but that is all it does.
716
717 \1f
718 File: lispref.info,  Node: Defining Commands,  Next: Interactive Call,  Prev: Command Overview,  Up: Command Loop
719
720 Defining Commands
721 =================
722
723    A Lisp function becomes a command when its body contains, at top
724 level, a form that calls the special form `interactive'.  This form
725 does nothing when actually executed, but its presence serves as a flag
726 to indicate that interactive calling is permitted.  Its argument
727 controls the reading of arguments for an interactive call.
728
729 * Menu:
730
731 * Using Interactive::     General rules for `interactive'.
732 * Interactive Codes::     The standard letter-codes for reading arguments
733                              in various ways.
734 * Interactive Examples::  Examples of how to read interactive arguments.
735
736 \1f
737 File: lispref.info,  Node: Using Interactive,  Next: Interactive Codes,  Up: Defining Commands
738
739 Using `interactive'
740 -------------------
741
742    This section describes how to write the `interactive' form that
743 makes a Lisp function an interactively-callable command.
744
745  - Special Form: interactive arg-descriptor
746      This special form declares that the function in which it appears
747      is a command, and that it may therefore be called interactively
748      (via `M-x' or by entering a key sequence bound to it).  The
749      argument ARG-DESCRIPTOR declares how to compute the arguments to
750      the command when the command is called interactively.
751
752      A command may be called from Lisp programs like any other
753      function, but then the caller supplies the arguments and
754      ARG-DESCRIPTOR has no effect.
755
756      The `interactive' form has its effect because the command loop
757      (actually, its subroutine `call-interactively') scans through the
758      function definition looking for it, before calling the function.
759      Once the function is called, all its body forms including the
760      `interactive' form are executed, but at this time `interactive'
761      simply returns `nil' without even evaluating its argument.
762
763    There are three possibilities for the argument ARG-DESCRIPTOR:
764
765    * It may be omitted or `nil'; then the command is called with no
766      arguments.  This leads quickly to an error if the command requires
767      one or more arguments.
768
769    * It may be a Lisp expression that is not a string; then it should
770      be a form that is evaluated to get a list of arguments to pass to
771      the command.
772
773      If this expression reads keyboard input (this includes using the
774      minibuffer), keep in mind that the integer value of point or the
775      mark before reading input may be incorrect after reading input.
776      This is because the current buffer may be receiving subprocess
777      output; if subprocess output arrives while the command is waiting
778      for input, it could relocate point and the mark.
779
780      Here's an example of what _not_ to do:
781
782           (interactive
783            (list (region-beginning) (region-end)
784                  (read-string "Foo: " nil 'my-history)))
785
786      Here's how to avoid the problem, by examining point and the mark
787      only after reading the keyboard input:
788
789           (interactive
790            (let ((string (read-string "Foo: " nil 'my-history)))
791              (list (region-beginning) (region-end) string)))
792
793    * It may be a string; then its contents should consist of a code
794      character followed by a prompt (which some code characters use and
795      some ignore).  The prompt ends either with the end of the string
796      or with a newline.  Here is a simple example:
797
798           (interactive "bFrobnicate buffer: ")
799
800      The code letter `b' says to read the name of an existing buffer,
801      with completion.  The buffer name is the sole argument passed to
802      the command.  The rest of the string is a prompt.
803
804      If there is a newline character in the string, it terminates the
805      prompt.  If the string does not end there, then the rest of the
806      string should contain another code character and prompt,
807      specifying another argument.  You can specify any number of
808      arguments in this way.
809
810      The prompt string can use `%' to include previous argument values
811      (starting with the first argument) in the prompt.  This is done
812      using `format' (*note Formatting Strings::).  For example, here is
813      how you could read the name of an existing buffer followed by a
814      new name to give to that buffer:
815
816           (interactive "bBuffer to rename: \nsRename buffer %s to: ")
817
818      If the first character in the string is `*', then an error is
819      signaled if the buffer is read-only.
820
821      If the first character in the string is `@', and if the key
822      sequence used to invoke the command includes any mouse events, then
823      the window associated with the first of those events is selected
824      before the command is run.
825
826      If the first character in the string is `_', then this command will
827      not cause the region to be deactivated when it completes; that is,
828      `zmacs-region-stays' will be set to `t' when the command exits
829      successfully.
830
831      You can use `*', `@', and `_' together; the order does not matter.
832      Actual reading of arguments is controlled by the rest of the
833      prompt string (starting with the first character that is not `*',
834      `@', or `_').
835
836  - Function: function-interactive function
837      This function retrieves the interactive specification of FUNCTION,
838      which may be any funcallable object.  The specification will be
839      returned as the list of the symbol `interactive' and the specs.  If
840      FUNCTION is not interactive, `nil' will be returned.
841
842 \1f
843 File: lispref.info,  Node: Interactive Codes,  Next: Interactive Examples,  Prev: Using Interactive,  Up: Defining Commands
844
845 Code Characters for `interactive'
846 ---------------------------------
847
848    The code character descriptions below contain a number of key words,
849 defined here as follows:
850
851 Completion
852      Provide completion.  <TAB>, <SPC>, and <RET> perform name
853      completion because the argument is read using `completing-read'
854      (*note Completion::).  `?' displays a list of possible completions.
855
856 Existing
857      Require the name of an existing object.  An invalid name is not
858      accepted; the commands to exit the minibuffer do not exit if the
859      current input is not valid.
860
861 Default
862      A default value of some sort is used if the user enters no text in
863      the minibuffer.  The default depends on the code character.
864
865 No I/O
866      This code letter computes an argument without reading any input.
867      Therefore, it does not use a prompt string, and any prompt string
868      you supply is ignored.
869
870      Even though the code letter doesn't use a prompt string, you must
871      follow it with a newline if it is not the last code character in
872      the string.
873
874 Prompt
875      A prompt immediately follows the code character.  The prompt ends
876      either with the end of the string or with a newline.
877
878 Special
879      This code character is meaningful only at the beginning of the
880      interactive string, and it does not look for a prompt or a newline.
881      It is a single, isolated character.
882
883    Here are the code character descriptions for use with `interactive':
884
885 `*'
886      Signal an error if the current buffer is read-only.  Special.
887
888 `@'
889      Select the window mentioned in the first mouse event in the key
890      sequence that invoked this command.  Special.
891
892 `_'
893      Do not cause the region to be deactivated when this command
894      completes.  Special.
895
896 `a'
897      A function name (i.e., a symbol satisfying `fboundp').  Existing,
898      Completion, Prompt.
899
900 `b'
901      The name of an existing buffer.  By default, uses the name of the
902      current buffer (*note Buffers::).  Existing, Completion, Default,
903      Prompt.
904
905 `B'
906      A buffer name.  The buffer need not exist.  By default, uses the
907      name of a recently used buffer other than the current buffer.
908      Completion, Default, Prompt.
909
910 `c'
911      A character.  The cursor does not move into the echo area.  Prompt.
912
913 `C'
914      A command name (i.e., a symbol satisfying `commandp').  Existing,
915      Completion, Prompt.
916
917 `d'
918      The position of point, as an integer (*note Point::).  No I/O.
919
920 `D'
921      A directory name.  The default is the current default directory of
922      the current buffer, `default-directory' (*note System
923      Environment::).  Existing, Completion, Default, Prompt.
924
925 `e'
926      The last mouse-button or misc-user event in the key sequence that
927      invoked the command.  No I/O.
928
929      You can use `e' more than once in a single command's interactive
930      specification.  If the key sequence that invoked the command has N
931      mouse-button or misc-user events, the Nth `e' provides the Nth
932      such event.
933
934 `f'
935      A file name of an existing file (*note File Names::).  The default
936      directory is `default-directory'.  Existing, Completion, Default,
937      Prompt.
938
939 `F'
940      A file name.  The file need not exist.  Completion, Default,
941      Prompt.
942
943 `k'
944      A key sequence (*note Keymap Terminology::).  This keeps reading
945      events until a command (or undefined command) is found in the
946      current key maps.  The key sequence argument is represented as a
947      vector of events.  The cursor does not move into the echo area.
948      Prompt.
949
950      This kind of input is used by commands such as `describe-key' and
951      `global-set-key'.
952
953 `K'
954      A key sequence, whose definition you intend to change.  This works
955      like `k', except that it suppresses, for the last input event in
956      the key sequence, the conversions that are normally used (when
957      necessary) to convert an undefined key into a defined one.
958
959 `m'
960      The position of the mark, as an integer.  No I/O.
961
962 `n'
963      A number read with the minibuffer.  If the input is not a number,
964      the user is asked to try again.  The prefix argument, if any, is
965      not used.  Prompt.
966
967 `N'
968      The raw prefix argument.  If the prefix argument is `nil', then
969      read a number as with `n'.  Requires a number.  *Note Prefix
970      Command Arguments::.  Prompt.
971
972 `p'
973      The numeric prefix argument.  (Note that this `p' is lower case.)
974      No I/O.
975
976 `P'
977      The raw prefix argument.  (Note that this `P' is upper case.)  No
978      I/O.
979
980 `r'
981      Point and the mark, as two numeric arguments, smallest first.
982      This is the only code letter that specifies two successive
983      arguments rather than one.  No I/O.
984
985 `s'
986      Arbitrary text, read in the minibuffer and returned as a string
987      (*note Text from Minibuffer::).  Terminate the input with either
988      <LFD> or <RET>.  (`C-q' may be used to include either of these
989      characters in the input.)  Prompt.
990
991 `S'
992      An interned symbol whose name is read in the minibuffer.  Any
993      whitespace character terminates the input.  (Use `C-q' to include
994      whitespace in the string.)  Other characters that normally
995      terminate a symbol (e.g., parentheses and brackets) do not do so
996      here.  Prompt.
997
998 `v'
999      A variable declared to be a user option (i.e., satisfying the
1000      predicate `user-variable-p').  *Note High-Level Completion::.
1001      Existing, Completion, Prompt.
1002
1003 `x'
1004      A Lisp object, specified with its read syntax, terminated with a
1005      <LFD> or <RET>.  The object is not evaluated.  *Note Object from
1006      Minibuffer::.  Prompt.
1007
1008 `X'
1009      A Lisp form is read as with `x', but then evaluated so that its
1010      value becomes the argument for the command.  Prompt.
1011
1012 \1f
1013 File: lispref.info,  Node: Interactive Examples,  Prev: Interactive Codes,  Up: Defining Commands
1014
1015 Examples of Using `interactive'
1016 -------------------------------
1017
1018    Here are some examples of `interactive':
1019
1020      (defun foo1 ()              ; `foo1' takes no arguments,
1021          (interactive)           ;   just moves forward two words.
1022          (forward-word 2))
1023           => foo1
1024      
1025      (defun foo2 (n)             ; `foo2' takes one argument,
1026          (interactive "p")       ;   which is the numeric prefix.
1027          (forward-word (* 2 n)))
1028           => foo2
1029      
1030      (defun foo3 (n)             ; `foo3' takes one argument,
1031          (interactive "nCount:") ;   which is read with the Minibuffer.
1032          (forward-word (* 2 n)))
1033           => foo3
1034      
1035      (defun three-b (b1 b2 b3)
1036        "Select three existing buffers.
1037      Put them into three windows, selecting the last one."
1038          (interactive "bBuffer1:\nbBuffer2:\nbBuffer3:")
1039          (delete-other-windows)
1040          (split-window (selected-window) 8)
1041          (switch-to-buffer b1)
1042          (other-window 1)
1043          (split-window (selected-window) 8)
1044          (switch-to-buffer b2)
1045          (other-window 1)
1046          (switch-to-buffer b3))
1047           => three-b
1048      (three-b "*scratch*" "declarations.texi" "*mail*")
1049           => nil
1050
1051 \1f
1052 File: lispref.info,  Node: Interactive Call,  Next: Command Loop Info,  Prev: Defining Commands,  Up: Command Loop
1053
1054 Interactive Call
1055 ================
1056
1057    After the command loop has translated a key sequence into a
1058 definition, it invokes that definition using the function
1059 `command-execute'.  If the definition is a function that is a command,
1060 `command-execute' calls `call-interactively', which reads the arguments
1061 and calls the command.  You can also call these functions yourself.
1062
1063  - Function: commandp object
1064      Returns `t' if OBJECT is suitable for calling interactively; that
1065      is, if OBJECT is a command.  Otherwise, returns `nil'.
1066
1067      The interactively callable objects include strings and vectors
1068      (treated as keyboard macros), lambda expressions that contain a
1069      top-level call to `interactive', compiled-function objects made
1070      from such lambda expressions, autoload objects that are declared
1071      as interactive (non-`nil' fourth argument to `autoload'), and some
1072      of the primitive functions.
1073
1074      A symbol is `commandp' if its function definition is `commandp'.
1075
1076      Keys and keymaps are not commands.  Rather, they are used to look
1077      up commands (*note Keymaps::).
1078
1079      See `documentation' in *Note Accessing Documentation::, for a
1080      realistic example of using `commandp'.
1081
1082  - Function: call-interactively command &optional record-flag
1083      This function calls the interactively callable function COMMAND,
1084      reading arguments according to its interactive calling
1085      specifications.  An error is signaled if COMMAND is not a function
1086      or if it cannot be called interactively (i.e., is not a command).
1087      Note that keyboard macros (strings and vectors) are not accepted,
1088      even though they are considered commands, because they are not
1089      functions.
1090
1091      If RECORD-FLAG is the symbol `lambda', the interactive calling
1092      arguments for `command' are read and returned as a list, but the
1093      function is not called on them.
1094
1095      If RECORD-FLAG is `t', then this command and its arguments are
1096      unconditionally added to the list `command-history'.  Otherwise,
1097      the command is added only if it uses the minibuffer to read an
1098      argument.  *Note Command History::.
1099
1100  - Function: command-execute command &optional record-flag
1101      This function executes COMMAND as an editing command.  The
1102      argument COMMAND must satisfy the `commandp' predicate; i.e., it
1103      must be an interactively callable function or a keyboard macro.
1104
1105      A string or vector as COMMAND is executed with
1106      `execute-kbd-macro'.  A function is passed to
1107      `call-interactively', along with the optional RECORD-FLAG.
1108
1109      A symbol is handled by using its function definition in its place.
1110      A symbol with an `autoload' definition counts as a command if it
1111      was declared to stand for an interactively callable function.
1112      Such a definition is handled by loading the specified library and
1113      then rechecking the definition of the symbol.
1114
1115  - Command: execute-extended-command prefix-argument
1116      This function reads a command name from the minibuffer using
1117      `completing-read' (*note Completion::).  Then it uses
1118      `command-execute' to call the specified command.  Whatever that
1119      command returns becomes the value of `execute-extended-command'.
1120
1121      If the command asks for a prefix argument, it receives the value
1122      PREFIX-ARGUMENT.  If `execute-extended-command' is called
1123      interactively, the current raw prefix argument is used for
1124      PREFIX-ARGUMENT, and thus passed on to whatever command is run.
1125
1126      `execute-extended-command' is the normal definition of `M-x', so
1127      it uses the string `M-x ' as a prompt.  (It would be better to
1128      take the prompt from the events used to invoke
1129      `execute-extended-command', but that is painful to implement.)  A
1130      description of the value of the prefix argument, if any, also
1131      becomes part of the prompt.
1132
1133           (execute-extended-command 1)
1134           ---------- Buffer: Minibuffer ----------
1135           1 M-x forward-word RET
1136           ---------- Buffer: Minibuffer ----------
1137                => t
1138
1139  - Function: interactive-p
1140      This function returns `t' if the containing function (the one that
1141      called `interactive-p') was called interactively, with the function
1142      `call-interactively'.  (It makes no difference whether
1143      `call-interactively' was called from Lisp or directly from the
1144      editor command loop.)  If the containing function was called by
1145      Lisp evaluation (or with `apply' or `funcall'), then it was not
1146      called interactively.
1147
1148      The most common use of `interactive-p' is for deciding whether to
1149      print an informative message.  As a special exception,
1150      `interactive-p' returns `nil' whenever a keyboard macro is being
1151      run.  This is to suppress the informative messages and speed
1152      execution of the macro.
1153
1154      For example:
1155
1156           (defun foo ()
1157             (interactive)
1158             (and (interactive-p)
1159                  (message "foo")))
1160                => foo
1161           
1162           (defun bar ()
1163             (interactive)
1164             (setq foobar (list (foo) (interactive-p))))
1165                => bar
1166           
1167           ;; Type `M-x foo'.
1168                -| foo
1169           
1170           ;; Type `M-x bar'.
1171           ;; This does not print anything.
1172           
1173           foobar
1174                => (nil t)
1175