From Emilio C. Lopes <eclig@gmx.net>:
[emacs.git] / lispintro / emacs-lisp-intro.texi
blob2096a60928fad85353e32bb4fe7a46567b01c922
1 @c \input texinfo                                  @c -*-texinfo-*-
2 @comment %**start of header
3 @setfilename ../info/eintr
4 @c sethtmlfilename emacs-lisp-intro.html
5 @settitle Programming in Emacs Lisp
6 @syncodeindex vr cp
7 @syncodeindex fn cp
8 @setchapternewpage odd
9 @finalout
11 @c ---------
12 @c <<<< For hard copy printing, this file is now
13 @c      set for smallbook, which works for all sizes
14 @c      of paper, and with Postscript figures >>>>
15 @smallbook
16 @clear  largebook
17 @set print-postscript-figures
18 @c set largebook
19 @c clear print-postscript-figures
20 @c ---------
22 @comment %**end of header
24 @set edition-number 2.12
25 @set update-date 2003 Nov 19
27 @ignore
28  ## Summary of shell commands to create various output formats:
30     pushd /usr/local/src/emacs/lispintro/
32     ## Info output
33     makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
35     ## DVI output
36     texi2dvi emacs-lisp-intro.texi
38     ## HTML output
39     makeinfo --html --no-split --verbose emacs-lisp-intro.texi
41     ## Plain text output
42     makeinfo --fill-column=70 --no-split --paragraph-indent=0 \
43     --verbose --no-headers --output=emacs-lisp-intro.txt emacs-lisp-intro.texi
45     ## DocBook output
46     makeinfo --docbook --no-split --paragraph-indent=0 \
47     --verbose emacs-lisp-intro.texi
49     ## XML output
50     makeinfo --xml --no-split --paragraph-indent=0 \
51     --verbose emacs-lisp-intro.texi
53     #### (You must be in the same directory as the viewed file.)
55       ## View DVI output
56       xdvi emacs-lisp-intro.dvi &
58       ## View HTML output
59       galeon emacs-lisp-intro.html
61       ## View Info output with standalone reader
62       info emacs-lisp-intro.info
64 @end ignore
66 @c ================ Included Figures ================
68 @c Set  print-postscript-figures  if you print PostScript figures.
69 @c If you clear this, the ten figures will be printed as ASCII diagrams.
70 @c (This is not relevant to Info, since Info only handles ASCII.)
71 @c Your site may require editing changes to print PostScript; in this
72 @c case, search for `print-postscript-figures' and make appropriate changes.
75 @c ================ How to Create an Info file ================
77 @c If you have `makeinfo' installed, run the following command
79 @c     makeinfo emacs-lisp-intro.texi
81 @c or, if you want a single, large Info file, and no paragraph indents:
82 @c     makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
84 @c After creating the Info file, edit your Info `dir' file, if the
85 @c `dircategory' section below does not enable your system to
86 @c install the manual automatically.
87 @c (The `dir' file is often in the `/usr/local/info/' directory.)
89 @c ================ How to Create an HTML file ================
91 @c To convert to HTML format
92 @c     makeinfo --html --no-split --verbose emacs-lisp-intro.texi
94 @c ================ How to Print a Book in Various Sizes ================
96 @c This book can be printed in any of three different sizes.
97 @c In the above header, set @-commands appropriately.
99 @c     7 by 9.25 inches:
100 @c              @smallbook
101 @c              @clear largebook
103 @c     8.5 by 11 inches:
104 @c              @c smallbook
105 @c              @set largebook
107 @c     European A4 size paper:
108 @c              @c smallbook
109 @c              @afourpaper
110 @c              @set largebook
112 @c ================ How to Typeset and Print ================
114 @c If you do not include PostScript figures, run either of the
115 @c following command sequences, or similar commands suited to your
116 @c system:
118 @c     texi2dvi emacs-lisp-intro.texi
119 @c     lpr -d emacs-lisp-intro.dvi
121 @c or else:
123 @c     tex emacs-lisp-intro.texi
124 @c     texindex emacs-lisp-intro.??
125 @c     tex emacs-lisp-intro.texi
126 @c     lpr -d emacs-lisp-intro.dvi
128 @c If you include the PostScript figures, and you have old software,
129 @c you may need to convert the .dvi file to a .ps file before
130 @c printing.  Run either of the following command sequences, or one
131 @c similar:
133 @c     dvips -f < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
135 @c or else:
137 @c     postscript -p < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
140 @c (Note: if you edit the book so as to change the length of the
141 @c table of contents, you may have to change the value of `pageno' below.)
143 @c ================ End of Formatting Sections ================
145 @c For next or subsequent edition:
146 @c   create function using with-output-to-temp-buffer
147 @c   create a major mode, with keymaps
148 @c   run an asynchronous process, like grep or diff
150 @c For 8.5 by 11 inch format: do not use such a small amount of
151 @c whitespace between paragraphs as smallbook format
152 @ifset largebook
153 @tex
154 \global\parskip 6pt plus 1pt
155 @end tex
156 @end ifset
158 @c For all sized formats:  print within-book cross
159 @c reference with ``...''  rather than [...]
161 @c This works with the texinfo.tex file, version 2003-05-04.08,
162 @c in the Texinfo version 4.6 of the 2003 Jun 13 distribution.
164 @tex
165 \global\def\xrefprintnodename#1{``#1''}
166 @end tex
168 @c ----------------------------------------------------
170 @dircategory Emacs
171 @direntry
172 * Emacs Lisp Intro: (eintr).
173                         A simple introduction to Emacs Lisp programming.
174 @end direntry
176 @copying
177 This is an @cite{Introduction to Programming in Emacs Lisp}, for
178 people who are not programmers.
179 @sp 1
180 Edition @value{edition-number}, @value{update-date}
181 @sp 1
182 Copyright @copyright{} 1990, 1991, 1992, 1993, 1994, 1995, 1997, 2001,
183 2002, 2003 Free Software Foundation, Inc.
184 @sp 1
186 @iftex
187 Published by the:@*
189 GNU Press,                      @hfill  @uref{http://www.gnupress.org}@*
190 a division of the               @hfill General: @email{press@@gnu.org}@*
191 Free Software Foundation, Inc.  @hfill Orders:@w{ }  @email{sales@@gnu.org}@*
192 59 Temple Place, Suite 330      @hfill Tel: +1 (617) 542-5942@*
193 Boston, MA 02111-1307 USA       @hfill Fax: +1 (617) 542-2652@*
194 @end iftex
196 @ifnottex
197 Published by the:
199 @example
200 GNU Press,                          Website: http://www.gnupress.org
201 a division of the                   General: press@@gnu.org
202 Free Software Foundation, Inc.      Orders:  sales@@gnu.org
203 59 Temple Place, Suite 330          Tel: +1 (617) 542-5942
204 Boston, MA 02111-1307 USA           Fax: +1 (617) 542-2652
205 @end example
206 @end ifnottex
208 @sp 1
209 @c Printed copies are available for $30 each.@*
210 ISBN 1-882114-43-4
212 Permission is granted to copy, distribute and/or modify this document
213 under the terms of the GNU Free Documentation License, Version 1.1 or
214 any later version published by the Free Software Foundation; there
215 being no Invariant Section, with the Front-Cover Texts being ``A GNU
216 Manual'', and with the Back-Cover Texts as in (a) below.  A copy of
217 the license is included in the section entitled ``GNU Free
218 Documentation License''.
220 (a) The FSF's Back-Cover Text is: ``You have freedom to copy and
221 modify this GNU Manual, like GNU software.  Copies published by the
222 Free Software Foundation raise funds for GNU development.''
223 @end copying
225 @c half title; two lines here, so do not use `shorttitlepage'
226 @tex
227 {\begingroup%
228     \hbox{}\vskip 1.5in \chaprm \centerline{An Introduction to}%
229         \endgroup}%
230 {\begingroup\hbox{}\vskip 0.25in \chaprm%
231         \centerline{Programming in Emacs Lisp}%
232         \endgroup\page\hbox{}\page}
233 @end tex
235 @titlepage
236 @sp 6
237 @center @titlefont{An Introduction to}
238 @sp 2
239 @center @titlefont{Programming in Emacs Lisp}
240 @sp 2
241 @center Revised Second Edition
242 @sp 4
243 @center by Robert J. Chassell
245 @page
246 @vskip 0pt plus 1filll
247 @insertcopying
248 @end titlepage
250 @iftex
251 @headings off
252 @evenheading @thispage @| @| @thischapter
253 @oddheading @thissection @| @| @thispage
254 @end iftex
256 @ifnothtml
257 @c     Keep T.O.C. short by tightening up for largebook
258 @ifset largebook
259 @tex
260 \global\parskip 2pt plus 1pt
261 \global\advance\baselineskip by -1pt
262 @end tex
263 @end ifset
264 @end ifnothtml
266 @shortcontents
267 @contents
269 @ifnottex
270 @node Top, Preface, (dir), (dir)
271 @top An Introduction to Programming in Emacs Lisp
273 @insertcopying
275 This master menu first lists each chapter and index; then it lists
276 every node in every chapter.
277 @end ifnottex
279 @menu
280 * Preface::                     What to look for.
281 * List Processing::             What is Lisp?
282 * Practicing Evaluation::       Running several programs.
283 * Writing Defuns::              How to write function definitions.
284 * Buffer Walk Through::         Exploring a few buffer-related functions.
285 * More Complex::                A few, even more complex functions.
286 * Narrowing & Widening::        Restricting your and Emacs attention to
287                                     a region.
288 * car cdr & cons::              Fundamental functions in Lisp.
289 * Cutting & Storing Text::      Removing text and saving it.
290 * List Implementation::         How lists are implemented in the computer.
291 * Yanking::                     Pasting stored text.
292 * Loops & Recursion::           How to repeat a process.
293 * Regexp Search::               Regular expression searches.
294 * Counting Words::              A review of repetition and regexps.
295 * Words in a defun::            Counting words in a @code{defun}.
296 * Readying a Graph::            A prototype graph printing function.
297 * Emacs Initialization::        How to write a @file{.emacs} file.
298 * Debugging::                   How to run the Emacs Lisp debuggers.
299 * Conclusion::                  Now you have the basics.
300 * the-the::                     An appendix: how to find reduplicated words.
301 * Kill Ring::                   An appendix: how the kill ring works.
302 * Full Graph::                  How to create a graph with labelled axes.
303 * Free Software and Free Manuals::
304 * GNU Free Documentation License::
305 * Index::
306 * About the Author::
308 @detailmenu
309  --- The Detailed Node Listing ---
311 Preface
313 * Why::                         Why learn Emacs Lisp?
314 * On Reading this Text::        Read, gain familiarity, pick up habits....
315 * Who You Are::                 For whom this is written.
316 * Lisp History::
317 * Note for Novices::            You can read this as a novice.
318 * Thank You::
320 List Processing
322 * Lisp Lists::                  What are lists?
323 * Run a Program::               Any list in Lisp is a program ready to run.
324 * Making Errors::               Generating an error message.
325 * Names & Definitions::         Names of symbols and function definitions.
326 * Lisp Interpreter::            What the Lisp interpreter does.
327 * Evaluation::                  Running a program.
328 * Variables::                   Returning a value from a variable.
329 * Arguments::                   Passing information to a function.
330 * set & setq::                  Setting the value of a variable.
331 * Summary::                     The major points.
332 * Error Message Exercises::
334 Lisp Lists
336 * Numbers Lists::               List have numbers, other lists, in them.
337 * Lisp Atoms::                  Elemental entities.
338 * Whitespace in Lists::         Formating lists to be readable.
339 * Typing Lists::                How GNU Emacs helps you type lists.
341 The Lisp Interpreter
343 * Complications::               Variables, Special forms, Lists within.
344 * Byte Compiling::              Specially processing code for speed.
346 Evaluation
348 * Evaluating Inner Lists::      Lists within lists...
350 Variables
352 * fill-column Example::
353 * Void Function::               The error message for a symbol
354                                   without a function.
355 * Void Variable::               The error message for a symbol without a value.
357 Arguments
359 * Data types::                  Types of data passed to a function.
360 * Args as Variable or List::    An argument can be the value
361                                   of a variable or list.
362 * Variable Number of Arguments::  Some functions may take a
363                                   variable number of arguments.
364 * Wrong Type of Argument::      Passing an argument of the wrong type
365                                   to a function.
366 * message::                     A useful function for sending messages.
368 Setting the Value of a Variable
370 * Using set::                   Setting values.
371 * Using setq::                  Setting a quoted value.
372 * Counting::                    Using @code{setq} to count.
374 Practicing Evaluation
376 * How to Evaluate::             Typing editing commands or @kbd{C-x C-e}
377                                   causes evaluation.
378 * Buffer Names::                Buffers and files are different.
379 * Getting Buffers::             Getting a buffer itself, not merely its name.
380 * Switching Buffers::           How to change to another buffer.
381 * Buffer Size & Locations::     Where point is located and the size of
382                                 the buffer.
383 * Evaluation Exercise::
385 How To Write Function Definitions
387 * Primitive Functions::
388 * defun::                       The @code{defun} special form.
389 * Install::                     Install a function definition.
390 * Interactive::                 Making a function interactive.
391 * Interactive Options::         Different options for @code{interactive}.
392 * Permanent Installation::      Installing code permanently.
393 * let::                         Creating and initializing local variables.
394 * if::                          What if?
395 * else::                        If--then--else expressions.
396 * Truth & Falsehood::           What Lisp considers false and true.
397 * save-excursion::              Keeping track of point, mark, and buffer.
398 * Review::
399 * defun Exercises::
401 Install a Function Definition
403 * Effect of installation::
404 * Change a defun::              How to change a function definition.
406 Make a Function Interactive
408 * Interactive multiply-by-seven::  An overview.
409 * multiply-by-seven in detail::  The interactive version.
411 @code{let}
413 * Prevent confusion::
414 * Parts of let Expression::
415 * Sample let Expression::
416 * Uninitialized let Variables::
418 The @code{if} Special Form
420 * if in more detail::
421 * type-of-animal in detail::    An example of an @code{if} expression.
423 Truth and Falsehood in Emacs Lisp
425 * nil explained::               @code{nil} has two meanings.
427 @code{save-excursion}
429 * Point and mark::              A review of various locations.
430 * Template for save-excursion::
432 A Few Buffer--Related Functions
434 * Finding More::                How to find more information.
435 * simplified-beginning-of-buffer::  Shows @code{goto-char},
436                                 @code{point-min}, and @code{push-mark}.
437 * mark-whole-buffer::           Almost the same as @code{beginning-of-buffer}.
438 * append-to-buffer::            Uses @code{save-excursion} and
439                                 @code{insert-buffer-substring}.
440 * Buffer Related Review::       Review.
441 * Buffer Exercises::
443 The Definition of @code{mark-whole-buffer}
445 * mark-whole-buffer overview::
446 * Body of mark-whole-buffer::   Only three lines of code.
448 The Definition of @code{append-to-buffer}
450 * append-to-buffer overview::
451 * append interactive::          A two part interactive expression.
452 * append-to-buffer body::       Incorporates a @code{let} expression.
453 * append save-excursion::       How the @code{save-excursion} works.
455 A Few More Complex Functions
457 * copy-to-buffer::              With @code{set-buffer}, @code{get-buffer-create}.
458 * insert-buffer::               Read-only, and with @code{or}.
459 * beginning-of-buffer::         Shows @code{goto-char},
460                                 @code{point-min}, and @code{push-mark}.
461 * Second Buffer Related Review::
462 * optional Exercise::
464 The Definition of @code{insert-buffer}
466 * insert-buffer code::
467 * insert-buffer interactive::   When you can read, but not write.
468 * insert-buffer body::          The body has an @code{or} and a @code{let}.
469 * if & or::                     Using an @code{if} instead of an @code{or}.
470 * Insert or::                   How the @code{or} expression works.
471 * Insert let::                  Two @code{save-excursion} expressions.
473 The Interactive Expression in @code{insert-buffer}
475 * Read-only buffer::            When a buffer cannot be modified.
476 * b for interactive::           An existing buffer or else its name.
478 Complete Definition of @code{beginning-of-buffer}
480 * Optional Arguments::
481 * beginning-of-buffer opt arg::  Example with optional argument.
482 * beginning-of-buffer complete::
484 @code{beginning-of-buffer} with an Argument
486 * Disentangle beginning-of-buffer::
487 * Large buffer case::
488 * Small buffer case::
490 Narrowing and Widening
492 * Narrowing advantages::        The advantages of narrowing
493 * save-restriction::            The @code{save-restriction} special form.
494 * what-line::                   The number of the line that point is on.
495 * narrow Exercise::
497 @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
499 * Strange Names::               An historical aside: why the strange names?
500 * car & cdr::                   Functions for extracting part of a list.
501 * cons::                        Constructing a list.
502 * nthcdr::                      Calling @code{cdr} repeatedly.
503 * nth::
504 * setcar::                      Changing the first element of a list.
505 * setcdr::                      Changing the rest of a list.
506 * cons Exercise::
508 @code{cons}
510 * Build a list::
511 * length::                      How to find the length of a list.
513 Cutting and Storing Text
515 * Storing Text::                Text is stored in a list.
516 * zap-to-char::                 Cutting out text up to a character.
517 * kill-region::                 Cutting text out of a region.
518 * Digression into C::           Minor note on C programming language macros.
519 * defvar::                      How to give a variable an initial value.
520 * copy-region-as-kill::         A definition for copying text.
521 * cons & search-fwd Review::
522 * search Exercises::
524 @code{zap-to-char}
526 * Complete zap-to-char::        The complete implementation.
527 * zap-to-char interactive::     A three part interactive expression.
528 * zap-to-char body::            A short overview.
529 * search-forward::              How to search for a string.
530 * progn::                       The @code{progn} special form.
531 * Summing up zap-to-char::      Using @code{point} and @code{search-forward}.
533 @code{kill-region}
535 * Complete kill-region::        The function definition.
536 * condition-case::              Dealing with a problem.
537 * delete-and-extract-region::   Doing the work.
539 Initializing a Variable with @code{defvar}
541 * See variable current value::
542 * defvar and asterisk::         An old-time convention.
544 @code{copy-region-as-kill}
546 * Complete copy-region-as-kill::  The complete function definition.
547 * copy-region-as-kill body::    The body of @code{copy-region-as-kill}.
549 The Body of @code{copy-region-as-kill}
551 * last-command & this-command::
552 * kill-append function::
553 * kill-new function::
555 How Lists are Implemented
557 * Lists diagrammed::
558 * Symbols as Chest::            Exploring a powerful metaphor.
559 * List Exercise::
561 Yanking Text Back
563 * Kill Ring Overview::          The kill ring is a list.
564 * kill-ring-yank-pointer::      The @code{kill-ring-yank-pointer} variable.
565 * yank nthcdr Exercises::
567 Loops and Recursion
569 * while::                       Causing a stretch of code to repeat.
570 * dolist dotimes::
571 * Recursion::                   Causing a function to call itself.
572 * Looping exercise::
574 @code{while}
576 * Looping with while::          Repeat so long as test returns true.
577 * Loop Example::                A @code{while} loop that uses a list.
578 * print-elements-of-list::      Uses @code{while}, @code{car}, @code{cdr}.
579 * Incrementing Loop::           A loop with an incrementing counter.
580 * Decrementing Loop::           A loop with a decrementing counter.
582 A Loop with an Incrementing Counter
584 * Incrementing Example::        Counting pebbles in a triangle.
585 * Inc Example parts::           The parts of the function definition.
586 * Inc Example altogether::      Putting the function definition together.
588 Loop with a Decrementing Counter
590 * Decrementing Example::        More pebbles on the beach.
591 * Dec Example parts::           The parts of the function definition.
592 * Dec Example altogether::      Putting the function definition together.
594 Save your time: @code{dolist} and @code{dotimes}
596 * dolist::
597 * dotimes::
599 Recursion
601 * Building Robots::             Same model, different serial number ...
602 * Recursive Definition Parts::  Walk until you stop ...
603 * Recursion with list::         Using a list as the test whether to recurse.
604 * Recursive triangle function::
605 * Recursion with cond::
606 * Recursive Patterns::          Often used templates.
607 * No Deferment::                Don't store up work ...
608 * No deferment solution::
610 Recursion in Place of a Counter
612 * Recursive Example arg of 1 or 2::
613 * Recursive Example arg of 3 or 4::
615 Recursive Patterns
617 * Every::
618 * Accumulate::
619 * Keep::
621 Regular Expression Searches
623 * sentence-end::                The regular expression for @code{sentence-end}.
624 * re-search-forward::           Very similar to @code{search-forward}.
625 * forward-sentence::            A straightforward example of regexp search.
626 * forward-paragraph::           A somewhat complex example.
627 * etags::                       How to create your own @file{TAGS} table.
628 * Regexp Review::
629 * re-search Exercises::
631 @code{forward-sentence}
633 * Complete forward-sentence::
634 * fwd-sentence while loops::    Two @code{while} loops.
635 * fwd-sentence re-search::      A regular expression search.
637 @code{forward-paragraph}: a Goldmine of Functions
639 * forward-paragraph in brief::  Key parts of the function definition.
640 * fwd-para let::                The @code{let*} expression.
641 * fwd-para while::              The forward motion @code{while} loop.
642 * fwd-para between paragraphs::  Movement between paragraphs.
643 * fwd-para within paragraph::   Movement within paragraphs.
644 * fwd-para no fill prefix::     When there is no fill prefix.
645 * fwd-para with fill prefix::   When there is a fill prefix.
646 * fwd-para summary::            Summary of @code{forward-paragraph} code.
648 Counting: Repetition and Regexps
650 * Why Count Words::
651 * count-words-region::          Use a regexp, but find a problem.
652 * recursive-count-words::       Start with case of no words in region.
653 * Counting Exercise::
655 The @code{count-words-region} Function
657 * Design count-words-region::   The definition using a @code{while} loop.
658 * Whitespace Bug::              The Whitespace Bug in @code{count-words-region}.
660 Counting Words in a @code{defun}
662 * Divide and Conquer::
663 * Words and Symbols::           What to count?
664 * Syntax::                      What constitutes a word or symbol?
665 * count-words-in-defun::        Very like @code{count-words}.
666 * Several defuns::              Counting several defuns in a file.
667 * Find a File::                 Do you want to look at a file?
668 * lengths-list-file::           A list of the lengths of many definitions.
669 * Several files::               Counting in definitions in different files.
670 * Several files recursively::   Recursively counting in different files.
671 * Prepare the data::            Prepare the data for display in a graph.
673 Count Words in @code{defuns} in Different Files
675 * lengths-list-many-files::     Return a list of the lengths of defuns.
676 * append::                      Attach one list to another.
678 Prepare the Data for Display in a Graph
680 * Sorting::                     Sorting lists.
681 * Files List::                  Making a list of files.
682 * Counting function definitions::
684 Readying a Graph
686 * Columns of a graph::
687 * graph-body-print::            How to print the body of a graph.
688 * recursive-graph-body-print::
689 * Printed Axes::
690 * Line Graph Exercise::
692 Your @file{.emacs} File
694 * Default Configuration::
695 * Site-wide Init::              You can write site-wide init files.
696 * defcustom::                   Emacs will write code for you.
697 * Beginning a .emacs File::     How to write a @code{.emacs file}.
698 * Text and Auto-fill::          Automatically wrap lines.
699 * Mail Aliases::                Use abbreviations for email addresses.
700 * Indent Tabs Mode::            Don't use tabs with @TeX{}
701 * Keybindings::                 Create some personal keybindings.
702 * Keymaps::                     More about key binding.
703 * Loading Files::               Load (i.e., evaluate) files automatically.
704 * Autoload::                    Make functions available.
705 * Simple Extension::            Define a function; bind it to a key.
706 * X11 Colors::                  Colors in version 19 in X.
707 * Miscellaneous::
708 * Mode Line::                   How to customize your mode line.
710 Debugging
712 * debug::                       How to use the built-in debugger.
713 * debug-on-entry::              Start debugging when you call a function.
714 * debug-on-quit::               Start debugging when you quit with @kbd{C-g}.
715 * edebug::                      How to use Edebug, a source level debugger.
716 * Debugging Exercises::
718 Handling the Kill Ring
720 * rotate-yank-pointer::         Move a pointer along a list and around.
721 * yank::                        Paste a copy of a clipped element.
722 * yank-pop::                    Insert first element pointed to.
723 * ring file::
725 The @code{rotate-yank-pointer} Function
727 * Understanding rotate-yk-ptr::
728 * rotate-yk-ptr body::          The body of @code{rotate-yank-pointer}.
730 The Body of @code{rotate-yank-pointer}
732 * Digression concerning error::  How to mislead humans, but not computers.
733 * rotate-yk-ptr else-part::     The else-part of the @code{if} expression.
734 * Remainder Function::          The remainder, @code{%}, function.
735 * rotate-yk-ptr remainder::     Using @code{%} in @code{rotate-yank-pointer}.
736 * kill-rng-yk-ptr last elt::    Pointing to the last element.
738 @code{yank}
740 * rotate-yk-ptr arg::           Pass the argument to @code{rotate-yank-pointer}.
741 * rotate-yk-ptr negative arg::  Pass a negative argument.
743 A Graph with Labelled Axes
745 * Labelled Example::
746 * print-graph Varlist::         @code{let} expression in @code{print-graph}.
747 * print-Y-axis::                Print a label for the vertical axis.
748 * print-X-axis::                Print a horizontal label.
749 * Print Whole Graph::           The function to print a complete graph.
751 The @code{print-Y-axis} Function
753 * Height of label::             What height for the Y axis?
754 * Compute a Remainder::         How to compute the remainder of a division.
755 * Y Axis Element::              Construct a line for the Y axis.
756 * Y-axis-column::               Generate a list of Y axis labels.
757 * print-Y-axis Penultimate::    A not quite final version.
759 The @code{print-X-axis} Function
761 * Similarities differences::    Much like @code{print-Y-axis}, but not exactly.
762 * X Axis Tic Marks::            Create tic marks for the horizontal axis.
764 Printing the Whole Graph
766 * The final version::           A few changes.
767 * Test print-graph::            Run a short test.
768 * Graphing words in defuns::    Executing the final code.
769 * lambda::                      How to write an anonymous function.
770 * mapcar::                      Apply a function to elements of a list.
771 * Another Bug::                 Yet another bug @dots{} most insidious.
772 * Final printed graph::         The graph itself!
774 @end detailmenu
775 @end menu
777 @c >>>> Set pageno appropriately <<<<
779 @c The first page of the Preface is a roman numeral; it is the first
780 @c right handed page after the Table of Contents; hence the following
781 @c setting must be for an odd negative number.
783 @iftex
784 @global@pageno = -11
785 @end iftex
787 @node Preface, List Processing, Top, Top
788 @comment  node-name,  next,  previous,  up
789 @unnumbered Preface
791 Most of the GNU Emacs integrated environment is written in the programming
792 language called Emacs Lisp.  The code written in this programming
793 language is the software---the sets of instructions---that tell the
794 computer what to do when you give it commands.  Emacs is designed so
795 that you can write new code in Emacs Lisp and easily install it as an
796 extension to the editor.
798 (GNU Emacs is sometimes called an ``extensible editor'', but it does
799 much more than provide editing capabilities.  It is better to refer to
800 Emacs as an ``extensible computing environment''.  However, that
801 phrase is quite a mouthful.  It is easier to refer to Emacs simply as
802 an editor.  Moreover, everything you do in Emacs---find the Mayan date
803 and phases of the moon, simplify polynomials, debug code, manage
804 files, read letters, write books---all these activities are kinds of
805 editing in the most general sense of the word.)
807 @menu
808 * Why::                         Why learn Emacs Lisp?
809 * On Reading this Text::        Read, gain familiarity, pick up habits....
810 * Who You Are::                 For whom this is written.
811 * Lisp History::
812 * Note for Novices::            You can read this as a novice.
813 * Thank You::
814 @end menu
816 @node Why, On Reading this Text, Preface, Preface
817 @ifnottex
818 @unnumberedsec Why Study Emacs Lisp?
819 @end ifnottex
821 Although Emacs Lisp is usually thought of in association only with Emacs,
822 it is a full computer programming language.  You can use Emacs Lisp as
823 you would any other programming language.
825 Perhaps you want to understand programming; perhaps you want to extend
826 Emacs; or perhaps you want to become a programmer.  This introduction to
827 Emacs Lisp is designed to get you started: to guide you in learning the
828 fundamentals of programming, and more importantly, to show you how you
829 can teach yourself to go further.
831 @node On Reading this Text, Who You Are, Why, Preface
832 @comment  node-name,  next,  previous,  up
833 @unnumberedsec On Reading this Text
835 All through this document, you will see little sample programs you can
836 run inside of Emacs.  If you read this document in Info inside of GNU
837 Emacs, you can run the programs as they appear.  (This is easy to do and
838 is explained when the examples are presented.)  Alternatively, you can
839 read this introduction as a printed book while sitting beside a computer
840 running Emacs.  (This is what I like to do; I like printed books.)  If
841 you don't have a running Emacs beside you, you can still read this book,
842 but in this case, it is best to treat it as a novel or as a travel guide
843 to a country not yet visited: interesting, but not the same as being
844 there.
846 Much of this introduction is dedicated to walk-throughs or guided tours
847 of code used in GNU Emacs.  These tours are designed for two purposes:
848 first, to give you familiarity with real, working code (code you use
849 every day); and, second, to give you familiarity with the way Emacs
850 works.  It is interesting to see how a working environment is
851 implemented.
852 Also, I
853 hope that you will pick up the habit of browsing through source code.
854 You can learn from it and mine it for ideas.  Having GNU Emacs is like
855 having a dragon's cave of treasures.
857 In addition to learning about Emacs as an editor and Emacs Lisp as a
858 programming language, the examples and guided tours will give you an
859 opportunity to get acquainted with Emacs as a Lisp programming
860 environment.  GNU Emacs supports programming and provides tools that
861 you will want to become comfortable using, such as @kbd{M-.} (the key
862 which invokes the @code{find-tag} command).  You will also learn about
863 buffers and other objects that are part of the environment.
864 Learning about these features of Emacs is like learning new routes
865 around your home town.
867 @ignore
868 In addition, I have written several programs as extended examples.
869 Although these are examples, the programs are real.  I use them.
870 Other people use them.  You may use them.  Beyond the fragments of
871 programs used for illustrations, there is very little in here that is
872 `just for teaching purposes'; what you see is used.  This is a great
873 advantage of Emacs Lisp: it is easy to learn to use it for work.
874 @end ignore
876 Finally, I hope to convey some of the skills for using Emacs to
877 learn aspects of programming that you don't know.  You can often use
878 Emacs to help you understand what puzzles you or to find out how to do
879 something new.  This self-reliance is not only a pleasure, but an
880 advantage.
882 @node Who You Are, Lisp History, On Reading this Text, Preface
883 @comment  node-name,  next,  previous,  up
884 @unnumberedsec For Whom This is Written
886 This text is written as an elementary introduction for people who are
887 not programmers.  If you are a programmer, you may not be satisfied with
888 this primer.  The reason is that you may have become expert at reading
889 reference manuals and be put off by the way this text is organized.
891 An expert programmer who reviewed this text said to me:
893 @quotation
894 @i{I prefer to learn from reference manuals.  I ``dive into'' each
895 paragraph, and ``come up for air'' between paragraphs.}
897 @i{When I get to the end of a paragraph, I assume that that subject is
898 done, finished, that I know everything I need (with the
899 possible exception of the case when the next paragraph starts talking
900 about it in more detail).  I expect that a well written reference manual
901 will not have a lot of redundancy, and that it will have excellent
902 pointers to the (one) place where the information I want is.}
903 @end quotation
905 This introduction is not written for this person!
907 Firstly, I try to say everything at least three times: first, to
908 introduce it; second, to show it in context; and third, to show it in a
909 different context, or to review it.
911 Secondly, I hardly ever put all the information about a subject in one
912 place, much less in one paragraph.  To my way of thinking, that imposes
913 too heavy a burden on the reader.  Instead I try to explain only what
914 you need to know at the time.  (Sometimes I include a little extra
915 information so you won't be surprised later when the additional
916 information is formally introduced.)
918 When you read this text, you are not expected to learn everything the
919 first time.  Frequently, you need only make, as it were, a `nodding
920 acquaintance' with some of the items mentioned.  My hope is that I have
921 structured the text and given you enough hints that you will be alert to
922 what is important, and concentrate on it.
924 You will need to ``dive into'' some paragraphs; there is no other way
925 to read them.  But I have tried to keep down the number of such
926 paragraphs.  This book is intended as an approachable hill, rather than
927 as a daunting mountain.
929 This introduction to @cite{Programming in Emacs Lisp} has a companion
930 document,
931 @iftex
932 @cite{The GNU Emacs Lisp Reference Manual}.
933 @end iftex
934 @ifnottex
935 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
936 Emacs Lisp Reference Manual}.
937 @end ifnottex
938 The reference manual has more detail than this introduction.  In the
939 reference manual, all the information about one topic is concentrated
940 in one place.  You should turn to it if you are like the programmer
941 quoted above.  And, of course, after you have read this
942 @cite{Introduction}, you will find the @cite{Reference Manual} useful
943 when you are writing your own programs.
945 @node Lisp History, Note for Novices, Who You Are, Preface
946 @unnumberedsec Lisp History
947 @cindex Lisp history
949 Lisp was first developed in the late 1950s at the Massachusetts
950 Institute of Technology for research in artificial intelligence.  The
951 great power of the Lisp language makes it superior for other purposes as
952 well, such as writing editor commands and integrated environments.
954 @cindex Maclisp
955 @cindex Common Lisp
956 GNU Emacs Lisp is largely inspired by Maclisp, which was written at MIT
957 in the 1960s.  It is somewhat inspired by Common Lisp, which became a
958 standard in the 1980s.  However, Emacs Lisp is much simpler than Common
959 Lisp.  (The standard Emacs distribution contains an optional extensions
960 file, @file{cl.el}, that adds many Common Lisp features to Emacs Lisp.)
962 @node Note for Novices, Thank You, Lisp History, Preface
963 @comment  node-name,  next,  previous,  up
964 @unnumberedsec A Note for Novices
966 If you don't know GNU Emacs, you can still read this document
967 profitably.  However, I recommend you learn Emacs, if only to learn to
968 move around your computer screen.  You can teach yourself how to use
969 Emacs with the on-line tutorial.  To use it, type @kbd{C-h t}.  (This
970 means you press and release the @key{CTRL} key and the @kbd{h} at the
971 same time, and then press and release @kbd{t}.)
973 Also, I often refer to one of Emacs' standard commands by listing the
974 keys which you press to invoke the command and then giving the name of
975 the command in parentheses, like this: @kbd{M-C-\}
976 (@code{indent-region}).  What this means is that the
977 @code{indent-region} command is customarily invoked by typing
978 @kbd{M-C-\}.  (You can, if you wish, change the keys that are typed to
979 invoke the command; this is called @dfn{rebinding}.  @xref{Keymaps, ,
980 Keymaps}.)  The abbreviation @kbd{M-C-\} means that you type your
981 @key{META} key, @key{CTRL} key and @key{\} key all at the same time.
982 (On many modern keyboards the @key{META} key is labelled
983 @key{ALT}.)
984 Sometimes a combination like this is called a keychord, since it is
985 similar to the way you play a chord on a piano.  If your keyboard does
986 not have a @key{META} key, the @key{ESC} key prefix is used in place
987 of it.  In this case, @kbd{M-C-\} means that you press and release your
988 @key{ESC} key and then type the @key{CTRL} key and the @key{\} key at
989 the same time.  But usually @kbd{M-C-\} means press the @key{CTRL} key
990 along with the key that is labelled @key{ALT} and, at the same time,
991 press the @key{\} key.
993 In addition to typing a lone keychord, you can prefix what you type
994 with @kbd{C-u}, which is called the `universal argument'.  The
995 @kbd{C-u} keychord passes an argument to the subsequent command.
996 Thus, to indent a region of plain text by 6 spaces, mark the region,
997 and then type @w{@kbd{C-u 6 M-C-\}}.  (If you do not specify a number,
998 Emacs either passes the number 4 to the command or otherwise runs the
999 command differently than it would otherwise.)  @xref{Arguments, ,
1000 Numeric Arguments, emacs, The GNU Emacs Manual}.
1002 If you are reading this in Info using GNU Emacs, you can read through
1003 this whole document just by pressing the space bar, @key{SPC}.
1004 (To learn about Info, type @kbd{C-h i} and then select Info.)
1006 A note on terminology:  when I use the word Lisp alone, I often am
1007 referring to the various dialects of Lisp in general, but when I speak
1008 of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
1010 @node Thank You,  , Note for Novices, Preface
1011 @comment  node-name,  next,  previous,  up
1012 @unnumberedsec Thank You
1014 My thanks to all who helped me with this book.  My especial thanks to
1015 @r{Jim Blandy}, @r{Noah Friedman}, @w{Jim Kingdon}, @r{Roland
1016 McGrath}, @w{Frank Ritter}, @w{Randy Smith}, @w{Richard M.@:
1017 Stallman}, and @w{Melissa Weisshaus}.  My thanks also go to both
1018 @w{Philip Johnson} and @w{David Stampe} for their patient
1019 encouragement.  My mistakes are my own.
1021 @flushright
1022 Robert J. Chassell
1023 @end flushright
1025 @c ================ Beginning of main text ================
1027 @c Start main text on right-hand (verso) page
1029 @tex
1030 \par\vfill\supereject
1031 \headings off
1032 \ifodd\pageno
1033     \par\vfill\supereject
1034 \else
1035     \par\vfill\supereject
1036     \page\hbox{}\page
1037     \par\vfill\supereject
1039 @end tex
1041 @iftex
1042 @headings off
1043 @evenheading @thispage @| @| @thischapter
1044 @oddheading @thissection @| @| @thispage
1045 @global@pageno = 1
1046 @end iftex
1048 @node List Processing, Practicing Evaluation, Preface, Top
1049 @comment  node-name,  next,  previous,  up
1050 @chapter List Processing
1052 To the untutored eye, Lisp is a strange programming language.  In Lisp
1053 code there are parentheses everywhere.  Some people even claim that the
1054 name stands for `Lots of Isolated Silly Parentheses'.  But the claim is
1055 unwarranted.  Lisp stands for LISt Processing, and the programming
1056 language handles @emph{lists} (and lists of lists) by putting them
1057 between parentheses.  The parentheses mark the boundaries of the list.
1058 Sometimes a list is preceded by a single apostrophe or quotation mark,
1059 @samp{'}.  Lists are the basis of Lisp.
1061 @menu
1062 * Lisp Lists::                  What are lists?
1063 * Run a Program::               Any list in Lisp is a program ready to run.
1064 * Making Errors::               Generating an error message.
1065 * Names & Definitions::         Names of symbols and function definitions.
1066 * Lisp Interpreter::            What the Lisp interpreter does.
1067 * Evaluation::                  Running a program.
1068 * Variables::                   Returning a value from a variable.
1069 * Arguments::                   Passing information to a function.
1070 * set & setq::                  Setting the value of a variable.
1071 * Summary::                     The major points.
1072 * Error Message Exercises::
1073 @end menu
1075 @node Lisp Lists, Run a Program, List Processing, List Processing
1076 @comment  node-name,  next,  previous,  up
1077 @section Lisp Lists
1078 @cindex Lisp Lists
1080 In Lisp, a list looks like this: @code{'(rose violet daisy buttercup)}.
1081 This list is preceded by a single apostrophe.  It could just as well be
1082 written as follows, which looks more like the kind of list you are likely
1083 to be familiar with:
1085 @smallexample
1086 @group
1087 '(rose
1088   violet
1089   daisy
1090   buttercup)
1091 @end group
1092 @end smallexample
1094 @noindent
1095 The elements of this list are the names of the four different flowers,
1096 separated from each other by whitespace and surrounded by parentheses,
1097 like flowers in a field with a stone wall around them.
1098 @cindex Flowers in a field
1100 @menu
1101 * Numbers Lists::               List have numbers, other lists, in them.
1102 * Lisp Atoms::                  Elemental entities.
1103 * Whitespace in Lists::         Formating lists to be readable.
1104 * Typing Lists::                How GNU Emacs helps you type lists.
1105 @end menu
1107 @node Numbers Lists, Lisp Atoms, Lisp Lists, Lisp Lists
1108 @ifnottex
1109 @unnumberedsubsec Numbers, Lists inside of Lists
1110 @end ifnottex
1112 Lists can also have numbers in them, as in this list: @code{(+ 2 2)}.
1113 This list has a plus-sign, @samp{+}, followed by two @samp{2}s, each
1114 separated by whitespace.
1116 In Lisp, both data and programs are represented the same way; that is,
1117 they are both lists of words, numbers, or other lists, separated by
1118 whitespace and surrounded by parentheses.  (Since a program looks like
1119 data, one program may easily serve as data for another; this is a very
1120 powerful feature of Lisp.)  (Incidentally, these two parenthetical
1121 remarks are @emph{not} Lisp lists, because they contain @samp{;} and
1122 @samp{.} as punctuation marks.)
1124 @need 1200
1125 Here is another list, this time with a list inside of it:
1127 @smallexample
1128 '(this list has (a list inside of it))
1129 @end smallexample
1131 The components of this list are the words @samp{this}, @samp{list},
1132 @samp{has}, and the list @samp{(a list inside of it)}.  The interior
1133 list is made up of the words @samp{a}, @samp{list}, @samp{inside},
1134 @samp{of}, @samp{it}.
1136 @node Lisp Atoms, Whitespace in Lists, Numbers Lists, Lisp Lists
1137 @comment  node-name,  next,  previous,  up
1138 @subsection Lisp Atoms
1139 @cindex Lisp Atoms
1141 In Lisp, what we have been calling words are called @dfn{atoms}.  This
1142 term comes from the historical meaning of the word atom, which means
1143 `indivisible'.  As far as Lisp is concerned, the words we have been
1144 using in the lists cannot be divided into any smaller parts and still
1145 mean the same thing as part of a program; likewise with numbers and
1146 single character symbols like @samp{+}.  On the other hand, unlike an
1147 atom, a list can be split into parts.  (@xref{car cdr & cons, ,
1148 @code{car} @code{cdr} & @code{cons} Fundamental Functions}.)
1150 In a list, atoms are separated from each other by whitespace.  They can be
1151 right next to a parenthesis.
1153 @cindex @samp{empty list} defined
1154 Technically speaking, a list in Lisp consists of parentheses surrounding
1155 atoms separated by whitespace or surrounding other lists or surrounding
1156 both atoms and other lists.  A list can have just one atom in it or
1157 have nothing in it at all.  A list with nothing in it looks like this:
1158 @code{()}, and is called the @dfn{empty list}.  Unlike anything else, an
1159 empty list is considered both an atom and a list at the same time.
1161 @cindex Symbolic expressions, introduced
1162 @cindex @samp{expression} defined
1163 @cindex @samp{form} defined
1164 The printed representation of both atoms and lists are called
1165 @dfn{symbolic expressions} or, more concisely, @dfn{s-expressions}.
1166 The word @dfn{expression} by itself can refer to either the printed
1167 representation, or to the atom or list as it is held internally in the
1168 computer.  Often, people use the term @dfn{expression}
1169 indiscriminately.  (Also, in many texts, the word @dfn{form} is used
1170 as a synonym for expression.)
1172 Incidentally, the atoms that make up our universe were named such when
1173 they were thought to be indivisible; but it has been found that physical
1174 atoms are not indivisible.  Parts can split off an atom or it can
1175 fission into two parts of roughly equal size.  Physical atoms were named
1176 prematurely, before their truer nature was found.  In Lisp, certain
1177 kinds of atom, such as an array, can be separated into parts; but the
1178 mechanism for doing this is different from the mechanism for splitting a
1179 list.  As far as list operations are concerned, the atoms of a list are
1180 unsplittable.
1182 As in English, the meanings of the component letters of a Lisp atom
1183 are different from the meaning the letters make as a word.  For
1184 example, the word for the South American sloth, the @samp{ai}, is
1185 completely different from the two words, @samp{a}, and @samp{i}.
1187 There are many kinds of atom in nature but only a few in Lisp: for
1188 example, @dfn{numbers}, such as 37, 511, or 1729, and @dfn{symbols}, such
1189 as @samp{+}, @samp{foo}, or @samp{forward-line}.  The words we have
1190 listed in the examples above are all symbols.  In everyday Lisp
1191 conversation, the word ``atom'' is not often used, because programmers
1192 usually try to be more specific about what kind of atom they are dealing
1193 with.  Lisp programming is mostly about symbols (and sometimes numbers)
1194 within lists.  (Incidentally, the preceding three word parenthetical
1195 remark is a proper list in Lisp, since it consists of atoms, which in
1196 this case are symbols, separated by whitespace and enclosed by
1197 parentheses, without any non-Lisp punctuation.)
1199 @need 1250
1200 In addition, text between double quotation marks---even sentences or
1201 paragraphs---is an atom.  Here is an example:
1202 @cindex Text between double quotation marks
1204 @smallexample
1205 '(this list includes "text between quotation marks.")
1206 @end smallexample
1208 @cindex @samp{string} defined
1209 @noindent
1210 In Lisp, all of the quoted text including the punctuation mark and the
1211 blank spaces is a single atom.  This kind of atom is called a
1212 @dfn{string} (for `string of characters') and is the sort of thing that
1213 is used for messages that a computer can print for a human to read.
1214 Strings are a different kind of atom than numbers or symbols and are
1215 used differently.
1217 @node Whitespace in Lists, Typing Lists, Lisp Atoms, Lisp Lists
1218 @comment  node-name,  next,  previous,  up
1219 @subsection Whitespace in Lists
1220 @cindex Whitespace in lists
1222 @need 1200
1223 The amount of whitespace in a list does not matter.  From the point of view
1224 of the Lisp language,
1226 @smallexample
1227 @group
1228 '(this list
1229    looks like this)
1230 @end group
1231 @end smallexample
1233 @need 800
1234 @noindent
1235 is exactly the same as this:
1237 @smallexample
1238 '(this list looks like this)
1239 @end smallexample
1241 Both examples show what to Lisp is the same list, the list made up of
1242 the symbols @samp{this}, @samp{list}, @samp{looks}, @samp{like}, and
1243 @samp{this} in that order.
1245 Extra whitespace and newlines are designed to make a list more readable
1246 by humans.  When Lisp reads the expression, it gets rid of all the extra
1247 whitespace (but it needs to have at least one space between atoms in
1248 order to tell them apart.)
1250 Odd as it seems, the examples we have seen cover almost all of what Lisp
1251 lists look like!  Every other list in Lisp looks more or less like one
1252 of these examples, except that the list may be longer and more complex.
1253 In brief, a list is between parentheses, a string is between quotation
1254 marks, a symbol looks like a word, and a number looks like a number.
1255 (For certain situations, square brackets, dots and a few other special
1256 characters may be used; however, we will go quite far without them.)
1258 @node Typing Lists,  , Whitespace in Lists, Lisp Lists
1259 @comment  node-name,  next,  previous,  up
1260 @subsection GNU Emacs Helps You Type Lists
1261 @cindex Help typing lists
1262 @cindex Formatting help
1264 When you type a Lisp expression in GNU Emacs using either Lisp
1265 Interaction mode or Emacs Lisp mode, you have available to you several
1266 commands to format the Lisp expression so it is easy to read.  For
1267 example, pressing the @key{TAB} key automatically indents the line the
1268 cursor is on by the right amount.  A command to properly indent the
1269 code in a region is customarily bound to @kbd{M-C-\}.  Indentation is
1270 designed so that you can see which elements of a list belong to which
1271 list---elements of a sub-list are indented more than the elements of
1272 the enclosing list.
1274 In addition, when you type a closing parenthesis, Emacs momentarily
1275 jumps the cursor back to the matching opening parenthesis, so you can
1276 see which one it is.  This is very useful, since every list you type
1277 in Lisp must have its closing parenthesis match its opening
1278 parenthesis.  (@xref{Major Modes, , Major Modes, emacs, The GNU Emacs
1279 Manual}, for more information about Emacs' modes.)
1281 @node Run a Program, Making Errors, Lisp Lists, List Processing
1282 @comment  node-name,  next,  previous,  up
1283 @section Run a Program
1284 @cindex Run a program
1285 @cindex Program, running one
1287 @cindex @samp{evaluate} defined
1288 A list in Lisp---any list---is a program ready to run.  If you run it
1289 (for which the Lisp jargon is @dfn{evaluate}), the computer will do one
1290 of three things: do nothing except return to you the list itself; send
1291 you an error message; or, treat the first symbol in the list as a
1292 command to do something.  (Usually, of course, it is the last of these
1293 three things that you really want!)
1295 @c use code for the single apostrophe, not samp.
1296 The single apostrophe, @code{'}, that I put in front of some of the
1297 example lists in preceding sections is called a @dfn{quote}; when it
1298 precedes a list, it tells Lisp to do nothing with the list, other than
1299 take it as it is written.  But if there is no quote preceding a list,
1300 the first item of the list is special: it is a command for the computer
1301 to obey.  (In Lisp, these commands are called @emph{functions}.)  The list
1302 @code{(+ 2 2)} shown above did not have a quote in front of it, so Lisp
1303 understands that the @code{+} is an instruction to do something with the
1304 rest of the list: add the numbers that follow.
1306 @need 1250
1307 If you are reading this inside of GNU Emacs in Info, here is how you can
1308 evaluate such a list:  place your cursor immediately after the right
1309 hand parenthesis of the following list and then type @kbd{C-x C-e}:
1311 @smallexample
1312 (+ 2 2)
1313 @end smallexample
1315 @c use code for the number four, not samp.
1316 @noindent
1317 You will see the number @code{4} appear in the echo area.  (In the
1318 jargon, what you have just done is ``evaluate the list.''  The echo area
1319 is the line at the bottom of the screen that displays or ``echoes''
1320 text.)  Now try the same thing with a quoted list:  place the cursor
1321 right after the following list and type @kbd{C-x C-e}:
1323 @smallexample
1324 '(this is a quoted list)
1325 @end smallexample
1327 @noindent
1328 You will see @code{(this is a quoted list)} appear in the echo area.
1330 @cindex Lisp interpreter, explained
1331 @cindex Interpreter, Lisp, explained
1332 In both cases, what you are doing is giving a command to the program
1333 inside of GNU Emacs called the @dfn{Lisp interpreter}---giving the
1334 interpreter a command to evaluate the expression.  The name of the Lisp
1335 interpreter comes from the word for the task done by a human who comes
1336 up with the meaning of an expression---who ``interprets'' it.
1338 You can also evaluate an atom that is not part of a list---one that is
1339 not surrounded by parentheses; again, the Lisp interpreter translates
1340 from the humanly readable expression to the language of the computer.
1341 But before discussing this (@pxref{Variables}), we will discuss what the
1342 Lisp interpreter does when you make an error.
1344 @node Making Errors, Names & Definitions, Run a Program, List Processing
1345 @comment  node-name,  next,  previous,  up
1346 @section Generate an Error Message
1347 @cindex Generate an error message
1348 @cindex Error message generation
1350 Partly so you won't worry if you do it accidentally, we will now give
1351 a command to the Lisp interpreter that generates an error message.
1352 This is a harmless activity; and indeed, we will often try to generate
1353 error messages intentionally.  Once you understand the jargon, error
1354 messages can be informative.  Instead of being called ``error''
1355 messages, they should be called ``help'' messages.  They are like
1356 signposts to a traveller in a strange country; deciphering them can be
1357 hard, but once understood, they can point the way.
1359 The error message is generated by a built-in GNU Emacs debugger.  We
1360 will `enter the debugger'.  You get out of the debugger by typing @code{q}.
1362 What we will do is evaluate a list that is not quoted and does not
1363 have a meaningful command as its first element.  Here is a list almost
1364 exactly the same as the one we just used, but without the single-quote
1365 in front of it.  Position the cursor right after it and type @kbd{C-x
1366 C-e}:
1368 @smallexample
1369 (this is an unquoted list)
1370 @end smallexample
1372 @noindent
1373 What you see depends on which version of Emacs you are running.  GNU
1374 Emacs version 21 provides more information than version 20 and before.
1375 First, the more recent result of generating an error; then the
1376 earlier, version 20 result.
1378 @need 1250
1379 @noindent
1380 In GNU Emacs version 21, a @file{*Backtrace*} window will open up and
1381 you will see the following in it:
1383 @smallexample
1384 @group
1385 ---------- Buffer: *Backtrace* ----------
1386 Debugger entered--Lisp error: (void-function this)
1387   (this is an unquoted list)
1388   eval((this is an unquoted list))
1389   eval-last-sexp-1(nil)
1390   eval-last-sexp(nil)
1391   call-interactively(eval-last-sexp)
1392 ---------- Buffer: *Backtrace* ----------
1393 @end group
1394 @end smallexample
1396 @need 1200
1397 @noindent
1398 Your cursor will be in this window (you may have to wait a few seconds
1399 before it becomes visible).  To quit the debugger and make the
1400 debugger window go away, type:
1402 @smallexample
1404 @end smallexample
1406 @noindent
1407 Please type @kbd{q} right now, so you become confident that you can
1408 get out of the debugger.  Then, type @kbd{C-x C-e} again to re-enter
1411 @cindex @samp{function} defined
1412 Based on what we already know, we can almost read this error message.
1414 You read the @file{*Backtrace*} buffer from the bottom up; it tells
1415 you what Emacs did.  When you typed @kbd{C-x C-e}, you made an
1416 interactive call to the command @code{eval-last-sexp}.  @code{eval} is
1417 an abbreviation for `evaluate' and @code{sexp} is an abbreviation for
1418 `symbolic expression'.  The command means `evaluate last symbolic
1419 expression', which is the expression just before your cursor.
1421 Each line above tells you what the Lisp interpreter evaluated next.
1422 The most recent action is at the top.  The buffer is called the
1423 @file{*Backtrace*} buffer because it enables you to track Emacs
1424 backwards.
1426 @need 800
1427 At the top of the @file{*Backtrace*} buffer, you see the line:
1429 @smallexample
1430 Debugger entered--Lisp error: (void-function this)
1431 @end smallexample
1433 @noindent
1434 The Lisp interpreter tried to evaluate the first atom of the list, the
1435 word @samp{this}.  It is this action that generated the error message
1436 @samp{void-function this}.
1438 The message contains the words @samp{void-function} and @samp{this}.
1440 @cindex @samp{function} defined
1441 The word @samp{function} was mentioned once before.  It is a very
1442 important word.  For our purposes, we can define it by saying that a
1443 @dfn{function} is a set of instructions to the computer that tell the
1444 computer to do something.
1446 Now we can begin to understand the error message: @samp{void-function
1447 this}.  The function (that is, the word @samp{this}) does not have a
1448 definition of any set of instructions for the computer to carry out.
1450 The slightly odd word, @samp{void-function}, is designed to cover the
1451 way Emacs Lisp is implemented, which is that when a symbol does not
1452 have a function definition attached to it, the place that should
1453 contain the instructions is `void'.
1455 On the other hand, since we were able to add 2 plus 2 successfully, by
1456 evaluating @code{(+ 2 2)}, we can infer that the symbol @code{+} must
1457 have a set of instructions for the computer to obey and those
1458 instructions must be to add the numbers that follow the @code{+}.
1460 @need 1250
1461 In GNU Emacs version 20, and in earlier versions, you will see only
1462 one line of error message; it will appear in the echo area and look
1463 like this:
1465 @smallexample
1466 Symbol's function definition is void:@: this
1467 @end smallexample
1469 @noindent
1470 (Also, your terminal may beep at you---some do, some don't; and others
1471 blink.  This is just a device to get your attention.)  The message goes
1472 away as soon as you type another key, even just to move the cursor.
1474 We know the meaning of the word @samp{Symbol}.  It refers to the first
1475 atom of the list, the word @samp{this}.  The word @samp{function}
1476 refers to the instructions that tell the computer what to do.
1477 (Technically, the symbol tells the computer where to find the
1478 instructions, but this is a complication we can ignore for the
1479 moment.)
1481 The error message can be understood: @samp{Symbol's function
1482 definition is void:@: this}.  The symbol (that is, the word
1483 @samp{this}) lacks instructions for the computer to carry out.
1485 @node Names & Definitions, Lisp Interpreter, Making Errors, List Processing
1486 @comment  node-name,  next,  previous,  up
1487 @section Symbol Names and Function Definitions
1488 @cindex Symbol names
1490 We can articulate another characteristic of Lisp based on what we have
1491 discussed so far---an important characteristic: a symbol, like
1492 @code{+}, is not itself the set of instructions for the computer to
1493 carry out.  Instead, the symbol is used, perhaps temporarily, as a way
1494 of locating the definition or set of instructions.  What we see is the
1495 name through which the instructions can be found.  Names of people
1496 work the same way.  I can be referred to as @samp{Bob}; however, I am
1497 not the letters @samp{B}, @samp{o}, @samp{b} but am, or were, the
1498 consciousness consistently associated with a particular life-form.
1499 The name is not me, but it can be used to refer to me.
1501 In Lisp, one set of instructions can be attached to several names.
1502 For example, the computer instructions for adding numbers can be
1503 linked to the symbol @code{plus} as well as to the symbol @code{+}
1504 (and are in some dialects of Lisp).  Among humans, I can be referred
1505 to as @samp{Robert} as well as @samp{Bob} and by other words as well.
1507 On the other hand, a symbol can have only one function definition
1508 attached to it at a time.  Otherwise, the computer would be confused as
1509 to which definition to use.  If this were the case among people, only
1510 one person in the world could be named @samp{Bob}.  However, the function
1511 definition to which the name refers can be changed readily.
1512 (@xref{Install, , Install a Function Definition}.)
1514 Since Emacs Lisp is large, it is customary to name symbols in a way
1515 that identifies the part of Emacs to which the function belongs.
1516 Thus, all the names for functions that deal with Texinfo start with
1517 @samp{texinfo-} and those for functions that deal with reading mail
1518 start with @samp{rmail-}.
1520 @node Lisp Interpreter, Evaluation, Names & Definitions, List Processing
1521 @comment  node-name,  next,  previous,  up
1522 @section The Lisp Interpreter
1523 @cindex Lisp interpreter, what it does
1524 @cindex Interpreter, what it does
1526 Based on what we have seen, we can now start to figure out what the
1527 Lisp interpreter does when we command it to evaluate a list.
1528 First, it looks to see whether there is a quote before the list; if
1529 there is, the interpreter just gives us the list.  On the other
1530 hand, if there is no quote, the interpreter looks at the first element
1531 in the list and sees whether it has a function definition.  If it does,
1532 the interpreter carries out the instructions in the function definition.
1533 Otherwise, the interpreter prints an error message.
1535 This is how Lisp works.  Simple.  There are added complications which we
1536 will get to in a minute, but these are the fundamentals.  Of course, to
1537 write Lisp programs, you need to know how to write function definitions
1538 and attach them to names, and how to do this without confusing either
1539 yourself or the computer.
1541 @menu
1542 * Complications::               Variables, Special forms, Lists within.
1543 * Byte Compiling::              Specially processing code for speed.
1544 @end menu
1546 @node Complications, Byte Compiling, Lisp Interpreter, Lisp Interpreter
1547 @ifnottex
1548 @unnumberedsubsec Complications
1549 @end ifnottex
1551 Now, for the first complication.  In addition to lists, the Lisp
1552 interpreter can evaluate a symbol that is not quoted and does not have
1553 parentheses around it.  The Lisp interpreter will attempt to determine
1554 the symbol's value as a @dfn{variable}.  This situation is described
1555 in the section on variables.  (@xref{Variables}.)
1557 @cindex Special form
1558 The second complication occurs because some functions are unusual and do
1559 not work in the usual manner.  Those that don't are called @dfn{special
1560 forms}.  They are used for special jobs, like defining a function, and
1561 there are not many of them.  In the next few chapters, you will be
1562 introduced to several of the more important special forms.
1564 The third and final complication is this: if the function that the
1565 Lisp interpreter is looking at is not a special form, and if it is part
1566 of a list, the Lisp interpreter looks to see whether the list has a list
1567 inside of it.  If there is an inner list, the Lisp interpreter first
1568 figures out what it should do with the inside list, and then it works on
1569 the outside list.  If there is yet another list embedded inside the
1570 inner list, it works on that one first, and so on.  It always works on
1571 the innermost list first.  The interpreter works on the innermost list
1572 first, to evaluate the result of that list.  The result may be
1573 used by the enclosing expression.
1575 Otherwise, the interpreter works left to right, from one expression to
1576 the next.
1578 @node Byte Compiling,  , Complications, Lisp Interpreter
1579 @subsection Byte Compiling
1580 @cindex Byte compiling
1582 One other aspect of interpreting: the Lisp interpreter is able to
1583 interpret two kinds of entity: humanly readable code, on which we will
1584 focus exclusively, and specially processed code, called @dfn{byte
1585 compiled} code, which is not humanly readable.  Byte compiled code
1586 runs faster than humanly readable code.
1588 You can transform humanly readable code into byte compiled code by
1589 running one of the compile commands such as @code{byte-compile-file}.
1590 Byte compiled code is usually stored in a file that ends with a
1591 @file{.elc} extension rather than a @file{.el} extension.  You will
1592 see both kinds of file in the @file{emacs/lisp} directory; the files
1593 to read are those with @file{.el} extensions.
1595 As a practical matter, for most things you might do to customize or
1596 extend Emacs, you do not need to byte compile; and I will not discuss
1597 the topic here.  @xref{Byte Compilation, , Byte Compilation, elisp,
1598 The GNU Emacs Lisp Reference Manual}, for a full description of byte
1599 compilation.
1601 @node Evaluation, Variables, Lisp Interpreter, List Processing
1602 @comment  node-name,  next,  previous,  up
1603 @section Evaluation
1604 @cindex Evaluation
1606 When the Lisp interpreter works on an expression, the term for the
1607 activity is called @dfn{evaluation}.  We say that the interpreter
1608 `evaluates the expression'.  I've used this term several times before.
1609 The word comes from its use in everyday language, `to ascertain the
1610 value or amount of; to appraise', according to @cite{Webster's New
1611 Collegiate Dictionary}.
1613 After evaluating an expression, the Lisp interpreter will most likely
1614 @dfn{return} the value that the computer produces by carrying out the
1615 instructions it found in the function definition, or perhaps it will
1616 give up on that function and produce an error message.  (The interpreter
1617 may also find itself tossed, so to speak, to a different function or it
1618 may attempt to repeat continually what it is doing for ever and ever in
1619 what is called an `infinite loop'.  These actions are less common; and
1620 we can ignore them.)  Most frequently, the interpreter returns a value.
1622 @cindex @samp{side effect} defined
1623 At the same time the interpreter returns a value, it may do something
1624 else as well, such as move a cursor or copy a file; this other kind of
1625 action is called a @dfn{side effect}.  Actions that we humans think are
1626 important, such as printing results, are often ``side effects'' to the
1627 Lisp interpreter.  The jargon can sound peculiar, but it turns out that
1628 it is fairly easy to learn to use side effects.
1630 In summary, evaluating a symbolic expression most commonly causes the
1631 Lisp interpreter to return a value and perhaps carry out a side effect;
1632 or else produce an error.
1634 @menu
1635 * Evaluating Inner Lists::      Lists within lists...
1636 @end menu
1638 @node Evaluating Inner Lists,  , Evaluation, Evaluation
1639 @comment  node-name,  next,  previous,  up
1640 @subsection Evaluating Inner Lists
1641 @cindex Inner list evaluation
1642 @cindex Evaluating inner lists
1644 If evaluation applies to a list that is inside another list, the outer
1645 list may use the value returned by the first evaluation as information
1646 when the outer list is evaluated.  This explains why inner expressions
1647 are evaluated first: the values they return are used by the outer
1648 expressions.
1650 @need 1250
1651 We can investigate this process by evaluating another addition example.
1652 Place your cursor after the following expression and type @kbd{C-x C-e}:
1654 @smallexample
1655 (+ 2 (+ 3 3))
1656 @end smallexample
1658 @noindent
1659 The number 8 will appear in the echo area.
1661 What happens is that the Lisp interpreter first evaluates the inner
1662 expression, @code{(+ 3 3)}, for which the value 6 is returned; then it
1663 evaluates the outer expression as if it were written @code{(+ 2 6)}, which
1664 returns the value 8.  Since there are no more enclosing expressions to
1665 evaluate, the interpreter prints that value in the echo area.
1667 Now it is easy to understand the name of the command invoked by the
1668 keystrokes @kbd{C-x C-e}: the name is @code{eval-last-sexp}.  The
1669 letters @code{sexp} are an abbreviation for `symbolic expression', and
1670 @code{eval} is an abbreviation for `evaluate'.  The command means
1671 `evaluate last symbolic expression'.
1673 As an experiment, you can try evaluating the expression by putting the
1674 cursor at the beginning of the next line immediately following the
1675 expression, or inside the expression.
1677 @need 800
1678 Here is another copy of the expression:
1680 @smallexample
1681 (+ 2 (+ 3 3))
1682 @end smallexample
1684 @noindent
1685 If you place the cursor at the beginning of the blank line that
1686 immediately follows the expression and type @kbd{C-x C-e}, you will
1687 still get the value 8 printed in the echo area.  Now try putting the
1688 cursor inside the expression.  If you put it right after the next to
1689 last parenthesis (so it appears to sit on top of the last parenthesis),
1690 you will get a 6 printed in the echo area!  This is because the command
1691 evaluates the expression @code{(+ 3 3)}.
1693 Now put the cursor immediately after a number.  Type @kbd{C-x C-e} and
1694 you will get the number itself.  In Lisp, if you evaluate a number, you
1695 get the number itself---this is how numbers differ from symbols.  If you
1696 evaluate a list starting with a symbol like @code{+}, you will get a
1697 value returned that is the result of the computer carrying out the
1698 instructions in the function definition attached to that name.  If a
1699 symbol by itself is evaluated, something different happens, as we will
1700 see in the next section.
1702 @node Variables, Arguments, Evaluation, List Processing
1703 @comment  node-name,  next,  previous,  up
1704 @section Variables
1705 @cindex Variables
1707 In Emacs Lisp, a symbol can have a value attached to it just as it can
1708 have a function definition attached to it.  The two are different.
1709 The function definition is a set of instructions that a computer will
1710 obey.  A value, on the other hand, is something, such as number or a
1711 name, that can vary (which is why such a symbol is called a variable).
1712 The value of a symbol can be any expression in Lisp, such as a symbol,
1713 number, list, or string.  A symbol that has a value is often called a
1714 @dfn{variable}.
1716 A symbol can have both a function definition and a value attached to
1717 it at the same time.  Or it can have just one or the other.
1718 The two are separate.  This is somewhat similar
1719 to the way the name Cambridge can refer to the city in Massachusetts
1720 and have some information attached to the name as well, such as
1721 ``great programming center''.
1723 @ignore
1724 (Incidentally, in Emacs Lisp, a symbol can have two
1725 other things attached to it, too: a property list and a documentation
1726 string; these are discussed later.)
1727 @end ignore
1729 Another way to think about this is to imagine a symbol as being a chest
1730 of drawers.  The function definition is put in one drawer, the value in
1731 another, and so on.  What is put in the drawer holding the value can be
1732 changed without affecting the contents of the drawer holding the
1733 function definition, and vice-versa.
1735 @menu
1736 * fill-column Example::
1737 * Void Function::               The error message for a symbol
1738                                   without a function.
1739 * Void Variable::               The error message for a symbol without a value.
1740 @end menu
1742 @node fill-column Example, Void Function, Variables, Variables
1743 @ifnottex
1744 @unnumberedsubsec @code{fill-column}, an Example Variable
1745 @end ifnottex
1747 @findex fill-column, @r{an example variable}
1748 @cindex Example variable, @code{fill-column}
1749 @cindex Variable, example of, @code{fill-column}
1750 The variable @code{fill-column} illustrates a symbol with a value
1751 attached to it: in every GNU Emacs buffer, this symbol is set to some
1752 value, usually 72 or 70, but sometimes to some other value.  To find the
1753 value of this symbol, evaluate it by itself.  If you are reading this in
1754 Info inside of GNU Emacs, you can do this by putting the cursor after
1755 the symbol and typing @kbd{C-x C-e}:
1757 @smallexample
1758 fill-column
1759 @end smallexample
1761 @noindent
1762 After I typed @kbd{C-x C-e}, Emacs printed the number 72 in my echo
1763 area.  This is the value for which @code{fill-column} is set for me as I
1764 write this.  It may be different for you in your Info buffer.  Notice
1765 that the value returned as a variable is printed in exactly the same way
1766 as the value returned by a function carrying out its instructions.  From
1767 the point of view of the Lisp interpreter, a value returned is a value
1768 returned.  What kind of expression it came from ceases to matter once
1769 the value is known.
1771 A symbol can have any value attached to it or, to use the jargon, we can
1772 @dfn{bind} the variable to a value: to a number, such as 72; to a
1773 string, @code{"such as this"}; to a list, such as @code{(spruce pine
1774 oak)}; we can even bind a variable to a function definition.
1776 A symbol can be bound to a value in several ways.  @xref{set & setq, ,
1777 Setting the Value of a Variable}, for information about one way to do
1778 this.
1780 @node Void Function, Void Variable, fill-column Example, Variables
1781 @comment  node-name,  next,  previous,  up
1782 @subsection Error Message for a Symbol Without a Function
1783 @cindex Symbol without function error
1784 @cindex Error for symbol without function
1786 When we evaluated @code{fill-column} to find its value as a variable,
1787 we did not place parentheses around the word.  This is because we did
1788 not intend to use it as a function name.
1790 If @code{fill-column} were the first or only element of a list, the
1791 Lisp interpreter would attempt to find the function definition
1792 attached to it.  But @code{fill-column} has no function definition.
1793 Try evaluating this:
1795 @smallexample
1796 (fill-column)
1797 @end smallexample
1799 @need 1250
1800 @noindent
1801 In GNU Emacs version 21, you will create a @file{*Backtrace*} buffer
1802 that says:
1804 @smallexample
1805 @group
1806 ---------- Buffer: *Backtrace* ----------
1807 Debugger entered--Lisp error: (void-function fill-column)
1808   (fill-column)
1809   eval((fill-column))
1810   eval-last-sexp-1(nil)
1811   eval-last-sexp(nil)
1812   call-interactively(eval-last-sexp)
1813 ---------- Buffer: *Backtrace* ----------
1814 @end group
1815 @end smallexample
1817 @noindent
1818 (Remember, to quit the debugger and make the debugger window go away,
1819 type @kbd{q} in the @file{*Backtrace*} buffer.)
1821 @need 800
1822 In GNU Emacs 20 and before, you will produce an error message that says:
1824 @smallexample
1825 Symbol's function definition is void:@: fill-column
1826 @end smallexample
1828 @noindent
1829 (The message will go away away as soon as you move the cursor or type
1830 another key.)
1832 @node Void Variable,  , Void Function, Variables
1833 @comment  node-name,  next,  previous,  up
1834 @subsection Error Message for a Symbol Without a Value
1835 @cindex Symbol without value error
1836 @cindex Error for symbol without value
1838 If you attempt to evaluate a symbol that does not have a value bound to
1839 it, you will receive an error message.  You can see this by
1840 experimenting with our 2 plus 2 addition.  In the following expression,
1841 put your cursor right after the @code{+}, before the first number 2,
1842 type @kbd{C-x C-e}:
1844 @smallexample
1845 (+ 2 2)
1846 @end smallexample
1848 @need 1500
1849 @noindent
1850 In GNU Emacs 21, you will create a @file{*Backtrace*} buffer that
1851 says:
1853 @smallexample
1854 @group
1855 ---------- Buffer: *Backtrace* ----------
1856 Debugger entered--Lisp error: (void-variable +)
1857   eval(+)
1858   eval-last-sexp-1(nil)
1859   eval-last-sexp(nil)
1860   call-interactively(eval-last-sexp)
1861 ---------- Buffer: *Backtrace* ----------
1862 @end group
1863 @end smallexample
1865 @noindent
1866 (As with the other times we entered the debugger, you can quit by
1867 typing @kbd{q} in the @file{*Backtrace*} buffer.)
1869 This backtrace is different from the very first error message we saw,
1870 which said, @samp{Debugger entered--Lisp error: (void-function this)}.
1871 In this case, the function does not have a value as a variable; while
1872 in the other error message, the function (the word `this') did not
1873 have a definition.
1875 In this experiment with the @code{+}, what we did was cause the Lisp
1876 interpreter to evaluate the @code{+} and look for the value of the
1877 variable instead of the function definition.  We did this by placing the
1878 cursor right after the symbol rather than after the parenthesis of the
1879 enclosing list as we did before.  As a consequence, the Lisp interpreter
1880 evaluated the preceding s-expression, which in this case was the
1881 @code{+} by itself.
1883 Since @code{+} does not have a value bound to it, just the function
1884 definition, the error message reported that the symbol's value as a
1885 variable was void.
1887 @need 800
1888 In GNU Emacs version 20 and before, your error message will say:
1890 @example
1891 Symbol's value as variable is void:@: +
1892 @end example
1894 @noindent
1895 The meaning is the same as in GNU Emacs 21.
1897 @node Arguments, set & setq, Variables, List Processing
1898 @comment  node-name,  next,  previous,  up
1899 @section Arguments
1900 @cindex Arguments
1901 @cindex Passing information to functions
1903 To see how information is passed to functions, let's look again at
1904 our old standby, the addition of two plus two.  In Lisp, this is written
1905 as follows:
1907 @smallexample
1908 (+ 2 2)
1909 @end smallexample
1911 If you evaluate this expression, the number 4 will appear in your echo
1912 area.  What the Lisp interpreter does is add the numbers that follow
1913 the @code{+}.
1915 @cindex @samp{argument} defined
1916 The numbers added by @code{+} are called the @dfn{arguments} of the
1917 function @code{+}.  These numbers are the information that is given to
1918 or @dfn{passed} to the function.
1920 The word `argument' comes from the way it is used in mathematics and
1921 does not refer to a disputation between two people; instead it refers to
1922 the information presented to the function, in this case, to the
1923 @code{+}.  In Lisp, the arguments to a function are the atoms or lists
1924 that follow the function.  The values returned by the evaluation of
1925 these atoms or lists are passed to the function.  Different functions
1926 require different numbers of arguments; some functions require none at
1927 all.@footnote{It is curious to track the path by which the word `argument'
1928 came to have two different meanings, one in mathematics and the other in
1929 everyday English.  According to the @cite{Oxford English Dictionary},
1930 the word derives from the Latin for @samp{to make clear, prove}; thus it
1931 came to mean, by one thread of derivation, `the evidence offered as
1932 proof', which is to say, `the information offered', which led to its
1933 meaning in Lisp.  But in the other thread of derivation, it came to mean
1934 `to assert in a manner against which others may make counter
1935 assertions', which led to the meaning of the word as a disputation.
1936 (Note here that the English word has two different definitions attached
1937 to it at the same time.  By contrast, in Emacs Lisp, a symbol cannot
1938 have two different function definitions at the same time.)}
1940 @menu
1941 * Data types::                  Types of data passed to a function.
1942 * Args as Variable or List::    An argument can be the value
1943                                   of a variable or list.
1944 * Variable Number of Arguments::  Some functions may take a
1945                                   variable number of arguments.
1946 * Wrong Type of Argument::      Passing an argument of the wrong type
1947                                   to a function.
1948 * message::                     A useful function for sending messages.
1949 @end menu
1951 @node Data types, Args as Variable or List, Arguments, Arguments
1952 @comment  node-name,  next,  previous,  up
1953 @subsection Arguments' Data Types
1954 @cindex Data types
1955 @cindex Types of data
1956 @cindex Arguments' data types
1958 The type of data that should be passed to a function depends on what
1959 kind of information it uses.  The arguments to a function such as
1960 @code{+} must have values that are numbers, since @code{+} adds numbers.
1961 Other functions use different kinds of data for their arguments.
1963 @need 1250
1964 @findex concat
1965 For example, the @code{concat} function links together or unites two or
1966 more strings of text to produce a string.  The arguments are strings.
1967 Concatenating the two character strings @code{abc}, @code{def} produces
1968 the single string @code{abcdef}.  This can be seen by evaluating the
1969 following:
1971 @smallexample
1972 (concat "abc" "def")
1973 @end smallexample
1975 @noindent
1976 The value produced by evaluating this expression is @code{"abcdef"}.
1978 A function such as @code{substring} uses both a string and numbers as
1979 arguments.  The function returns a part of the string, a substring of
1980 the first argument.  This function takes three arguments.  Its first
1981 argument is the string of characters, the second and third arguments are
1982 numbers that indicate the beginning and end of the substring.  The
1983 numbers are a count of the number of characters (including spaces and
1984 punctuations) from the beginning of the string.
1986 @need 800
1987 For example, if you evaluate the following:
1989 @smallexample
1990 (substring "The quick brown fox jumped." 16 19)
1991 @end smallexample
1993 @noindent
1994 you will see @code{"fox"} appear in the echo area.  The arguments are the
1995 string and the two numbers.
1997 Note that the string passed to @code{substring} is a single atom even
1998 though it is made up of several words separated by spaces.  Lisp counts
1999 everything between the two quotation marks as part of the string,
2000 including the spaces.  You can think of the @code{substring} function as
2001 a kind of `atom smasher' since it takes an otherwise indivisible atom
2002 and extracts a part.  However, @code{substring} is only able to extract
2003 a substring from an argument that is a string, not from another type of
2004 atom such as a number or symbol.
2006 @node Args as Variable or List, Variable Number of Arguments, Data types, Arguments
2007 @comment  node-name,  next,  previous,  up
2008 @subsection An Argument as the Value of a Variable or List
2010 An argument can be a symbol that returns a value when it is evaluated.
2011 For example, when the symbol @code{fill-column} by itself is evaluated,
2012 it returns a number.  This number can be used in an addition.
2014 @need 1250
2015 Position the cursor after the following expression and type @kbd{C-x
2016 C-e}:
2018 @smallexample
2019 (+ 2 fill-column)
2020 @end smallexample
2022 @noindent
2023 The value will be a number two more than what you get by evaluating
2024 @code{fill-column} alone.  For me, this is 74, because the value of
2025 @code{fill-column} is 72.
2027 As we have just seen, an argument can be a symbol that returns a value
2028 when evaluated.  In addition, an argument can be a list that returns a
2029 value when it is evaluated.  For example, in the following expression,
2030 the arguments to the function @code{concat} are the strings
2031 @w{@code{"The "}} and @w{@code{" red foxes."}} and the list
2032 @code{(number-to-string (+ 2 fill-column))}.
2034 @c For Emacs 21, need number-to-string
2035 @smallexample
2036 (concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
2037 @end smallexample
2039 @noindent
2040 If you evaluate this expression---and if, as with my Emacs,
2041 @code{fill-column} evaluates to 72---@code{"The 74 red foxes."} will
2042 appear in the echo area.  (Note that you must put spaces after the
2043 word @samp{The} and before the word @samp{red} so they will appear in
2044 the final string.  The function @code{number-to-string} converts the
2045 integer that the addition function returns to a string.
2046 @code{number-to-string} is also known as @code{int-to-string}.)
2048 @node Variable Number of Arguments, Wrong Type of Argument, Args as Variable or List, Arguments
2049 @comment  node-name,  next,  previous,  up
2050 @subsection Variable Number of Arguments
2051 @cindex Variable number of arguments
2052 @cindex Arguments, variable number of
2054 Some functions, such as @code{concat}, @code{+} or @code{*}, take any
2055 number of arguments.  (The @code{*} is the symbol for multiplication.)
2056 This can be seen by evaluating each of the following expressions in
2057 the usual way.  What you will see in the echo area is printed in this
2058 text after @samp{@result{}}, which you may read as `evaluates to'.
2060 @need 1250
2061 In the first set, the functions have no arguments:
2063 @smallexample
2064 @group
2065 (+)       @result{} 0
2067 (*)       @result{} 1
2068 @end group
2069 @end smallexample
2071 @need 1250
2072 In this set, the functions have one argument each:
2074 @smallexample
2075 @group
2076 (+ 3)     @result{} 3
2078 (* 3)     @result{} 3
2079 @end group
2080 @end smallexample
2082 @need 1250
2083 In this set, the functions have three arguments each:
2085 @smallexample
2086 @group
2087 (+ 3 4 5) @result{} 12
2089 (* 3 4 5) @result{} 60
2090 @end group
2091 @end smallexample
2093 @node Wrong Type of Argument, message, Variable Number of Arguments, Arguments
2094 @comment  node-name,  next,  previous,  up
2095 @subsection Using the Wrong Type Object as an Argument
2096 @cindex Wrong type of argument
2097 @cindex Argument, wrong type of
2099 When a function is passed an argument of the wrong type, the Lisp
2100 interpreter produces an error message.  For example, the @code{+}
2101 function expects the values of its arguments to be numbers.  As an
2102 experiment we can pass it the quoted symbol @code{hello} instead of a
2103 number.  Position the cursor after the following expression and type
2104 @kbd{C-x C-e}:
2106 @smallexample
2107 (+ 2 'hello)
2108 @end smallexample
2110 @noindent
2111 When you do this you will generate an error message.  What has happened
2112 is that @code{+} has tried to add the 2 to the value returned by
2113 @code{'hello}, but the value returned by @code{'hello} is the symbol
2114 @code{hello}, not a number.  Only numbers can be added.  So @code{+}
2115 could not carry out its addition.
2117 @need 1250
2118 In GNU Emacs version 21, you will create and enter a
2119 @file{*Backtrace*} buffer that says:
2121 @noindent
2122 @smallexample
2123 @group
2124 ---------- Buffer: *Backtrace* ----------
2125 Debugger entered--Lisp error:
2126          (wrong-type-argument number-or-marker-p hello)
2127   +(2 hello)
2128   eval((+ 2 (quote hello)))
2129   eval-last-sexp-1(nil)
2130   eval-last-sexp(nil)
2131   call-interactively(eval-last-sexp)
2132 ---------- Buffer: *Backtrace* ----------
2133 @end group
2134 @end smallexample
2136 @need 1250
2137 As usual, the error message tries to be helpful and makes sense after you
2138 learn how to read it.
2140 The first part of the error message is straightforward; it says
2141 @samp{wrong type argument}.  Next comes the mysterious jargon word
2142 @w{@samp{number-or-marker-p}}.  This word is trying to tell you what
2143 kind of argument the @code{+} expected.
2145 The symbol @code{number-or-marker-p} says that the Lisp interpreter is
2146 trying to determine whether the information presented it (the value of
2147 the argument) is a number or a marker (a special object representing a
2148 buffer position).  What it does is test to see whether the @code{+} is
2149 being given numbers to add.  It also tests to see whether the
2150 argument is something called a marker, which is a specific feature of
2151 Emacs Lisp.  (In Emacs, locations in a buffer are recorded as markers.
2152 When the mark is set with the @kbd{C-@@} or @kbd{C-@key{SPC}} command,
2153 its position is kept as a marker.  The mark can be considered a
2154 number---the number of characters the location is from the beginning
2155 of the buffer.)  In Emacs Lisp, @code{+} can be used to add the
2156 numeric value of marker positions as numbers.
2158 The @samp{p} of @code{number-or-marker-p} is the embodiment of a
2159 practice started in the early days of Lisp programming.  The @samp{p}
2160 stands for `predicate'.  In the jargon used by the early Lisp
2161 researchers, a predicate refers to a function to determine whether some
2162 property is true or false.  So the @samp{p} tells us that
2163 @code{number-or-marker-p} is the name of a function that determines
2164 whether it is true or false that the argument supplied is a number or
2165 a marker.  Other Lisp symbols that end in @samp{p} include @code{zerop},
2166 a function that tests whether its argument has the value of zero, and
2167 @code{listp}, a function that tests whether its argument is a list.
2169 Finally, the last part of the error message is the symbol @code{hello}.
2170 This is the value of the argument that was passed to @code{+}.  If the
2171 addition had been passed the correct type of object, the value passed
2172 would have been a number, such as 37, rather than a symbol like
2173 @code{hello}.  But then you would not have got the error message.
2175 @need 1250
2176 In GNU Emacs version 20 and before, the echo area displays an error
2177 message that says:
2179 @smallexample
2180 Wrong type argument:@: number-or-marker-p, hello
2181 @end smallexample
2183 This says, in different words, the same as the top line of the
2184 @file{*Backtrace*} buffer.
2186 @node message,  , Wrong Type of Argument, Arguments
2187 @comment  node-name,  next,  previous,  up
2188 @subsection The @code{message} Function
2189 @findex message
2191 Like @code{+}, the @code{message} function takes a variable number of
2192 arguments.  It is used to send messages to the user and is so useful
2193 that we will describe it here.
2195 @need 1250
2196 A message is printed in the echo area.  For example, you can print a
2197 message in your echo area by evaluating the following list:
2199 @smallexample
2200 (message "This message appears in the echo area!")
2201 @end smallexample
2203 The whole string between double quotation marks is a single argument
2204 and is printed @i{in toto}.  (Note that in this example, the message
2205 itself will appear in the echo area within double quotes; that is
2206 because you see the value returned by the @code{message} function.  In
2207 most uses of @code{message} in programs that you write, the text will
2208 be printed in the echo area as a side-effect, without the quotes.
2209 @xref{multiply-by-seven in detail, , @code{multiply-by-seven} in
2210 detail}, for an example of this.)
2212 However, if there is a @samp{%s} in the quoted string of characters, the
2213 @code{message} function does not print the @samp{%s} as such, but looks
2214 to the argument that follows the string.  It evaluates the second
2215 argument and prints the value at the location in the string where the
2216 @samp{%s} is.
2218 @need 1250
2219 You can see this by positioning the cursor after the following
2220 expression and typing @kbd{C-x C-e}:
2222 @smallexample
2223 (message "The name of this buffer is: %s." (buffer-name))
2224 @end smallexample
2226 @noindent
2227 In Info, @code{"The name of this buffer is: *info*."} will appear in the
2228 echo area.  The function @code{buffer-name} returns the name of the
2229 buffer as a string, which the @code{message} function inserts in place
2230 of @code{%s}.
2232 To print a value as an integer, use @samp{%d} in the same way as
2233 @samp{%s}.  For example, to print a message in the echo area that
2234 states the value of the @code{fill-column}, evaluate the following:
2236 @smallexample
2237 (message "The value of fill-column is %d." fill-column)
2238 @end smallexample
2240 @noindent
2241 On my system, when I evaluate this list, @code{"The value of
2242 fill-column is 72."} appears in my echo area@footnote{Actually, you
2243 can use @code{%s} to print a number.  It is non-specific.  @code{%d}
2244 prints only the part of a number left of a decimal point, and not
2245 anything that is not a number.}.
2247 If there is more than one @samp{%s} in the quoted string, the value of
2248 the first argument following the quoted string is printed at the
2249 location of the first @samp{%s} and the value of the second argument is
2250 printed at the location of the second @samp{%s}, and so on.
2252 @need 1250
2253 For example, if you evaluate the following,
2255 @smallexample
2256 @group
2257 (message "There are %d %s in the office!"
2258          (- fill-column 14) "pink elephants")
2259 @end group
2260 @end smallexample
2262 @noindent
2263 a rather whimsical message will appear in your echo area.  On my system
2264 it says, @code{"There are 58 pink elephants in the office!"}.
2266 The expression @code{(- fill-column 14)} is evaluated and the resulting
2267 number is inserted in place of the @samp{%d}; and the string in double
2268 quotes, @code{"pink elephants"}, is treated as a single argument and
2269 inserted in place of the @samp{%s}.  (That is to say, a string between
2270 double quotes evaluates to itself, like a number.)
2272 Finally, here is a somewhat complex example that not only illustrates
2273 the computation of a number, but also shows how you can use an
2274 expression within an expression to generate the text that is substituted
2275 for @samp{%s}:
2277 @smallexample
2278 @group
2279 (message "He saw %d %s"
2280          (- fill-column 32)
2281          (concat "red "
2282                  (substring
2283                   "The quick brown foxes jumped." 16 21)
2284                  " leaping."))
2285 @end group
2286 @end smallexample
2288 In this example, @code{message} has three arguments: the string,
2289 @code{"He saw %d %s"}, the expression, @code{(- fill-column 32)}, and
2290 the expression beginning with the function @code{concat}.  The value
2291 resulting from the evaluation of @code{(- fill-column 32)} is inserted
2292 in place of the @samp{%d}; and the value returned by the expression
2293 beginning with @code{concat} is inserted in place of the @samp{%s}.
2295 When I evaluate the expression, the message @code{"He saw 38 red
2296 foxes leaping."} appears in my echo area.
2298 @node set & setq, Summary, Arguments, List Processing
2299 @comment  node-name,  next,  previous,  up
2300 @section Setting the Value of a Variable
2301 @cindex Variable, setting value
2302 @cindex Setting value of variable
2304 @cindex @samp{bind} defined
2305 There are several ways by which a variable can be given a value.  One of
2306 the ways is to use either the function @code{set} or the function
2307 @code{setq}.  Another way is to use @code{let} (@pxref{let}).  (The
2308 jargon for this process is to @dfn{bind} a variable to a value.)
2310 The following sections not only describe how @code{set} and @code{setq}
2311 work but also illustrate how arguments are passed.
2313 @menu
2314 * Using set::                   Setting values.
2315 * Using setq::                  Setting a quoted value.
2316 * Counting::                    Using @code{setq} to count.
2317 @end menu
2319 @node Using set, Using setq, set & setq, set & setq
2320 @comment  node-name,  next,  previous,  up
2321 @subsection Using @code{set}
2322 @findex set
2324 To set the value of the symbol @code{flowers} to the list @code{'(rose
2325 violet daisy buttercup)}, evaluate the following expression by
2326 positioning the cursor after the expression and typing @kbd{C-x C-e}.
2328 @smallexample
2329 (set 'flowers '(rose violet daisy buttercup))
2330 @end smallexample
2332 @noindent
2333 The list @code{(rose violet daisy buttercup)} will appear in the echo
2334 area.  This is what is @emph{returned} by the @code{set} function.  As a
2335 side effect, the symbol @code{flowers} is bound to the list ; that is,
2336 the symbol @code{flowers}, which can be viewed as a variable, is given
2337 the list as its value.  (This process, by the way, illustrates how a
2338 side effect to the Lisp interpreter, setting the value, can be the
2339 primary effect that we humans are interested in.  This is because every
2340 Lisp function must return a value if it does not get an error, but it
2341 will only have a side effect if it is designed to have one.)
2343 After evaluating the @code{set} expression, you can evaluate the symbol
2344 @code{flowers} and it will return the value you just set.  Here is the
2345 symbol.  Place your cursor after it and type @kbd{C-x C-e}.
2347 @smallexample
2348 flowers
2349 @end smallexample
2351 @noindent
2352 When you evaluate @code{flowers}, the list
2353 @code{(rose violet daisy buttercup)} appears in the echo area.
2355 Incidentally, if you evaluate @code{'flowers}, the variable with a quote
2356 in front of it, what you will see in the echo area is the symbol itself,
2357 @code{flowers}.  Here is the quoted symbol, so you can try this:
2359 @smallexample
2360 'flowers
2361 @end smallexample
2363 Note also, that when you use @code{set}, you need to quote both
2364 arguments to @code{set}, unless you want them evaluated.  Since we do
2365 not want either argument evaluated, neither the variable
2366 @code{flowers} nor the list @code{(rose violet daisy buttercup)}, both
2367 are quoted.  (When you use @code{set} without quoting its first
2368 argument, the first argument is evaluated before anything else is
2369 done.  If you did this and @code{flowers} did not have a value
2370 already, you would get an error message that the @samp{Symbol's value
2371 as variable is void}; on the other hand, if @code{flowers} did return
2372 a value after it was evaluated, the @code{set} would attempt to set
2373 the value that was returned.  There are situations where this is the
2374 right thing for the function to do; but such situations are rare.)
2376 @node Using setq, Counting, Using set, set & setq
2377 @comment  node-name,  next,  previous,  up
2378 @subsection Using @code{setq}
2379 @findex setq
2381 As a practical matter, you almost always quote the first argument to
2382 @code{set}.  The combination of @code{set} and a quoted first argument
2383 is so common that it has its own name: the special form @code{setq}.
2384 This special form is just like @code{set} except that the first argument
2385 is quoted automatically, so you don't need to type the quote mark
2386 yourself.  Also, as an added convenience, @code{setq} permits you to set
2387 several different variables to different values, all in one expression.
2389 To set the value of the variable @code{carnivores} to the list
2390 @code{'(lion tiger leopard)} using @code{setq}, the following expression
2391 is used:
2393 @smallexample
2394 (setq carnivores '(lion tiger leopard))
2395 @end smallexample
2397 @noindent
2398 This is exactly the same as using @code{set} except the first argument
2399 is automatically quoted by @code{setq}.  (The @samp{q} in @code{setq}
2400 means @code{quote}.)
2402 @need 1250
2403 With @code{set}, the expression would look like this:
2405 @smallexample
2406 (set 'carnivores '(lion tiger leopard))
2407 @end smallexample
2409 Also, @code{setq} can be used to assign different values to
2410 different variables.  The first argument is bound to the value
2411 of the second argument, the third argument is bound to the value of the
2412 fourth argument, and so on.  For example, you could use the following to
2413 assign a list of trees to the symbol @code{trees} and a list of herbivores
2414 to the symbol @code{herbivores}:
2416 @smallexample
2417 @group
2418 (setq trees '(pine fir oak maple)
2419       herbivores '(gazelle antelope zebra))
2420 @end group
2421 @end smallexample
2423 @noindent
2424 (The expression could just as well have been on one line, but it might
2425 not have fit on a page; and humans find it easier to read nicely
2426 formatted lists.)
2428 Although I have been using the term `assign', there is another way of
2429 thinking about the workings of @code{set} and @code{setq}; and that is to
2430 say that @code{set} and @code{setq} make the symbol @emph{point} to the
2431 list.  This latter way of thinking is very common and in forthcoming
2432 chapters we shall come upon at least one symbol that has `pointer' as
2433 part of its name.  The name is chosen because the symbol has a value,
2434 specifically a list, attached to it; or, expressed another way,
2435 the symbol is set to ``point'' to the list.
2437 @node Counting,  , Using setq, set & setq
2438 @comment  node-name,  next,  previous,  up
2439 @subsection Counting
2440 @cindex Counting
2442 Here is an example that shows how to use @code{setq} in a counter.  You
2443 might use this to count how many times a part of your program repeats
2444 itself.  First set a variable to zero; then add one to the number each
2445 time the program repeats itself.  To do this, you need a variable that
2446 serves as a counter, and two expressions: an initial @code{setq}
2447 expression that sets the counter variable to zero; and a second
2448 @code{setq} expression that increments the counter each time it is
2449 evaluated.
2451 @smallexample
2452 @group
2453 (setq counter 0)                ; @r{Let's call this the initializer.}
2455 (setq counter (+ counter 1))    ; @r{This is the incrementer.}
2457 counter                         ; @r{This is the counter.}
2458 @end group
2459 @end smallexample
2461 @noindent
2462 (The text following the @samp{;} are comments.  @xref{Change a
2463 defun, , Change a Function Definition}.)
2465 If you evaluate the first of these expressions, the initializer,
2466 @code{(setq counter 0)}, and then evaluate the third expression,
2467 @code{counter}, the number @code{0} will appear in the echo area.  If
2468 you then evaluate the second expression, the incrementer, @code{(setq
2469 counter (+ counter 1))}, the counter will get the value 1.  So if you
2470 again evaluate @code{counter}, the number @code{1} will appear in the
2471 echo area.  Each time you evaluate the second expression, the value of
2472 the counter will be incremented.
2474 When you evaluate the incrementer, @code{(setq counter (+ counter 1))},
2475 the Lisp interpreter first evaluates the innermost list; this is the
2476 addition.  In order to evaluate this list, it must evaluate the variable
2477 @code{counter} and the number @code{1}.  When it evaluates the variable
2478 @code{counter}, it receives its current value.  It passes this value and
2479 the number @code{1} to the @code{+} which adds them together.  The sum
2480 is then returned as the value of the inner list and passed to the
2481 @code{setq} which sets the variable @code{counter} to this new value.
2482 Thus, the value of the variable, @code{counter}, is changed.
2484 @node Summary, Error Message Exercises, set & setq, List Processing
2485 @comment  node-name,  next,  previous,  up
2486 @section Summary
2488 Learning Lisp is like climbing a hill in which the first part is the
2489 steepest.  You have now climbed the most difficult part; what remains
2490 becomes easier as you progress onwards.
2492 @need 1000
2493 In summary,
2495 @itemize @bullet
2497 @item
2498 Lisp programs are made up of expressions, which are lists or single atoms.
2500 @item
2501 Lists are made up of zero or more atoms or inner lists, separated by whitespace and
2502 surrounded by parentheses.  A list can be empty.
2504 @item
2505 Atoms are multi-character symbols, like @code{forward-paragraph}, single
2506 character symbols like @code{+}, strings of characters between double
2507 quotation marks, or numbers.
2509 @item
2510 A number evaluates to itself.
2512 @item
2513 A string between double quotes also evaluates to itself.
2515 @item
2516 When you evaluate a symbol by itself, its value is returned.
2518 @item
2519 When you evaluate a list, the Lisp interpreter looks at the first symbol
2520 in the list and then at the function definition bound to that symbol.
2521 Then the instructions in the function definition are carried out.
2523 @item
2524 A single-quote, @code{'}, tells the Lisp interpreter that it should
2525 return the following expression as written, and not evaluate it as it
2526 would if the quote were not there.
2528 @item
2529 Arguments are the information passed to a function.  The arguments to a
2530 function are computed by evaluating the rest of the elements of the list
2531 of which the function is the first element.
2533 @item
2534 A function always returns a value when it is evaluated (unless it gets
2535 an error); in addition, it may also carry out some action called a
2536 ``side effect''.  In many cases, a function's primary purpose is to
2537 create a side effect.
2538 @end itemize
2540 @node Error Message Exercises,  , Summary, List Processing
2541 @comment  node-name,  next,  previous,  up
2542 @section Exercises
2544 A few simple exercises:
2546 @itemize @bullet
2547 @item
2548 Generate an error message by evaluating an appropriate symbol that is
2549 not within parentheses.
2551 @item
2552 Generate an error message by evaluating an appropriate symbol that is
2553 between parentheses.
2555 @item
2556 Create a counter that increments by two rather than one.
2558 @item
2559 Write an expression that prints a message in the echo area when
2560 evaluated.
2561 @end itemize
2563 @node Practicing Evaluation, Writing Defuns, List Processing, Top
2564 @comment  node-name,  next,  previous,  up
2565 @chapter Practicing Evaluation
2566 @cindex Practicing evaluation
2567 @cindex Evaluation practice
2569 Before learning how to write a function definition in Emacs Lisp, it is
2570 useful to spend a little time evaluating various expressions that have
2571 already been written.  These expressions will be lists with the
2572 functions as their first (and often only) element.  Since some of the
2573 functions associated with buffers are both simple and interesting, we
2574 will start with those.  In this section, we will evaluate a few of
2575 these.  In another section, we will study the code of several other
2576 buffer-related functions, to see how they were written.
2578 @menu
2579 * How to Evaluate::             Typing editing commands or @kbd{C-x C-e}
2580                                   causes evaluation.
2581 * Buffer Names::                Buffers and files are different.
2582 * Getting Buffers::             Getting a buffer itself, not merely its name.
2583 * Switching Buffers::           How to change to another buffer.
2584 * Buffer Size & Locations::     Where point is located and the size of
2585                                 the buffer.
2586 * Evaluation Exercise::
2587 @end menu
2589 @node How to Evaluate, Buffer Names, Practicing Evaluation, Practicing Evaluation
2590 @ifnottex
2591 @unnumberedsec How to Evaluate
2592 @end ifnottex
2594 @i{Whenever you give an editing command} to Emacs Lisp, such as the
2595 command to move the cursor or to scroll the screen, @i{you are evaluating
2596 an expression,} the first element of which is a function.  @i{This is
2597 how Emacs works.}
2599 @cindex @samp{interactive function} defined
2600 @cindex @samp{command} defined
2601 When you type keys, you cause the Lisp interpreter to evaluate an
2602 expression and that is how you get your results.  Even typing plain text
2603 involves evaluating an Emacs Lisp function, in this case, one that uses
2604 @code{self-insert-command}, which simply inserts the character you
2605 typed.  The functions you evaluate by typing keystrokes are called
2606 @dfn{interactive} functions, or @dfn{commands}; how you make a function
2607 interactive will be illustrated in the chapter on how to write function
2608 definitions.  @xref{Interactive, , Making a Function Interactive}.
2610 In addition to typing keyboard commands, we have seen a second way to
2611 evaluate an expression: by positioning the cursor after a list and
2612 typing @kbd{C-x C-e}.  This is what we will do in the rest of this
2613 section.  There are other ways to evaluate an expression as well; these
2614 will be described as we come to them.
2616 Besides being used for practicing evaluation, the functions shown in the
2617 next few sections are important in their own right.  A study of these
2618 functions makes clear the distinction between buffers and files, how to
2619 switch to a buffer, and how to determine a location within it.
2621 @node Buffer Names, Getting Buffers, How to Evaluate, Practicing Evaluation
2622 @comment  node-name,  next,  previous,  up
2623 @section Buffer Names
2624 @findex buffer-name
2625 @findex buffer-file-name
2627 The two functions, @code{buffer-name} and @code{buffer-file-name}, show
2628 the difference between a file and a buffer.  When you evaluate the
2629 following expression, @code{(buffer-name)}, the name of the buffer
2630 appears in the echo area.  When you evaluate @code{(buffer-file-name)},
2631 the name of the file to which the buffer refers appears in the echo
2632 area.  Usually, the name returned by @code{(buffer-name)} is the same as
2633 the name of the file to which it refers, and the name returned by
2634 @code{(buffer-file-name)} is the full path-name of the file.
2636 A file and a buffer are two different entities.  A file is information
2637 recorded permanently in the computer (unless you delete it).  A buffer,
2638 on the other hand, is information inside of Emacs that will vanish at
2639 the end of the editing session (or when you kill the buffer).  Usually,
2640 a buffer contains information that you have copied from a file; we say
2641 the buffer is @dfn{visiting} that file.  This copy is what you work on
2642 and modify.  Changes to the buffer do not change the file, until you
2643 save the buffer.  When you save the buffer, the buffer is copied to the file
2644 and is thus saved permanently.
2646 @need 1250
2647 If you are reading this in Info inside of GNU Emacs, you can evaluate
2648 each of the following expressions by positioning the cursor after it and
2649 typing @kbd{C-x C-e}.
2651 @smallexample
2652 @group
2653 (buffer-name)
2655 (buffer-file-name)
2656 @end group
2657 @end smallexample
2659 @noindent
2660 When I do this, @file{"introduction.texinfo"} is the value returned by
2661 evaluating @code{(buffer-name)}, and
2662 @file{"/gnu/work/intro/introduction.texinfo"} is the value returned by
2663 evaluating @code{(buffer-file-name)}.  The former is the name of the
2664 buffer and the latter is the name of the file.  (In the expressions, the
2665 parentheses tell the Lisp interpreter to treat @code{buffer-name} and
2666 @code{buffer-file-name} as functions; without the parentheses, the
2667 interpreter would attempt to evaluate the symbols as variables.
2668 @xref{Variables}.)
2670 In spite of the distinction between files and buffers, you will often
2671 find that people refer to a file when they mean a buffer and vice-versa.
2672 Indeed, most people say, ``I am editing a file,'' rather than saying,
2673 ``I am editing a buffer which I will soon save to a file.''  It is
2674 almost always clear from context what people mean.  When dealing with
2675 computer programs, however, it is important to keep the distinction in mind,
2676 since the computer is not as smart as a person.
2678 @cindex Buffer, history of word
2679 The word `buffer', by the way, comes from the meaning of the word as a
2680 cushion that deadens the force of a collision.  In early computers, a
2681 buffer cushioned the interaction between files and the computer's
2682 central processing unit.  The drums or tapes that held a file and the
2683 central processing unit were pieces of equipment that were very
2684 different from each other, working at their own speeds, in spurts.  The
2685 buffer made it possible for them to work together effectively.
2686 Eventually, the buffer grew from being an intermediary, a temporary
2687 holding place, to being the place where work is done.  This
2688 transformation is rather like that of a small seaport that grew into a
2689 great city: once it was merely the place where cargo was warehoused
2690 temporarily before being loaded onto ships; then it became a business
2691 and cultural center in its own right.
2693 Not all buffers are associated with files.  For example, when you start
2694 an Emacs session by typing the command @code{emacs} alone, without
2695 naming any files, Emacs will start with the @file{*scratch*} buffer on
2696 the screen.  This buffer is not visiting any file.  Similarly, a
2697 @file{*Help*} buffer is not associated with any file.
2699 @cindex @code{nil}, history of word
2700 If you switch to the @file{*scratch*} buffer, type @code{(buffer-name)},
2701 position the cursor after it, and type @kbd{C-x C-e} to evaluate the
2702 expression, the name @code{"*scratch*"} is returned and will appear in
2703 the echo area.  @code{"*scratch*"} is the name of the buffer.  However,
2704 if you type @code{(buffer-file-name)} in the @file{*scratch*} buffer and
2705 evaluate that, @code{nil} will appear in the echo area.  @code{nil} is
2706 from the Latin word for `nothing'; in this case, it means that the
2707 @file{*scratch*} buffer is not associated with any file.  (In Lisp,
2708 @code{nil} is also used to mean `false' and is a synonym for the empty
2709 list, @code{()}.)
2711 Incidentally, if you are in the @file{*scratch*} buffer and want the
2712 value returned by an expression to appear in the @file{*scratch*}
2713 buffer itself rather than in the echo area, type @kbd{C-u C-x C-e}
2714 instead of @kbd{C-x C-e}.  This causes the value returned to appear
2715 after the expression.  The buffer will look like this:
2717 @smallexample
2718 (buffer-name)"*scratch*"
2719 @end smallexample
2721 @noindent
2722 You cannot do this in Info since Info is read-only and it will not allow
2723 you to change the contents of the buffer.  But you can do this in any
2724 buffer you can edit; and when you write code or documentation (such as
2725 this book), this feature is very useful.
2727 @node Getting Buffers, Switching Buffers, Buffer Names, Practicing Evaluation
2728 @comment  node-name,  next,  previous,  up
2729 @section Getting Buffers
2730 @findex current-buffer
2731 @findex other-buffer
2732 @cindex Getting a buffer
2734 The @code{buffer-name} function returns the @emph{name} of the buffer;
2735 to get the buffer @emph{itself}, a different function is needed: the
2736 @code{current-buffer} function.  If you use this function in code, what
2737 you get is the buffer itself.
2739 A name and the object or entity to which the name refers are different
2740 from each other.  You are not your name.  You are a person to whom
2741 others refer by name.  If you ask to speak to George and someone hands you
2742 a card with the letters @samp{G}, @samp{e}, @samp{o}, @samp{r},
2743 @samp{g}, and @samp{e} written on it, you might be amused, but you would
2744 not be satisfied.  You do not want to speak to the name, but to the
2745 person to whom the name refers.  A buffer is similar: the name of the
2746 scratch buffer is @file{*scratch*}, but the name is not the buffer.  To
2747 get a buffer itself, you need to use a function such as
2748 @code{current-buffer}.
2750 However, there is a slight complication: if you evaluate
2751 @code{current-buffer} in an expression on its own, as we will do here,
2752 what you see is a printed representation of the name of the buffer
2753 without the contents of the buffer.  Emacs works this way for two
2754 reasons: the buffer may be thousands of lines long---too long to be
2755 conveniently displayed; and, another buffer may have the same contents
2756 but a different name, and it is important to distinguish between them.
2758 @need 800
2759 Here is an expression containing the function:
2761 @smallexample
2762 (current-buffer)
2763 @end smallexample
2765 @noindent
2766 If you evaluate the expression in the usual way, @file{#<buffer *info*>}
2767 appears in the echo area.  The special format indicates that the
2768 buffer itself is being returned, rather than just its name.
2770 Incidentally, while you can type a number or symbol into a program, you
2771 cannot do that with the printed representation of a buffer: the only way
2772 to get a buffer itself is with a function such as @code{current-buffer}.
2774 A related function is @code{other-buffer}.  This returns the most
2775 recently selected buffer other than the one you are in currently.  If
2776 you have recently switched back and forth from the @file{*scratch*}
2777 buffer, @code{other-buffer} will return that buffer.
2779 @need 800
2780 You can see this by evaluating the expression:
2782 @smallexample
2783 (other-buffer)
2784 @end smallexample
2786 @noindent
2787 You should see @file{#<buffer *scratch*>} appear in the echo area, or
2788 the name of whatever other buffer you switched back from most
2789 recently@footnote{Actually, by default, if the buffer from which you
2790 just switched is visible to you in another window, @code{other-buffer}
2791 will choose the most recent buffer that you cannot see; this is a
2792 subtlety that I often forget.}.
2794 @node Switching Buffers, Buffer Size & Locations, Getting Buffers, Practicing Evaluation
2795 @comment  node-name,  next,  previous,  up
2796 @section Switching Buffers
2797 @findex switch-to-buffer
2798 @findex set-buffer
2799 @cindex Switching to a buffer
2801 The @code{other-buffer} function actually provides a buffer when it is
2802 used as an argument to a function that requires one.  We can see this
2803 by using @code{other-buffer} and @code{switch-to-buffer} to switch to a
2804 different buffer.
2806 But first, a brief introduction to the @code{switch-to-buffer}
2807 function.  When you switched back and forth from Info to the
2808 @file{*scratch*} buffer to evaluate @code{(buffer-name)}, you most
2809 likely typed @kbd{C-x b} and then typed @file{*scratch*}@footnote{Or
2810 rather, to save typing, you probably typed just part of the name, such
2811 as @code{*sc}, and then pressed your @kbd{TAB} key to cause it to
2812 expand to the full name; and then typed your @kbd{RET} key.} when
2813 prompted in the minibuffer for the name of the buffer to which you
2814 wanted to switch.  The keystrokes, @kbd{C-x b}, cause the Lisp
2815 interpreter to evaluate the interactive function
2816 @code{switch-to-buffer}.  As we said before, this is how Emacs works:
2817 different keystrokes call or run different functions.  For example,
2818 @kbd{C-f} calls @code{forward-char}, @kbd{M-e} calls
2819 @code{forward-sentence}, and so on.
2821 By writing @code{switch-to-buffer} in an expression, and giving it a
2822 buffer to switch to, we can switch buffers just the way @kbd{C-x b}
2823 does.
2825 @need 1000
2826 Here is the Lisp expression:
2828 @smallexample
2829 (switch-to-buffer (other-buffer))
2830 @end smallexample
2832 @noindent
2833 The symbol @code{switch-to-buffer} is the first element of the list,
2834 so the Lisp interpreter will treat it as a function and carry out the
2835 instructions that are attached to it.  But before doing that, the
2836 interpreter will note that @code{other-buffer} is inside parentheses
2837 and work on that symbol first.  @code{other-buffer} is the first (and
2838 in this case, the only) element of this list, so the Lisp interpreter
2839 calls or runs the function.  It returns another buffer.  Next, the
2840 interpreter runs @code{switch-to-buffer}, passing to it, as an
2841 argument, the other buffer, which is what Emacs will switch to.  If
2842 you are reading this in Info, try this now.  Evaluate the expression.
2843 (To get back, type @kbd{C-x b @key{RET}}.)@footnote{Remember, this
2844 expression will move you to your most recent other buffer that you
2845 cannot see.  If you really want to go to your most recently selected
2846 buffer, even if you can still see it, you need to evaluate the
2847 following more complex expression:
2849 @smallexample
2850 (switch-to-buffer (other-buffer (current-buffer) t))
2851 @end smallexample
2853 @c noindent
2854 In this case, the first argument to @code{other-buffer} tells it which
2855 buffer to skip---the current one---and the second argument tells
2856 @code{other-buffer} it is OK to switch to a visible buffer.
2857 In regular use, @code{switch-to-buffer} takes you to an invisible
2858 window since you would most likely use @kbd{C-x o} (@code{other-window})
2859 to go to another visible buffer.}
2861 In the programming examples in later sections of this document, you will
2862 see the function @code{set-buffer} more often than
2863 @code{switch-to-buffer}.  This is because of a difference between
2864 computer programs and humans: humans have eyes and expect to see the
2865 buffer on which they are working on their computer terminals.  This is
2866 so obvious, it almost goes without saying.  However, programs do not
2867 have eyes.  When a computer program works on a buffer, that buffer does
2868 not need to be visible on the screen.
2870 @code{switch-to-buffer} is designed for humans and does two different
2871 things: it switches the buffer to which Emacs' attention is directed; and
2872 it switches the buffer displayed in the window to the new buffer.
2873 @code{set-buffer}, on the other hand, does only one thing: it switches
2874 the attention of the computer program to a different buffer.  The buffer
2875 on the screen remains unchanged (of course, normally nothing happens
2876 there until the command finishes running).
2878 @cindex @samp{call} defined
2879 Also, we have just introduced another jargon term, the word @dfn{call}.
2880 When you evaluate a list in which the first symbol is a function, you
2881 are calling that function.  The use of the term comes from the notion of
2882 the function as an entity that can do something for you if you `call'
2883 it---just as a plumber is an entity who can fix a leak if you call him
2884 or her.
2886 @node Buffer Size & Locations, Evaluation Exercise, Switching Buffers, Practicing Evaluation
2887 @comment  node-name,  next,  previous,  up
2888 @section Buffer Size and the Location of Point
2889 @cindex Size of buffer
2890 @cindex Buffer size
2891 @cindex Point location
2892 @cindex Location of point
2894 Finally, let's look at several rather simple functions,
2895 @code{buffer-size}, @code{point}, @code{point-min}, and
2896 @code{point-max}.  These give information about the size of a buffer and
2897 the location of point within it.
2899 The function @code{buffer-size} tells you the size of the current
2900 buffer; that is, the function returns a count of the number of
2901 characters in the buffer.
2903 @smallexample
2904 (buffer-size)
2905 @end smallexample
2907 @noindent
2908 You can evaluate this in the usual way, by positioning the
2909 cursor after the expression and typing @kbd{C-x C-e}.
2911 @cindex @samp{point} defined
2912 In Emacs, the current  position of the cursor is called @dfn{point}.
2913 The expression @code{(point)} returns a number that tells you where the
2914 cursor is located as a count of the number of characters from the
2915 beginning of the buffer up to point.
2917 @need 1250
2918 You can see the character count for point in this buffer by evaluating
2919 the following expression in the usual way:
2921 @smallexample
2922 (point)
2923 @end smallexample
2925 @noindent
2926 As I write this, the value of @code{point} is 65724.  The @code{point}
2927 function is frequently used in some of the examples later in this
2928 book.
2930 @need 1250
2931 The value of point depends, of course, on its location within the
2932 buffer.  If you evaluate point in this spot, the number will be larger:
2934 @smallexample
2935 (point)
2936 @end smallexample
2938 @noindent
2939 For me, the value of point in this location is 66043, which means that
2940 there are 319 characters (including spaces) between the two expressions.
2942 @cindex @samp{narrowing} defined
2943 The function @code{point-min} is somewhat similar to @code{point}, but
2944 it returns the value of the minimum permissible value of point in the
2945 current buffer.  This is the number 1 unless @dfn{narrowing} is in
2946 effect.  (Narrowing is a mechanism whereby you can restrict yourself,
2947 or a program, to operations on just a part of a buffer.
2948 @xref{Narrowing & Widening, , Narrowing and Widening}.)  Likewise, the
2949 function @code{point-max} returns the value of the maximum permissible
2950 value of point in the current buffer.
2952 @node Evaluation Exercise,  , Buffer Size & Locations, Practicing Evaluation
2953 @section Exercise
2955 Find a file with which you are working and move towards its middle.
2956 Find its buffer name, file name, length, and your position in the file.
2958 @node Writing Defuns, Buffer Walk Through, Practicing Evaluation, Top
2959 @comment  node-name,  next,  previous,  up
2960 @chapter How To Write Function Definitions
2961 @cindex Definition writing
2962 @cindex Function definition writing
2963 @cindex Writing a function definition
2965 When the Lisp interpreter evaluates a list, it looks to see whether the
2966 first symbol on the list has a function definition attached to it; or,
2967 put another way, whether the symbol points to a function definition.  If
2968 it does, the computer carries out the instructions in the definition.  A
2969 symbol that has a function definition is called, simply, a function
2970 (although, properly speaking, the definition is the function and the
2971 symbol refers to it.)
2973 @menu
2974 * Primitive Functions::
2975 * defun::                       The @code{defun} special form.
2976 * Install::                     Install a function definition.
2977 * Interactive::                 Making a function interactive.
2978 * Interactive Options::         Different options for @code{interactive}.
2979 * Permanent Installation::      Installing code permanently.
2980 * let::                         Creating and initializing local variables.
2981 * if::                          What if?
2982 * else::                        If--then--else expressions.
2983 * Truth & Falsehood::           What Lisp considers false and true.
2984 * save-excursion::              Keeping track of point, mark, and buffer.
2985 * Review::
2986 * defun Exercises::
2987 @end menu
2989 @node Primitive Functions, defun, Writing Defuns, Writing Defuns
2990 @ifnottex
2991 @unnumberedsec An Aside about Primitive Functions
2992 @end ifnottex
2993 @cindex Primitive functions
2994 @cindex Functions, primitive
2996 @cindex C language primitives
2997 @cindex Primitives written in C
2998 All functions are defined in terms of other functions, except for a few
2999 @dfn{primitive} functions that are written in the C programming
3000 language.  When you write functions' definitions, you will write them in
3001 Emacs Lisp and use other functions as your building blocks.  Some of the
3002 functions you will use will themselves be written in Emacs Lisp (perhaps
3003 by you) and some will be primitives written in C.  The primitive
3004 functions are used exactly like those written in Emacs Lisp and behave
3005 like them.  They are written in C so we can easily run GNU Emacs on any
3006 computer that has sufficient power and can run C.
3008 Let me re-emphasize this: when you write code in Emacs Lisp, you do not
3009 distinguish between the use of functions written in C and the use of
3010 functions written in Emacs Lisp.  The difference is irrelevant.  I
3011 mention the distinction only because it is interesting to know.  Indeed,
3012 unless you investigate, you won't know whether an already-written
3013 function is written in Emacs Lisp or C.
3015 @node defun, Install, Primitive Functions, Writing Defuns
3016 @comment  node-name,  next,  previous,  up
3017 @section The @code{defun} Special Form
3018 @findex defun
3019 @cindex Special form of @code{defun}
3021 @cindex @samp{function definition} defined
3022 In Lisp, a symbol such as @code{mark-whole-buffer} has code attached to
3023 it that tells the computer what to do when the function is called.
3024 This code is called the @dfn{function definition} and is created by
3025 evaluating a Lisp expression that starts with the symbol @code{defun}
3026 (which is an abbreviation for @emph{define function}).  Because
3027 @code{defun} does not evaluate its arguments in the usual way, it is
3028 called a @dfn{special form}.
3030 In subsequent sections, we will look at function definitions from the
3031 Emacs source code, such as @code{mark-whole-buffer}.  In this section,
3032 we will describe a simple function definition so you can see how it
3033 looks.  This function definition uses arithmetic because it makes for a
3034 simple example.  Some people dislike examples using arithmetic; however,
3035 if you are such a person, do not despair.  Hardly any of the code we
3036 will study in the remainder of this introduction involves arithmetic or
3037 mathematics.  The examples mostly involve text in one way or another.
3039 A function definition has up to five parts following the word
3040 @code{defun}:
3042 @enumerate
3043 @item
3044 The name of the symbol to which the function definition should be
3045 attached.
3047 @item
3048 A list of the arguments that will be passed to the function.  If no
3049 arguments will be passed to the function, this is an empty list,
3050 @code{()}.
3052 @item
3053 Documentation describing the function.  (Technically optional, but
3054 strongly recommended.)
3056 @item
3057 Optionally, an expression to make the function interactive so you can
3058 use it by typing @kbd{M-x} and then the name of the function; or by
3059 typing an appropriate key or keychord.
3061 @cindex @samp{body} defined
3062 @item
3063 The code that instructs the computer what to do: the @dfn{body} of the
3064 function definition.
3065 @end enumerate
3067 It is helpful to think of the five parts of a function definition as
3068 being organized in a template, with slots for each part:
3070 @smallexample
3071 @group
3072 (defun @var{function-name} (@var{arguments}@dots{})
3073   "@var{optional-documentation}@dots{}"
3074   (interactive @var{argument-passing-info})     ; @r{optional}
3075   @var{body}@dots{})
3076 @end group
3077 @end smallexample
3079 As an example, here is the code for a function that multiplies its
3080 argument by 7.  (This example is not interactive.  @xref{Interactive,
3081 , Making a Function Interactive}, for that information.)
3083 @smallexample
3084 @group
3085 (defun multiply-by-seven (number)
3086   "Multiply NUMBER by seven."
3087   (* 7 number))
3088 @end group
3089 @end smallexample
3091 This definition begins with a parenthesis and the symbol @code{defun},
3092 followed by the name of the function.
3094 @cindex @samp{argument list} defined
3095 The name of the function is followed by a list that contains the
3096 arguments that will be passed to the function.  This list is called
3097 the @dfn{argument list}.  In this example, the list has only one
3098 element, the symbol, @code{number}.  When the function is used, the
3099 symbol will be bound to the value that is used as the argument to the
3100 function.
3102 Instead of choosing the word @code{number} for the name of the argument,
3103 I could have picked any other name.  For example, I could have chosen
3104 the word @code{multiplicand}.  I picked the word `number' because it
3105 tells what kind of value is intended for this slot; but I could just as
3106 well have chosen the word `multiplicand' to indicate the role that the
3107 value placed in this slot will play in the workings of the function.  I
3108 could have called it @code{foogle}, but that would have been a bad
3109 choice because it would not tell humans what it means.  The choice of
3110 name is up to the programmer and should be chosen to make the meaning of
3111 the function clear.
3113 Indeed, you can choose any name you wish for a symbol in an argument
3114 list, even the name of a symbol used in some other function: the name
3115 you use in an argument list is private to that particular definition.
3116 In that definition, the name refers to a different entity than any use
3117 of the same name outside the function definition.  Suppose you have a
3118 nick-name `Shorty' in your family; when your family members refer to
3119 `Shorty', they mean you.  But outside your family, in a movie, for
3120 example, the name `Shorty' refers to someone else.  Because a name in an
3121 argument list is private to the function definition, you can change the
3122 value of such a symbol inside the body of a function without changing
3123 its value outside the function.  The effect is similar to that produced
3124 by a @code{let} expression.  (@xref{let, , @code{let}}.)
3126 @ignore
3127 Note also that we discuss the word `number' in two different ways: as a
3128 symbol that appears in the code, and as the name of something that will
3129 be replaced by a something else during the evaluation of the function.
3130 In the first case, @code{number} is a symbol, not a number; it happens
3131 that within the function, it is a variable who value is the number in
3132 question, but our primary interest in it is as a symbol.  On the other
3133 hand, when we are talking about the function, our interest is that we
3134 will substitute a number for the word @var{number}.  To keep this
3135 distinction clear, we use different typography for the two
3136 circumstances.  When we talk about this function, or about how it works,
3137 we refer to this number by writing @var{number}.  In the function
3138 itself, we refer to it by writing @code{number}.
3139 @end ignore
3141 The argument list is followed by the documentation string that
3142 describes the function.  This is what you see when you type
3143 @w{@kbd{C-h f}} and the name of a function.  Incidentally, when you
3144 write a documentation string like this, you should make the first line
3145 a complete sentence since some commands, such as @code{apropos}, print
3146 only the first line of a multi-line documentation string.  Also, you
3147 should not indent the second line of a documentation string, if you
3148 have one, because that looks odd when you use @kbd{C-h f}
3149 (@code{describe-function}).  The documentation string is optional, but
3150 it is so useful, it should be included in almost every function you
3151 write.
3153 @findex * @r{(multiplication)}
3154 The third line of the example consists of the body of the function
3155 definition.  (Most functions' definitions, of course, are longer than
3156 this.)  In this function, the body is the list, @code{(* 7 number)}, which
3157 says to multiply the value of @var{number} by 7.  (In Emacs Lisp,
3158 @code{*} is the function for multiplication, just as @code{+} is the
3159 function for addition.)
3161 When you use the @code{multiply-by-seven} function, the argument
3162 @code{number} evaluates to the actual number you want used.  Here is an
3163 example that shows how @code{multiply-by-seven} is used; but don't try
3164 to evaluate this yet!
3166 @smallexample
3167 (multiply-by-seven 3)
3168 @end smallexample
3170 @noindent
3171 The symbol @code{number}, specified in the function definition in the
3172 next section, is given or ``bound to'' the value 3 in the actual use of
3173 the function.  Note that although @code{number} was inside parentheses
3174 in the function definition, the argument passed to the
3175 @code{multiply-by-seven} function is not in parentheses.  The
3176 parentheses are written in the function definition so the computer can
3177 figure out where the argument list ends and the rest of the function
3178 definition begins.
3180 If you evaluate this example, you are likely to get an error message.
3181 (Go ahead, try it!)  This is because we have written the function
3182 definition, but not yet told the computer about the definition---we have
3183 not yet installed (or `loaded') the function definition in Emacs.
3184 Installing a function is the process that tells the Lisp interpreter the
3185 definition of the function.  Installation is described in the next
3186 section.
3188 @node Install, Interactive, defun, Writing Defuns
3189 @comment  node-name,  next,  previous,  up
3190 @section Install a Function Definition
3191 @cindex Install a Function Definition
3192 @cindex Definition installation
3193 @cindex Function definition installation
3195 If you are reading this inside of Info in Emacs, you can try out the
3196 @code{multiply-by-seven} function by first evaluating the function
3197 definition and then evaluating @code{(multiply-by-seven 3)}.  A copy of
3198 the function definition follows.  Place the cursor after the last
3199 parenthesis of the function definition and type @kbd{C-x C-e}.  When you
3200 do this, @code{multiply-by-seven} will appear in the echo area.  (What
3201 this means is that when a function definition is evaluated, the value it
3202 returns is the name of the defined function.)  At the same time, this
3203 action installs the function definition.
3205 @smallexample
3206 @group
3207 (defun multiply-by-seven (number)
3208   "Multiply NUMBER by seven."
3209   (* 7 number))
3210 @end group
3211 @end smallexample
3213 @noindent
3214 By evaluating this @code{defun}, you have just installed
3215 @code{multiply-by-seven} in Emacs.  The function is now just as much a
3216 part of Emacs as @code{forward-word} or any other editing function you
3217 use.  (@code{multiply-by-seven} will stay installed until you quit
3218 Emacs.  To reload code automatically whenever you start Emacs, see
3219 @ref{Permanent Installation, , Installing Code Permanently}.)
3222 @menu
3223 * Effect of installation::
3224 * Change a defun::              How to change a function definition.
3225 @end menu
3227 @node Effect of installation, Change a defun, Install, Install
3228 @ifnottex
3229 @unnumberedsubsec The effect of installation
3230 @end ifnottex
3233 You can see the effect of installing @code{multiply-by-seven} by
3234 evaluating the following sample.  Place the cursor after the following
3235 expression and type @kbd{C-x C-e}.  The number 21 will appear in the
3236 echo area.
3238 @smallexample
3239 (multiply-by-seven 3)
3240 @end smallexample
3242 If you wish, you can read the documentation for the function by typing
3243 @kbd{C-h f} (@code{describe-function}) and then the name of the
3244 function, @code{multiply-by-seven}.  When you do this, a
3245 @file{*Help*} window will appear on your screen that says:
3247 @smallexample
3248 @group
3249 multiply-by-seven:
3250 Multiply NUMBER by seven.
3251 @end group
3252 @end smallexample
3254 @noindent
3255 (To return to a single window on your screen, type @kbd{C-x 1}.)
3257 @node Change a defun,  , Effect of installation, Install
3258 @comment  node-name,  next,  previous,  up
3259 @subsection Change a Function Definition
3260 @cindex Changing a function definition
3261 @cindex Function definition, how to change
3262 @cindex Definition, how to change
3264 If you want to change the code in @code{multiply-by-seven}, just rewrite
3265 it.  To install the new version in place of the old one, evaluate the
3266 function definition again.  This is how you modify code in Emacs.  It is
3267 very simple.
3269 As an example, you can change the @code{multiply-by-seven} function to
3270 add the number to itself seven times instead of multiplying the number
3271 by seven.  It produces the same answer, but by a different path.  At
3272 the same time, we will add a comment to the code; a comment is text
3273 that the Lisp interpreter ignores, but that a human reader may find
3274 useful or enlightening.  The comment is that this is the ``second
3275 version''.
3277 @smallexample
3278 @group
3279 (defun multiply-by-seven (number)       ; @r{Second version.}
3280   "Multiply NUMBER by seven."
3281   (+ number number number number number number number))
3282 @end group
3283 @end smallexample
3285 @cindex Comments in Lisp code
3286 The comment follows a semicolon, @samp{;}.  In Lisp, everything on a
3287 line that follows a semicolon is a comment.  The end of the line is the
3288 end of the comment.  To stretch a comment over two or more lines, begin
3289 each line with a semicolon.
3291 @xref{Beginning a .emacs File, , Beginning a @file{.emacs}
3292 File}, and @ref{Comments, , Comments, elisp, The GNU Emacs Lisp
3293 Reference Manual}, for more about comments.
3295 You can install this version of the @code{multiply-by-seven} function by
3296 evaluating it in the same way you evaluated the first function: place
3297 the cursor after the last parenthesis and type @kbd{C-x C-e}.
3299 In summary, this is how you write code in Emacs Lisp: you write a
3300 function; install it; test it; and then make fixes or enhancements and
3301 install it again.
3303 @node Interactive, Interactive Options, Install, Writing Defuns
3304 @comment  node-name,  next,  previous,  up
3305 @section Make a Function Interactive
3306 @cindex Interactive functions
3307 @findex interactive
3309 You make a function interactive by placing a list that begins with
3310 the special form @code{interactive} immediately after the
3311 documentation.  A user can invoke an interactive function by typing
3312 @kbd{M-x} and then the name of the function; or by typing the keys to
3313 which it is bound, for example, by typing @kbd{C-n} for
3314 @code{next-line} or @kbd{C-x h} for @code{mark-whole-buffer}.
3316 Interestingly, when you call an interactive function interactively,
3317 the value returned is not automatically displayed in the echo area.
3318 This is because you often call an interactive function for its side
3319 effects, such as moving forward by a word or line, and not for the
3320 value returned.  If the returned value were displayed in the echo area
3321 each time you typed a key, it would be very distracting.
3323 @menu
3324 * Interactive multiply-by-seven::  An overview.
3325 * multiply-by-seven in detail::  The interactive version.
3326 @end menu
3328 @node Interactive multiply-by-seven, multiply-by-seven in detail, Interactive, Interactive
3329 @ifnottex
3330 @unnumberedsubsec An Interactive @code{multiply-by-seven}, An Overview
3331 @end ifnottex
3333 Both the use of the special form @code{interactive} and one way to
3334 display a value in the echo area can be illustrated by creating an
3335 interactive version of @code{multiply-by-seven}.
3337 @need 1250
3338 Here is the code:
3340 @smallexample
3341 @group
3342 (defun multiply-by-seven (number)       ; @r{Interactive version.}
3343   "Multiply NUMBER by seven."
3344   (interactive "p")
3345   (message "The result is %d" (* 7 number)))
3346 @end group
3347 @end smallexample
3349 @noindent
3350 You can install this code by placing your cursor after it and typing
3351 @kbd{C-x C-e}.  The name of the function will appear in your echo area.
3352 Then, you can use this code by typing @kbd{C-u} and a number and then
3353 typing @kbd{M-x multiply-by-seven} and pressing @key{RET}.  The phrase
3354 @samp{The result is @dots{}} followed by the product will appear in the
3355 echo area.
3357 Speaking more generally, you invoke a function like this in either of two
3358 ways:
3360 @enumerate
3361 @item
3362 By typing a prefix argument that contains the number to be passed, and
3363 then typing @kbd{M-x} and the name of the function, as with
3364 @kbd{C-u 3 M-x forward-sentence}; or,
3366 @item
3367 By typing whatever key or keychord the function is bound to, as with
3368 @kbd{C-u 3 M-e}.
3369 @end enumerate
3371 @noindent
3372 Both the examples just mentioned work identically to move point forward
3373 three sentences.  (Since @code{multiply-by-seven} is not bound to a key,
3374 it could not be used as an example of key binding.)
3376 (@xref{Keybindings, , Some Keybindings}, to learn how to bind a command
3377 to a key.)
3379 A prefix argument is passed to an interactive function by typing the
3380 @key{META} key followed by a number, for example, @kbd{M-3 M-e}, or by
3381 typing @kbd{C-u} and then a number, for example, @kbd{C-u 3 M-e} (if you
3382 type @kbd{C-u} without a number, it defaults to 4).
3384 @node multiply-by-seven in detail,  , Interactive multiply-by-seven, Interactive
3385 @comment  node-name,  next,  previous,  up
3386 @subsection An Interactive @code{multiply-by-seven}
3388 Let's look at the use of the special form @code{interactive} and then at
3389 the function @code{message} in the interactive version of
3390 @code{multiply-by-seven}.  You will recall that the function definition
3391 looks like this:
3393 @smallexample
3394 @group
3395 (defun multiply-by-seven (number)       ; @r{Interactive version.}
3396   "Multiply NUMBER by seven."
3397   (interactive "p")
3398   (message "The result is %d" (* 7 number)))
3399 @end group
3400 @end smallexample
3402 In this function, the expression, @code{(interactive "p")}, is a list of
3403 two elements.  The @code{"p"} tells Emacs to pass the prefix argument to
3404 the function and use its value for the argument of the function.
3406 @need 1000
3407 The argument will be a number.  This means that the symbol
3408 @code{number} will be bound to a number in the line:
3410 @smallexample
3411 (message "The result is %d" (* 7 number))
3412 @end smallexample
3414 @need 1250
3415 @noindent
3416 For example, if your prefix argument is 5, the Lisp interpreter will
3417 evaluate the line as if it were:
3419 @smallexample
3420 (message "The result is %d" (* 7 5))
3421 @end smallexample
3423 @noindent
3424 (If you are reading this in GNU Emacs, you can evaluate this expression
3425 yourself.)  First, the interpreter will evaluate the inner list, which
3426 is @code{(* 7 5)}.  This returns a value of 35.  Next, it
3427 will evaluate the outer list, passing the values of the second and
3428 subsequent elements of the list to the function @code{message}.
3430 As we have seen, @code{message} is an Emacs Lisp function especially
3431 designed for sending a one line message to a user.  (@xref{message, , The
3432 @code{message} function}.)
3433 In summary, the @code{message} function prints its first argument in the
3434 echo area as is, except for occurrences of @samp{%d}, @samp{%s}, or
3435 @samp{%c}.  When it sees one of these control sequences, the function
3436 looks to the second and subsequent arguments and prints the value of the
3437 argument in the location in the string where the control sequence is
3438 located.
3440 In the interactive @code{multiply-by-seven} function, the control string
3441 is @samp{%d}, which requires a number, and the value returned by
3442 evaluating @code{(* 7 5)} is the number 35.  Consequently, the number 35
3443 is printed in place of the @samp{%d} and the message is @samp{The result
3444 is 35}.
3446 (Note that when you call the function @code{multiply-by-seven}, the
3447 message is printed without quotes, but when you call @code{message}, the
3448 text is printed in double quotes.  This is because the value returned by
3449 @code{message} is what appears in the echo area when you evaluate an
3450 expression whose first element is @code{message}; but when embedded in a
3451 function, @code{message} prints the text as a side effect without
3452 quotes.)
3454 @node Interactive Options, Permanent Installation, Interactive, Writing Defuns
3455 @comment  node-name,  next,  previous,  up
3456 @section Different Options for @code{interactive}
3457 @cindex Options for @code{interactive}
3458 @cindex Interactive options
3460 In the example, @code{multiply-by-seven} used @code{"p"} as the
3461 argument to @code{interactive}.  This argument told Emacs to interpret
3462 your typing either @kbd{C-u} followed by a number or @key{META}
3463 followed by a number as a command to pass that number to the function
3464 as its argument.  Emacs has more than twenty characters predefined for
3465 use with @code{interactive}.  In almost every case, one of these
3466 options will enable you to pass the right information interactively to
3467 a function.  (@xref{Interactive Codes, , Code Characters for
3468 @code{interactive}, elisp, The GNU Emacs Lisp Reference Manual}.)
3470 @need 1250
3471 For example, the character @samp{r} causes Emacs to pass the beginning
3472 and end of the region (the current values of point and mark) to the
3473 function as two separate arguments.  It is used as follows:
3475 @smallexample
3476 (interactive "r")
3477 @end smallexample
3479 On the other hand, a @samp{B} tells Emacs to ask for the name of a
3480 buffer that will be passed to the function.  When it sees a @samp{B},
3481 Emacs will ask for the name by prompting the user in the minibuffer,
3482 using a string that follows the @samp{B}, as in @code{"BAppend to
3483 buffer:@: "}.  Not only will Emacs prompt for the name, but Emacs will
3484 complete the name if you type enough of it and press @key{TAB}.
3486 A function with two or more arguments can have information passed to
3487 each argument by adding parts to the string that follows
3488 @code{interactive}.  When you do this, the information is passed to
3489 each argument in the same order it is specified in the
3490 @code{interactive} list.  In the string, each part is separated from
3491 the next part by a @samp{\n}, which is a newline.  For example, you
3492 could follow @code{"BAppend to buffer:@: "} with a @samp{\n} and an
3493 @samp{r}.  This would cause Emacs to pass the values of point and mark
3494 to the function as well as prompt you for the buffer---three arguments
3495 in all.
3497 In this case, the function definition would look like the following,
3498 where @code{buffer}, @code{start}, and @code{end} are the symbols to
3499 which @code{interactive} binds the buffer and the current values of the
3500 beginning and ending of the region:
3502 @smallexample
3503 @group
3504 (defun @var{name-of-function} (buffer start end)
3505   "@var{documentation}@dots{}"
3506   (interactive "BAppend to buffer:@: \nr")
3507   @var{body-of-function}@dots{})
3508 @end group
3509 @end smallexample
3511 @noindent
3512 (The space after the colon in the prompt makes it look better when you
3513 are prompted.  The @code{append-to-buffer} function looks exactly like
3514 this.  @xref{append-to-buffer, , The Definition of
3515 @code{append-to-buffer}}.)
3517 If a function does not have arguments, then @code{interactive} does not
3518 require any.  Such a function contains the simple expression
3519 @code{(interactive)}.  The @code{mark-whole-buffer} function is like
3520 this.
3522 Alternatively, if the special letter-codes are not right for your
3523 application, you can pass your own arguments to @code{interactive} as
3524 a list.  @xref{Using Interactive, , Using @code{Interactive}, elisp, The
3525 GNU Emacs Lisp Reference Manual}, for more information about this advanced
3526 technique.
3528 @node Permanent Installation, let, Interactive Options, Writing Defuns
3529 @comment  node-name,  next,  previous,  up
3530 @section Install Code Permanently
3531 @cindex Install code permanently
3532 @cindex Permanent code installation
3533 @cindex Code installation
3535 When you install a function definition by evaluating it, it will stay
3536 installed until you quit Emacs.  The next time you start a new session
3537 of Emacs, the function will not be installed unless you evaluate the
3538 function definition again.
3540 At some point, you may want to have code installed automatically
3541 whenever you start a new session of Emacs.  There are several ways of
3542 doing this:
3544 @itemize @bullet
3545 @item
3546 If you have code that is just for yourself, you can put the code for the
3547 function definition in your @file{.emacs} initialization file.  When you
3548 start Emacs, your @file{.emacs} file is automatically evaluated and all
3549 the function definitions within it are installed.
3550 @xref{Emacs Initialization, , Your @file{.emacs} File}.
3552 @item
3553 Alternatively, you can put the function definitions that you want
3554 installed in one or more files of their own and use the @code{load}
3555 function to cause Emacs to evaluate and thereby install each of the
3556 functions in the files.
3557 @xref{Loading Files, , Loading Files}.
3559 @item
3560 On the other hand, if you have code that your whole site will use, it
3561 is usual to put it in a file called @file{site-init.el} that is loaded
3562 when Emacs is built.  This makes the code available to everyone who
3563 uses your machine.  (See the @file{INSTALL} file that is part of the
3564 Emacs distribution.)
3565 @end itemize
3567 Finally, if you have code that everyone who uses Emacs may want, you
3568 can post it on a computer network or send a copy to the Free Software
3569 Foundation.  (When you do this, please license the code and its
3570 documentation under a license that permits other people to run, copy,
3571 study, modify, and redistribute the code and which protects you from
3572 having your work taken from you.)  If you send a copy of your code to
3573 the Free Software Foundation, and properly protect yourself and
3574 others, it may be included in the next release of Emacs.  In large
3575 part, this is how Emacs has grown over the past years, by donations.
3577 @node let, if, Permanent Installation, Writing Defuns
3578 @comment  node-name,  next,  previous,  up
3579 @section @code{let}
3580 @findex let
3582 The @code{let} expression is a special form in Lisp that you will need
3583 to use in most function definitions.
3585 @code{let} is used to attach or bind a symbol to a value in such a way
3586 that the Lisp interpreter will not confuse the variable with a
3587 variable of the same name that is not part of the function.
3589 To understand why the @code{let} special form is necessary, consider
3590 the situation in which you own a home that you generally refer to as
3591 `the house', as in the sentence, ``The house needs painting.''  If you
3592 are visiting a friend and your host refers to `the house', he is
3593 likely to be referring to @emph{his} house, not yours, that is, to a
3594 different house.
3596 If your friend is referring to his house and you think he is referring
3597 to your house, you may be in for some confusion.  The same thing could
3598 happen in Lisp if a variable that is used inside of one function has
3599 the same name as a variable that is used inside of another function,
3600 and the two are not intended to refer to the same value.  The
3601 @code{let} special form prevents this kind of confusion.
3603 @menu
3604 * Prevent confusion::
3605 * Parts of let Expression::
3606 * Sample let Expression::
3607 * Uninitialized let Variables::
3608 @end menu
3610 @node Prevent confusion, Parts of let Expression, let, let
3611 @ifnottex
3612 @unnumberedsubsec @code{let} Prevents Confusion
3613 @end ifnottex
3615 @cindex @samp{local variable} defined
3616 The @code{let} special form prevents confusion.  @code{let} creates a
3617 name for a @dfn{local variable} that overshadows any use of the same
3618 name outside the @code{let} expression.  This is like understanding
3619 that whenever your host refers to `the house', he means his house, not
3620 yours.  (Symbols used in argument lists work the same way.
3621 @xref{defun, , The @code{defun} Special Form}.)
3623 Local variables created by a @code{let} expression retain their value
3624 @emph{only} within the @code{let} expression itself (and within
3625 expressions called within the @code{let} expression); the local
3626 variables have no effect outside the @code{let} expression.
3628 Another way to think about @code{let} is that it is like a @code{setq}
3629 that is temporary and local.  The values set by @code{let} are
3630 automatically undone when the @code{let} is finished.  The setting
3631 only affects expressions that are inside the bounds of the @code{let}
3632 expression.  In computer science jargon, we would say ``the binding of
3633 a symbol is visible only in functions called in the @code{let} form;
3634 in Emacs Lisp, scoping is dynamic, not lexical.''
3636 @code{let} can create more than one variable at once.  Also,
3637 @code{let} gives each variable it creates an initial value, either a
3638 value specified by you, or @code{nil}.  (In the jargon, this is called
3639 `binding the variable to the value'.)  After @code{let} has created
3640 and bound the variables, it executes the code in the body of the
3641 @code{let}, and returns the value of the last expression in the body,
3642 as the value of the whole @code{let} expression.  (`Execute' is a jargon
3643 term that means to evaluate a list; it comes from the use of the word
3644 meaning `to give practical effect to' (@cite{Oxford English
3645 Dictionary}).  Since you evaluate an expression to perform an action,
3646 `execute' has evolved as a synonym to `evaluate'.)
3648 @node Parts of let Expression, Sample let Expression, Prevent confusion, let
3649 @comment  node-name,  next,  previous,  up
3650 @subsection The Parts of a @code{let} Expression
3651 @cindex @code{let} expression, parts of
3652 @cindex Parts of @code{let} expression
3654 @cindex @samp{varlist} defined
3655 A @code{let} expression is a list of three parts.  The first part is
3656 the symbol @code{let}.  The second part is a list, called a
3657 @dfn{varlist}, each element of which is either a symbol by itself or a
3658 two-element list, the first element of which is a symbol.  The third
3659 part of the @code{let} expression is the body of the @code{let}.  The
3660 body usually consists of one or more lists.
3662 @need 800
3663 A template for a @code{let} expression looks like this:
3665 @smallexample
3666 (let @var{varlist} @var{body}@dots{})
3667 @end smallexample
3669 @noindent
3670 The symbols in the varlist are the variables that are given initial
3671 values by the @code{let} special form.  Symbols by themselves are given
3672 the initial value of @code{nil}; and each symbol that is the first
3673 element of a two-element list is bound to the value that is returned
3674 when the Lisp interpreter evaluates the second element.
3676 Thus, a varlist might look like this: @code{(thread (needles 3))}.  In
3677 this case, in a @code{let} expression, Emacs binds the symbol
3678 @code{thread} to an initial value of @code{nil}, and binds the symbol
3679 @code{needles} to an initial value of 3.
3681 When you write a @code{let} expression, what you do is put the
3682 appropriate expressions in the slots of the @code{let} expression
3683 template.
3685 If the varlist is composed of two-element lists, as is often the case,
3686 the template for the @code{let} expression looks like this:
3688 @smallexample
3689 @group
3690 (let ((@var{variable} @var{value})
3691       (@var{variable} @var{value})
3692       @dots{})
3693   @var{body}@dots{})
3694 @end group
3695 @end smallexample
3697 @node Sample let Expression, Uninitialized let Variables, Parts of let Expression, let
3698 @comment  node-name,  next,  previous,  up
3699 @subsection Sample @code{let} Expression
3700 @cindex Sample @code{let} expression
3701 @cindex @code{let} expression sample
3703 The following expression creates and gives initial values
3704 to the two variables @code{zebra} and @code{tiger}.  The body of the
3705 @code{let} expression is a list which calls the @code{message} function.
3707 @smallexample
3708 @group
3709 (let ((zebra 'stripes)
3710       (tiger 'fierce))
3711   (message "One kind of animal has %s and another is %s."
3712            zebra tiger))
3713 @end group
3714 @end smallexample
3716 Here, the varlist is @code{((zebra 'stripes) (tiger 'fierce))}.
3718 The two variables are @code{zebra} and @code{tiger}.  Each variable is
3719 the first element of a two-element list and each value is the second
3720 element of its two-element list.  In the varlist, Emacs binds the
3721 variable @code{zebra} to the value @code{stripes}, and binds the
3722 variable @code{tiger} to the value @code{fierce}.  In this example,
3723 both values are symbols preceded by a quote.  The values could just as
3724 well have been another list or a string.  The body of the @code{let}
3725 follows after the list holding the variables.  In this example, the body
3726 is a list that uses the @code{message} function to print a string in
3727 the echo area.
3729 @need 1500
3730 You may evaluate the example in the usual fashion, by placing the
3731 cursor after the last parenthesis and typing @kbd{C-x C-e}.  When you do
3732 this, the following will appear in the echo area:
3734 @smallexample
3735 "One kind of animal has stripes and another is fierce."
3736 @end smallexample
3738 As we have seen before, the @code{message} function prints its first
3739 argument, except for @samp{%s}.  In this example, the value of the variable
3740 @code{zebra} is printed at the location of the first @samp{%s} and the
3741 value of the variable @code{tiger} is printed at the location of the
3742 second @samp{%s}.
3744 @node Uninitialized let Variables,  , Sample let Expression, let
3745 @comment  node-name,  next,  previous,  up
3746 @subsection Uninitialized Variables in a @code{let} Statement
3747 @cindex Uninitialized @code{let} variables
3748 @cindex @code{let} variables uninitialized
3750 If you do not bind the variables in a @code{let} statement to specific
3751 initial values, they will automatically be bound to an initial value of
3752 @code{nil}, as in the following expression:
3754 @smallexample
3755 @group
3756 (let ((birch 3)
3757       pine
3758       fir
3759       (oak 'some))
3760   (message
3761    "Here are %d variables with %s, %s, and %s value."
3762    birch pine fir oak))
3763 @end group
3764 @end smallexample
3766 @noindent
3767 Here, the varlist is @code{((birch 3) pine fir (oak 'some))}.
3769 @need 1250
3770 If you evaluate this expression in the usual way, the following will
3771 appear in your echo area:
3773 @smallexample
3774 "Here are 3 variables with nil, nil, and some value."
3775 @end smallexample
3777 @noindent
3778 In this example, Emacs binds the symbol @code{birch} to the number 3,
3779 binds the symbols @code{pine} and @code{fir} to @code{nil}, and binds
3780 the symbol @code{oak} to the value @code{some}.
3782 Note that in the first part of the @code{let}, the variables @code{pine}
3783 and @code{fir} stand alone as atoms that are not surrounded by
3784 parentheses; this is because they are being bound to @code{nil}, the
3785 empty list.  But @code{oak} is bound to @code{some} and so is a part of
3786 the list @code{(oak 'some)}.  Similarly, @code{birch} is bound to the
3787 number 3 and so is in a list with that number.  (Since a number
3788 evaluates to itself, the number does not need to be quoted.  Also, the
3789 number is printed in the message using a @samp{%d} rather than a
3790 @samp{%s}.)  The four variables as a group are put into a list to
3791 delimit them from the body of the @code{let}.
3793 @node if, else, let, Writing Defuns
3794 @comment  node-name,  next,  previous,  up
3795 @section The @code{if} Special Form
3796 @findex if
3797 @cindex Conditional with @code{if}
3799 A third special form, in addition to @code{defun} and @code{let}, is the
3800 conditional @code{if}.  This form is used to instruct the computer to
3801 make decisions.  You can write function definitions without using
3802 @code{if}, but it is used often enough, and is important enough, to be
3803 included here.  It is used, for example, in the code for the
3804 function @code{beginning-of-buffer}.
3806 The basic idea behind an @code{if}, is that ``@emph{if} a test is true,
3807 @emph{then} an expression is evaluated.''  If the test is not true, the
3808 expression is not evaluated.  For example, you might make a decision
3809 such as, ``if it is warm and sunny, then go to the beach!''
3811 @menu
3812 * if in more detail::
3813 * type-of-animal in detail::    An example of an @code{if} expression.
3814 @end menu
3816 @node if in more detail, type-of-animal in detail, if, if
3817 @ifnottex
3818 @unnumberedsubsec @code{if} in more detail
3819 @end ifnottex
3821 @cindex @samp{if-part} defined
3822 @cindex @samp{then-part} defined
3823 An @code{if} expression written in Lisp does not use the word `then';
3824 the test and the action are the second and third elements of the list
3825 whose first element is @code{if}.  Nonetheless, the test part of an
3826 @code{if} expression is often called the @dfn{if-part} and the second
3827 argument is often called the @dfn{then-part}.
3829 Also, when an @code{if} expression is written, the true-or-false-test
3830 is usually written on the same line as the symbol @code{if}, but the
3831 action to carry out if the test is true, the ``then-part'', is written
3832 on the second and subsequent lines.  This makes the @code{if}
3833 expression easier to read.
3835 @smallexample
3836 @group
3837 (if @var{true-or-false-test}
3838     @var{action-to-carry-out-if-test-is-true})
3839 @end group
3840 @end smallexample
3842 @noindent
3843 The true-or-false-test will be an expression that
3844 is evaluated by the Lisp interpreter.
3846 Here is an example that you can evaluate in the usual manner.  The test
3847 is whether the number 5 is greater than the number 4.  Since it is, the
3848 message @samp{5 is greater than 4!} will be printed.
3850 @smallexample
3851 @group
3852 (if (> 5 4)                             ; @r{if-part}
3853     (message "5 is greater than 4!"))   ; @r{then-part}
3854 @end group
3855 @end smallexample
3857 @noindent
3858 (The function @code{>} tests whether its first argument is greater than
3859 its second argument and returns true if it is.)
3860 @findex > (greater than)
3862 Of course, in actual use, the test in an @code{if} expression will not
3863 be fixed for all time as it is by the expression @code{(> 5 4)}.
3864 Instead, at least one of the variables used in the test will be bound to
3865 a value that is not known ahead of time.  (If the value were known ahead
3866 of time, we would not need to run the test!)
3868 For example, the value may be bound to an argument of a function
3869 definition.  In the following function definition, the character of the
3870 animal is a value that is passed to the function.  If the value bound to
3871 @code{characteristic} is @code{fierce}, then the message, @samp{It's a
3872 tiger!} will be printed; otherwise, @code{nil} will be returned.
3874 @smallexample
3875 @group
3876 (defun type-of-animal (characteristic)
3877   "Print message in echo area depending on CHARACTERISTIC.
3878 If the CHARACTERISTIC is the symbol `fierce',
3879 then warn of a tiger."
3880   (if (equal characteristic 'fierce)
3881       (message "It's a tiger!")))
3882 @end group
3883 @end smallexample
3885 @need 1500
3886 @noindent
3887 If you are reading this inside of GNU Emacs, you can evaluate the
3888 function definition in the usual way to install it in Emacs, and then you
3889 can evaluate the following two expressions to see the results:
3891 @smallexample
3892 @group
3893 (type-of-animal 'fierce)
3895 (type-of-animal 'zebra)
3897 @end group
3898 @end smallexample
3900 @c Following sentences rewritten to prevent overfull hbox.
3901 @noindent
3902 When you evaluate @code{(type-of-animal 'fierce)}, you will see the
3903 following message printed in the echo area: @code{"It's a tiger!"}; and
3904 when you evaluate @code{(type-of-animal 'zebra)} you will see @code{nil}
3905 printed in the echo area.
3907 @node type-of-animal in detail,  , if in more detail, if
3908 @comment  node-name,  next,  previous,  up
3909 @subsection The @code{type-of-animal} Function in Detail
3911 Let's look at the @code{type-of-animal} function in detail.
3913 The function definition for @code{type-of-animal} was written by filling
3914 the slots of two templates, one for a function definition as a whole, and
3915 a second for an @code{if} expression.
3917 @need 1250
3918 The template for every function that is not interactive is:
3920 @smallexample
3921 @group
3922 (defun @var{name-of-function} (@var{argument-list})
3923   "@var{documentation}@dots{}"
3924   @var{body}@dots{})
3925 @end group
3926 @end smallexample
3928 @need 800
3929 The parts of the function that match this template look like this:
3931 @smallexample
3932 @group
3933 (defun type-of-animal (characteristic)
3934   "Print message in echo area depending on CHARACTERISTIC.
3935 If the CHARACTERISTIC is the symbol `fierce',
3936 then warn of a tiger."
3937   @var{body: the} @code{if} @var{expression})
3938 @end group
3939 @end smallexample
3941 The name of function is @code{type-of-animal}; it is passed the value
3942 of one argument.  The argument list is followed by a multi-line
3943 documentation string.  The documentation string is included in the
3944 example because it is a good habit to write documentation string for
3945 every function definition.  The body of the function definition
3946 consists of the @code{if} expression.
3948 @need 800
3949 The template for an @code{if} expression looks like this:
3951 @smallexample
3952 @group
3953 (if @var{true-or-false-test}
3954     @var{action-to-carry-out-if-the-test-returns-true})
3955 @end group
3956 @end smallexample
3958 @need 1250
3959 In the @code{type-of-animal} function, the code for the @code{if}
3960 looks like this:
3962 @smallexample
3963 @group
3964 (if (equal characteristic 'fierce)
3965     (message "It's a tiger!")))
3966 @end group
3967 @end smallexample
3969 @need 800
3970 Here, the true-or-false-test is the expression:
3972 @smallexample
3973 (equal characteristic 'fierce)
3974 @end smallexample
3976 @noindent
3977 In Lisp, @code{equal} is a function that determines whether its first
3978 argument is equal to its second argument.  The second argument is the
3979 quoted symbol @code{'fierce} and the first argument is the value of the
3980 symbol @code{characteristic}---in other words, the argument passed to
3981 this function.
3983 In the first exercise of @code{type-of-animal}, the argument
3984 @code{fierce} is passed to @code{type-of-animal}.  Since @code{fierce}
3985 is equal to @code{fierce}, the expression, @code{(equal characteristic
3986 'fierce)}, returns a value of true.  When this happens, the @code{if}
3987 evaluates the second argument or then-part of the @code{if}:
3988 @code{(message "It's tiger!")}.
3990 On the other hand, in the second exercise of @code{type-of-animal}, the
3991 argument @code{zebra} is passed to @code{type-of-animal}.  @code{zebra}
3992 is not equal to @code{fierce}, so the then-part is not evaluated and
3993 @code{nil} is returned by the @code{if} expression.
3995 @node else, Truth & Falsehood, if, Writing Defuns
3996 @comment  node-name,  next,  previous,  up
3997 @section If--then--else Expressions
3998 @cindex Else
4000 An @code{if} expression may have an optional third argument, called
4001 the @dfn{else-part}, for the case when the true-or-false-test returns
4002 false.  When this happens, the second argument or then-part of the
4003 overall @code{if} expression is @emph{not} evaluated, but the third or
4004 else-part @emph{is} evaluated.  You might think of this as the cloudy
4005 day alternative for the decision `if it is warm and sunny, then go to
4006 the beach, else read a book!''.
4008 The word ``else'' is not written in the Lisp code; the else-part of an
4009 @code{if} expression comes after the then-part.  In the written Lisp, the
4010 else-part is usually written to start on a line of its own and is
4011 indented less than the then-part:
4013 @smallexample
4014 @group
4015 (if @var{true-or-false-test}
4016     @var{action-to-carry-out-if-the-test-returns-true}
4017   @var{action-to-carry-out-if-the-test-returns-false})
4018 @end group
4019 @end smallexample
4021 For example, the following @code{if} expression prints the message @samp{4
4022 is not greater than 5!} when you evaluate it in the usual way:
4024 @smallexample
4025 @group
4026 (if (> 4 5)                             ; @r{if-part}
4027     (message "5 is greater than 4!")    ; @r{then-part}
4028   (message "4 is not greater than 5!")) ; @r{else-part}
4029 @end group
4030 @end smallexample
4032 @noindent
4033 Note that the different levels of indentation make it easy to
4034 distinguish the then-part from the else-part.  (GNU Emacs has several
4035 commands that automatically indent @code{if} expressions correctly.
4036 @xref{Typing Lists, , GNU Emacs Helps You Type Lists}.)
4038 We can extend the @code{type-of-animal} function to include an
4039 else-part by simply incorporating an additional part to the @code{if}
4040 expression.
4042 @need 1500
4043 You can see the consequences of doing this if you evaluate the following
4044 version of the @code{type-of-animal} function definition to install it
4045 and then evaluate the two subsequent expressions to pass different
4046 arguments to the function.
4048 @smallexample
4049 @group
4050 (defun type-of-animal (characteristic)  ; @r{Second version.}
4051   "Print message in echo area depending on CHARACTERISTIC.
4052 If the CHARACTERISTIC is the symbol `fierce',
4053 then warn of a tiger;
4054 else say it's not fierce."
4055   (if (equal characteristic 'fierce)
4056       (message "It's a tiger!")
4057     (message "It's not fierce!")))
4058 @end group
4059 @end smallexample
4060 @sp 1
4062 @smallexample
4063 @group
4064 (type-of-animal 'fierce)
4066 (type-of-animal 'zebra)
4068 @end group
4069 @end smallexample
4071 @c Following sentence rewritten to prevent overfull hbox.
4072 @noindent
4073 When you evaluate @code{(type-of-animal 'fierce)}, you will see the
4074 following message printed in the echo area: @code{"It's a tiger!"}; but
4075 when you evaluate @code{(type-of-animal 'zebra)}, you will see
4076 @code{"It's not fierce!"}.
4078 (Of course, if the @var{characteristic} were @code{ferocious}, the
4079 message @code{"It's not fierce!"} would be printed; and it would be
4080 misleading!  When you write code, you need to take into account the
4081 possibility that some such argument will be tested by the @code{if} and
4082 write your program accordingly.)
4084 @node Truth & Falsehood, save-excursion, else, Writing Defuns
4085 @comment  node-name,  next,  previous,  up
4086 @section Truth and Falsehood in Emacs Lisp
4087 @cindex Truth and falsehood in Emacs Lisp
4088 @cindex Falsehood and truth in Emacs Lisp
4089 @findex nil
4091 There is an important aspect to the truth test in an @code{if}
4092 expression.  So far, we have spoken of `true' and `false' as values of
4093 predicates as if they were new kinds of Emacs Lisp objects.  In fact,
4094 `false' is just our old friend @code{nil}.  Anything else---anything
4095 at all---is `true'.
4097 The expression that tests for truth is interpreted as @dfn{true}
4098 if the result of evaluating it is a value that is not @code{nil}.  In
4099 other words, the result of the test is considered true if the value
4100 returned is a number such as 47, a string such as @code{"hello"}, or a
4101 symbol (other than @code{nil}) such as @code{flowers}, or a list, or
4102 even a buffer!
4104 @menu
4105 * nil explained::               @code{nil} has two meanings.
4106 @end menu
4108 @node nil explained,  , Truth & Falsehood, Truth & Falsehood
4109 @ifnottex
4110 @unnumberedsubsec An explanation of @code{nil}
4111 @end ifnottex
4113 Before illustrating a test for truth, we need an explanation of @code{nil}.
4115 In Emacs Lisp, the symbol @code{nil} has two meanings.  First, it means the
4116 empty list.  Second, it means false and is the value returned when a
4117 true-or-false-test tests false.  @code{nil} can be written as an empty
4118 list, @code{()}, or as @code{nil}.  As far as the Lisp interpreter is
4119 concerned, @code{()} and @code{nil} are the same.  Humans, however, tend
4120 to use @code{nil} for false and @code{()} for the empty list.
4122 In Emacs Lisp, any value that is not @code{nil}---is not the empty
4123 list---is considered true.  This means that if an evaluation returns
4124 something that is not an empty list, an @code{if} expression will test
4125 true.  For example, if a number is put in the slot for the test, it
4126 will be evaluated and will return itself, since that is what numbers
4127 do when evaluated.  In this conditional, the @code{if} expression will
4128 test true.  The expression tests false only when @code{nil}, an empty
4129 list, is returned by evaluating the expression.
4131 You can see this by evaluating the two expressions in the following examples.
4133 In the first example, the number 4 is evaluated as the test in the
4134 @code{if} expression and returns itself; consequently, the then-part
4135 of the expression is evaluated and returned: @samp{true} appears in
4136 the echo area.  In the second example, the @code{nil} indicates false;
4137 consequently, the else-part of the expression is evaluated and
4138 returned: @samp{false} appears in the echo area.
4140 @smallexample
4141 @group
4142 (if 4
4143     'true
4144   'false)
4145 @end group
4147 @group
4148 (if nil
4149     'true
4150   'false)
4151 @end group
4152 @end smallexample
4154 @need 1250
4155 Incidentally, if some other useful value is not available for a test that
4156 returns true, then the Lisp interpreter will return the symbol @code{t}
4157 for true.  For example, the expression @code{(> 5 4)} returns @code{t}
4158 when evaluated, as you can see by evaluating it in the usual way:
4160 @smallexample
4161 (> 5 4)
4162 @end smallexample
4164 @need 1250
4165 @noindent
4166 On the other hand, this function returns @code{nil} if the test is false.
4168 @smallexample
4169 (> 4 5)
4170 @end smallexample
4172 @node save-excursion, Review, Truth & Falsehood, Writing Defuns
4173 @comment  node-name,  next,  previous,  up
4174 @section @code{save-excursion}
4175 @findex save-excursion
4176 @cindex Region, what it is
4177 @cindex Preserving point, mark, and buffer
4178 @cindex Point, mark, buffer preservation
4179 @findex point
4180 @findex mark
4182 The @code{save-excursion} function is the fourth and final special form
4183 that we will discuss in this chapter.
4185 In Emacs Lisp programs used for editing, the @code{save-excursion}
4186 function is very common.  It saves the location of point and mark,
4187 executes the body of the function, and then restores point and mark to
4188 their previous positions if their locations were changed.  Its primary
4189 purpose is to keep the user from being surprised and disturbed by
4190 unexpected movement of point or mark.
4192 @menu
4193 * Point and mark::              A review of various locations.
4194 * Template for save-excursion::
4195 @end menu
4197 @node Point and mark, Template for save-excursion, save-excursion, save-excursion
4198 @ifnottex
4199 @unnumberedsubsec Point and Mark
4200 @end ifnottex
4202 Before discussing @code{save-excursion}, however, it may be useful
4203 first to review what point and mark are in GNU Emacs.  @dfn{Point} is
4204 the current location of the cursor.  Wherever the cursor
4205 is, that is point.  More precisely, on terminals where the cursor
4206 appears to be on top of a character, point is immediately before the
4207 character.  In Emacs Lisp, point is an integer.  The first character in
4208 a buffer is number one, the second is number two, and so on.  The
4209 function @code{point} returns the current position of the cursor as a
4210 number.  Each buffer has its own value for point.
4212 The @dfn{mark} is another position in the buffer; its value can be set
4213 with a command such as @kbd{C-@key{SPC}} (@code{set-mark-command}).  If
4214 a mark has been set, you can use the command @kbd{C-x C-x}
4215 (@code{exchange-point-and-mark}) to cause the cursor to jump to the mark
4216 and set the mark to be the previous position of point.  In addition, if
4217 you set another mark, the position of the previous mark is saved in the
4218 mark ring.  Many mark positions can be saved this way.  You can jump the
4219 cursor to a saved mark by typing @kbd{C-u C-@key{SPC}} one or more
4220 times.
4222 The part of the buffer between point and mark is called @dfn{the
4223 region}.  Numerous commands work on the region, including
4224 @code{center-region}, @code{count-lines-region}, @code{kill-region}, and
4225 @code{print-region}.
4227 The @code{save-excursion} special form saves the locations of point and
4228 mark and restores those positions after the code within the body of the
4229 special form is evaluated by the Lisp interpreter.  Thus, if point were
4230 in the beginning of a piece of text and some code moved point to the end
4231 of the buffer, the @code{save-excursion} would put point back to where
4232 it was before, after the expressions in the body of the function were
4233 evaluated.
4235 In Emacs, a function frequently moves point as part of its internal
4236 workings even though a user would not expect this.  For example,
4237 @code{count-lines-region} moves point.  To prevent the user from being
4238 bothered by jumps that are both unexpected and (from the user's point of
4239 view) unnecessary, @code{save-excursion} is often used to keep point and
4240 mark in the location expected by the user.  The use of
4241 @code{save-excursion} is good housekeeping.
4243 To make sure the house stays clean, @code{save-excursion} restores the
4244 values of point and mark even if something goes wrong in the code inside
4245 of it (or, to be more precise and to use the proper jargon, ``in case of
4246 abnormal exit'').  This feature is very helpful.
4248 In addition to recording the values of point and mark,
4249 @code{save-excursion} keeps track of the current buffer, and restores
4250 it, too.  This means you can write code that will change the buffer and
4251 have @code{save-excursion} switch you back to the original buffer.  This
4252 is how @code{save-excursion} is used in @code{append-to-buffer}.
4253 (@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
4255 @node Template for save-excursion,  , Point and mark, save-excursion
4256 @comment  node-name,  next,  previous,  up
4257 @subsection Template for a @code{save-excursion} Expression
4259 @need 800
4260 The template for code using @code{save-excursion} is simple:
4262 @smallexample
4263 @group
4264 (save-excursion
4265   @var{body}@dots{})
4266 @end group
4267 @end smallexample
4269 @noindent
4270 The body of the function is one or more expressions that will be
4271 evaluated in sequence by the Lisp interpreter.  If there is more than
4272 one expression in the body, the value of the last one will be returned
4273 as the value of the @code{save-excursion} function.  The other
4274 expressions in the body are evaluated only for their side effects; and
4275 @code{save-excursion} itself is used only for its side effect (which
4276 is restoring the positions of point and mark).
4278 @need 1250
4279 In more detail, the template for a @code{save-excursion} expression
4280 looks like this:
4282 @smallexample
4283 @group
4284 (save-excursion
4285   @var{first-expression-in-body}
4286   @var{second-expression-in-body}
4287   @var{third-expression-in-body}
4288    @dots{}
4289   @var{last-expression-in-body})
4290 @end group
4291 @end smallexample
4293 @noindent
4294 An expression, of course, may be a symbol on its own or a list.
4296 In Emacs Lisp code, a @code{save-excursion} expression often occurs
4297 within the body of a @code{let} expression.  It looks like this:
4299 @smallexample
4300 @group
4301 (let @var{varlist}
4302   (save-excursion
4303     @var{body}@dots{}))
4304 @end group
4305 @end smallexample
4307 @node Review, defun Exercises, save-excursion, Writing Defuns
4308 @comment  node-name,  next,  previous,  up
4309 @section Review
4311 In the last few chapters we have introduced a fair number of functions
4312 and special forms.  Here they are described in brief, along with a few
4313 similar functions that have not been mentioned yet.
4315 @table @code
4316 @item eval-last-sexp
4317 Evaluate the last symbolic expression before the current location of
4318 point.  The value is printed in the echo area unless the function is
4319 invoked with an argument; in that case, the output is printed in the
4320 current buffer.  This command is normally bound to @kbd{C-x C-e}.
4322 @item defun
4323 Define function.  This special form has up to five parts: the name,
4324 a template for the arguments that will be passed to the function,
4325 documentation, an optional interactive declaration, and the body of the
4326 definition.
4328 @need 1250
4329 For example:
4331 @smallexample
4332 @group
4333 (defun back-to-indentation ()
4334   "Move point to first visible character on line."
4335   (interactive)
4336   (beginning-of-line 1)
4337   (skip-chars-forward " \t"))
4338 @end group
4339 @end smallexample
4341 @item interactive
4342 Declare to the interpreter that the function can be used
4343 interactively.  This special form may be followed by a string with one
4344 or more parts that pass the information to the arguments of the
4345 function, in sequence.  These parts may also tell the interpreter to
4346 prompt for information.  Parts of the string are separated by
4347 newlines, @samp{\n}.
4349 @need 1000
4350 Common code characters are:
4352 @table @code
4353 @item b
4354 The name of an existing buffer.
4356 @item f
4357 The name of an existing file.
4359 @item p
4360 The numeric prefix argument.  (Note that this `p' is lower case.)
4362 @item r
4363 Point and the mark, as two numeric arguments, smallest first.  This
4364 is the only code letter that specifies two successive arguments
4365 rather than one.
4366 @end table
4368 @xref{Interactive Codes, , Code Characters for @samp{interactive},
4369 elisp, The GNU Emacs Lisp Reference Manual}, for a complete list of
4370 code characters.
4372 @item let
4373 Declare that a list of variables is for use within the body of the
4374 @code{let} and give them an initial value, either @code{nil} or a
4375 specified value; then evaluate the rest of the expressions in the body
4376 of the @code{let} and return the value of the last one.  Inside the
4377 body of the @code{let}, the Lisp interpreter does not see the values of
4378 the variables of the same names that are bound outside of the
4379 @code{let}.
4381 @need 1250
4382 For example,
4384 @smallexample
4385 @group
4386 (let ((foo (buffer-name))
4387       (bar (buffer-size)))
4388   (message
4389    "This buffer is %s and has %d characters."
4390    foo bar))
4391 @end group
4392 @end smallexample
4394 @item save-excursion
4395 Record the values of point and mark and the current buffer before
4396 evaluating the body of this special form.  Restore the values of point
4397 and mark and buffer afterward.
4399 @need 1250
4400 For example,
4402 @smallexample
4403 @group
4404 (message "We are %d characters into this buffer."
4405          (- (point)
4406             (save-excursion
4407               (goto-char (point-min)) (point))))
4408 @end group
4409 @end smallexample
4411 @item if
4412 Evaluate the first argument to the function; if it is true, evaluate
4413 the second argument; else evaluate the third argument, if there is one.
4415 The @code{if} special form is called a @dfn{conditional}.  There are
4416 other conditionals in Emacs Lisp, but @code{if} is perhaps the most
4417 commonly used.
4419 @need 1250
4420 For example,
4422 @smallexample
4423 @group
4424 (if (string-equal
4425      (number-to-string 21)
4426      (substring (emacs-version) 10 12))
4427     (message "This is version 21 Emacs")
4428   (message "This is not version 21 Emacs"))
4429 @end group
4430 @end smallexample
4432 @item equal
4433 @itemx eq
4434 Test whether two objects are the same.  @code{equal} uses one meaning
4435 of the word `same' and @code{eq} uses another:  @code{equal} returns
4436 true if the two objects have a similar structure and contents, such as
4437 two copies of the same book.  On the other hand, @code{eq}, returns
4438 true if both arguments are actually the same object.
4439 @findex equal
4440 @findex eq
4442 @need 1250
4443 @item <
4444 @itemx >
4445 @itemx <=
4446 @itemx >=
4447 The @code{<} function tests whether its first argument is smaller than
4448 its second argument.  A corresponding function, @code{>}, tests whether
4449 the first argument is greater than the second.  Likewise, @code{<=}
4450 tests whether the first argument is less than or equal to the second and
4451 @code{>=} tests whether the first argument is greater than or equal to
4452 the second.  In all cases, both arguments must be numbers or markers
4453 (markers indicate positions in buffers).
4455 @item string<
4456 @itemx string-lessp
4457 @itemx string=
4458 @itemx string-equal
4459 The @code{string-lessp} function tests whether its first argument is
4460 smaller than the second argument.  A shorter, alternative name for the
4461 same function (a @code{defalias}) is @code{string<}.
4463 The arguments to @code{string-lessp} must be strings or symbols; the
4464 ordering is lexicographic, so case is significant.  The print names of
4465 symbols are used instead of the symbols themselves.
4467 @cindex @samp{empty string} defined
4468 An empty string, @samp{""}, a string with no characters in it, is
4469 smaller than any string of characters.
4471 @code{string-equal} provides the corresponding test for equality.  Its
4472 shorter, alternative name is @code{string=}.  There are no string test
4473 functions that correspond to @var{>}, @code{>=}, or @code{<=}.
4475 @item message
4476 Print a message in the echo area. The first argument is a string that
4477 can contain @samp{%s}, @samp{%d}, or @samp{%c} to print the value of
4478 arguments that follow the string.  The argument used by @samp{%s} must
4479 be a string or a symbol; the argument used by @samp{%d} must be a
4480 number.  The argument used by @samp{%c} must be an @sc{ascii} code
4481 number; it will be printed as the character with that @sc{ascii} code.
4483 @item setq
4484 @itemx set
4485 The @code{setq} function sets the value of its first argument to the
4486 value of the second argument.  The first argument is automatically
4487 quoted by @code{setq}.  It does the same for succeeding pairs of
4488 arguments.  Another function, @code{set}, takes only two arguments and
4489 evaluates both of them before setting the value returned by its first
4490 argument to the value returned by its second argument.
4492 @item buffer-name
4493 Without an argument, return the name of the buffer, as a string.
4495 @itemx buffer-file-name
4496 Without an argument, return the name of the file the buffer is
4497 visiting.
4499 @item current-buffer
4500 Return the buffer in which Emacs is active; it may not be
4501 the buffer that is visible on the screen.
4503 @item other-buffer
4504 Return the most recently selected buffer (other than the buffer passed
4505 to @code{other-buffer} as an argument and other than the current
4506 buffer).
4508 @item switch-to-buffer
4509 Select a buffer for Emacs to be active in and display it in the current
4510 window so users can look at it.  Usually bound to @kbd{C-x b}.
4512 @item set-buffer
4513 Switch Emacs' attention to a buffer on which programs will run.  Don't
4514 alter what the window is showing.
4516 @item buffer-size
4517 Return the number of characters in the current buffer.
4519 @item point
4520 Return the value of the current position of the cursor, as an
4521 integer counting the number of characters from the beginning of the
4522 buffer.
4524 @item point-min
4525 Return the minimum permissible value of point in
4526 the current buffer.  This is 1, unless narrowing is in effect.
4528 @item point-max
4529 Return the value of the maximum permissible value of point in the
4530 current buffer.  This is the end of the buffer, unless narrowing is in
4531 effect.
4532 @end table
4534 @need 1500
4535 @node defun Exercises,  , Review, Writing Defuns
4536 @section Exercises
4538 @itemize @bullet
4539 @item
4540 Write a non-interactive function that doubles the value of its
4541 argument, a number.  Make that function interactive.
4543 @item
4544 Write a function that tests whether the current value of
4545 @code{fill-column} is greater than the argument passed to the function,
4546 and if so, prints an appropriate message.
4547 @end itemize
4549 @node Buffer Walk Through, More Complex, Writing Defuns, Top
4550 @comment  node-name,  next,  previous,  up
4551 @chapter A Few Buffer--Related Functions
4553 In this chapter we study in detail several of the functions used in GNU
4554 Emacs.  This is called a ``walk-through''.  These functions are used as
4555 examples of Lisp code, but are not imaginary examples; with the
4556 exception of the first, simplified function definition, these functions
4557 show the actual code used in GNU Emacs.  You can learn a great deal from
4558 these definitions.  The functions described here are all related to
4559 buffers.  Later, we will study other functions.
4561 @menu
4562 * Finding More::                How to find more information.
4563 * simplified-beginning-of-buffer::  Shows @code{goto-char},
4564                                 @code{point-min}, and @code{push-mark}.
4565 * mark-whole-buffer::           Almost the same as @code{beginning-of-buffer}.
4566 * append-to-buffer::            Uses @code{save-excursion} and
4567                                 @code{insert-buffer-substring}.
4568 * Buffer Related Review::       Review.
4569 * Buffer Exercises::
4570 @end menu
4572 @node Finding More, simplified-beginning-of-buffer, Buffer Walk Through, Buffer Walk Through
4573 @section Finding More Information
4575 @findex describe-function, @r{introduced}
4576 @cindex Find function documentation
4577 In this walk-through, I will describe each new function as we come to
4578 it, sometimes in detail and sometimes briefly.  If you are interested,
4579 you can get the full documentation of any Emacs Lisp function at any
4580 time by typing @kbd{C-h f} and then the name of the function (and then
4581 @key{RET}).  Similarly, you can get the full documentation for a
4582 variable by typing @kbd{C-h v} and then the name of the variable (and
4583 then @key{RET}).
4585 @cindex Find source of function
4586 In versions 20 and higher, when a function is written in Emacs Lisp,
4587 @code{describe-function} will also tell you the location of the
4588 function definition.  If you move point over the file name and press
4589 the @key{RET} key, which in this case means @code{help-follow} rather
4590 than `return' or `enter', Emacs will take you directly to the function
4591 definition.
4593 More generally, if you want to see a function in its original source
4594 file, you can use the @code{find-tags} function to jump to it.
4595 @code{find-tags} works with a wide variety of languages, not just
4596 Lisp, and C, and it works with non-programming text as well.  For
4597 example, @code{find-tags} will jump to the various nodes in the
4598 Texinfo source file of this document.
4600 The @code{find-tags} function depends on `tags tables' that record
4601 the locations of the functions, variables, and other items to which
4602 @code{find-tags} jumps.
4604 To use the @code{find-tags} command, type @kbd{M-.}  (i.e., press the
4605 period key while holding down the @key{META} key, or else type the
4606 @key{ESC} key and then type the period key), and then, at the prompt,
4607 type in the name of the function whose source code you want to see,
4608 such as @code{mark-whole-buffer}, and then type @key{RET}.  Emacs will
4609 switch buffers and display the source code for the function on your
4610 screen.  To switch back to your current buffer, type @kbd{C-x b
4611 @key{RET}}.  (On some keyboards, the @key{META} key is labelled
4612 @key{ALT}.)
4614 @c !!! 21.0.100 tags table location in this paragraph
4615 @cindex TAGS table, specifying
4616 @findex find-tags
4617 Depending on how the initial default values of your copy of Emacs are
4618 set, you may also need to specify the location of your `tags table',
4619 which is a file called @file{TAGS}.  For example, if you are
4620 interested in Emacs sources, the tags table you will most likely want,
4621 if it has already been created for you, will be in a subdirectory of
4622 the @file{/usr/local/share/emacs/} directory; thus you would use the
4623 @code{M-x visit-tags-table} command and specify a pathname such as
4624 @file{/usr/local/share/emacs/21.0.100/lisp/TAGS} or
4625 @file{/usr/local/src/emacs/src/TAGS}.  If the tags table has
4626 not already been created, you will have to create it yourself.
4628 @need 1250
4629 To create a @file{TAGS} file in a specific directory, switch to that
4630 directory in Emacs using @kbd{M-x cd} command, or list the directory
4631 with @kbd{C-x d} (@code{dired}).  Then run the compile command, with
4632 @w{@code{etags *.el}} as the command to execute
4634 @smallexample
4635 M-x compile RET etags *.el RET
4636 @end smallexample
4638 For more information, see @ref{etags, , Create Your Own @file{TAGS} File}.
4640 After you become more familiar with Emacs Lisp, you will find that you will
4641 frequently use @code{find-tags} to navigate your way around source code;
4642 and you will create your own @file{TAGS} tables.
4644 @cindex Library, as term for `file'
4645 Incidentally, the files that contain Lisp code are conventionally
4646 called @dfn{libraries}.  The metaphor is derived from that of a
4647 specialized library, such as a law library or an engineering library,
4648 rather than a general library.  Each library, or file, contains
4649 functions that relate to a particular topic or activity, such as
4650 @file{abbrev.el} for handling abbreviations and other typing
4651 shortcuts, and @file{help.el} for on-line help.  (Sometimes several
4652 libraries provide code for a single activity, as the various
4653 @file{rmail@dots{}} files provide code for reading electronic mail.)
4654 In @cite{The GNU Emacs Manual}, you will see sentences such as ``The
4655 @kbd{C-h p} command lets you search the standard Emacs Lisp libraries
4656 by topic keywords.''
4658 @node simplified-beginning-of-buffer, mark-whole-buffer, Finding More, Buffer Walk Through
4659 @comment  node-name,  next,  previous,  up
4660 @section A Simplified @code{beginning-of-buffer} Definition
4661 @findex simplified-beginning-of-buffer
4663 The @code{beginning-of-buffer} command is a good function to start with
4664 since you are likely to be familiar with it and it is easy to
4665 understand.  Used as an interactive command, @code{beginning-of-buffer}
4666 moves the cursor to the beginning of the buffer, leaving the mark at the
4667 previous position.  It is generally bound to @kbd{M-<}.
4669 In this section, we will discuss a shortened version of the function
4670 that shows how it is most frequently used.  This shortened function
4671 works as written, but it does not contain the code for a complex option.
4672 In another section, we will describe the entire function.
4673 (@xref{beginning-of-buffer, , Complete Definition of
4674 @code{beginning-of-buffer}}.)
4676 Before looking at the code, let's consider what the function
4677 definition has to contain: it must include an expression that makes
4678 the function interactive so it can be called by typing @kbd{M-x
4679 beginning-of-buffer} or by typing a keychord such as @kbd{M-<}; it
4680 must include code to leave a mark at the original position in the
4681 buffer; and it must include code to move the cursor to the beginning
4682 of the buffer.
4684 @need 1250
4685 Here is the complete text of the shortened version of the function:
4687 @smallexample
4688 @group
4689 (defun simplified-beginning-of-buffer ()
4690   "Move point to the beginning of the buffer;
4691 leave mark at previous position."
4692   (interactive)
4693   (push-mark)
4694   (goto-char (point-min)))
4695 @end group
4696 @end smallexample
4698 Like all function definitions, this definition has five parts following
4699 the special form @code{defun}:
4701 @enumerate
4702 @item
4703 The name: in this example, @code{simplified-beginning-of-buffer}.
4705 @item
4706 A list of the arguments: in this example, an empty list, @code{()},
4708 @item
4709 The documentation string.
4711 @item
4712 The interactive expression.
4714 @item
4715 The body.
4716 @end enumerate
4718 @noindent
4719 In this function definition, the argument list is empty; this means that
4720 this function does not require any arguments.  (When we look at the
4721 definition for the complete function, we will see that it may be passed
4722 an optional argument.)
4724 The interactive expression tells Emacs that the function is intended to
4725 be used interactively.  In this example, @code{interactive} does not have
4726 an argument because @code{simplified-beginning-of-buffer} does not
4727 require one.
4729 @need 800
4730 The body of the function consists of the two lines:
4732 @smallexample
4733 @group
4734 (push-mark)
4735 (goto-char (point-min))
4736 @end group
4737 @end smallexample
4739 The first of these lines is the expression, @code{(push-mark)}.  When
4740 this expression is evaluated by the Lisp interpreter, it sets a mark at
4741 the current position of the cursor, wherever that may be.  The position
4742 of this mark is saved in the mark ring.
4744 The next line is @code{(goto-char (point-min))}.  This expression
4745 jumps the cursor to the minimum point in the buffer, that is, to the
4746 beginning of the buffer (or to the beginning of the accessible portion
4747 of the buffer if it is narrowed.  @xref{Narrowing & Widening, ,
4748 Narrowing and Widening}.)
4750 The @code{push-mark} command sets a mark at the place where the cursor
4751 was located before it was moved to the beginning of the buffer by the
4752 @code{(goto-char (point-min))} expression.  Consequently, you can, if
4753 you wish, go back to where you were originally by typing @kbd{C-x C-x}.
4755 That is all there is to the function definition!
4757 @findex describe-function
4758 When you are reading code such as this and come upon an unfamiliar
4759 function, such as @code{goto-char}, you can find out what it does by
4760 using the @code{describe-function} command.  To use this command, type
4761 @kbd{C-h f} and then type in the name of the function and press
4762 @key{RET}.  The @code{describe-function} command will print the
4763 function's documentation string in a @file{*Help*} window.  For
4764 example, the documentation for @code{goto-char} is:
4766 @smallexample
4767 @group
4768 One arg, a number.  Set point to that number.
4769 Beginning of buffer is position (point-min),
4770 end is (point-max).
4771 @end group
4772 @end smallexample
4774 @noindent
4775 (The prompt for @code{describe-function} will offer you the symbol
4776 under or preceding the cursor, so you can save typing by positioning
4777 the cursor right over or after the function and then typing @kbd{C-h f
4778 @key{RET}}.)
4780 The @code{end-of-buffer} function definition is written in the same way as
4781 the @code{beginning-of-buffer} definition except that the body of the
4782 function contains the expression @code{(goto-char (point-max))} in place
4783 of @code{(goto-char (point-min))}.
4785 @node mark-whole-buffer, append-to-buffer, simplified-beginning-of-buffer, Buffer Walk Through
4786 @comment  node-name,  next,  previous,  up
4787 @section The Definition of @code{mark-whole-buffer}
4788 @findex mark-whole-buffer
4790 The @code{mark-whole-buffer} function is no harder to understand than the
4791 @code{simplified-beginning-of-buffer} function.  In this case, however,
4792 we will look at the complete function, not a shortened version.
4794 The @code{mark-whole-buffer} function is not as commonly used as the
4795 @code{beginning-of-buffer} function, but is useful nonetheless: it
4796 marks a whole buffer as a region by putting point at the beginning and
4797 a mark at the end of the buffer.  It is generally bound to @kbd{C-x
4801 @menu
4802 * mark-whole-buffer overview::
4803 * Body of mark-whole-buffer::   Only three lines of code.
4804 @end menu
4807 @node mark-whole-buffer overview, Body of mark-whole-buffer, mark-whole-buffer, mark-whole-buffer
4808 @ifnottex
4809 @unnumberedsubsec An overview of @code{mark-whole-buffer}
4810 @end ifnottex
4812 @need 1250
4813 In GNU Emacs 20, the code for the complete function looks like this:
4815 @smallexample
4816 @group
4817 (defun mark-whole-buffer ()
4818   "Put point at beginning and mark at end of buffer."
4819   (interactive)
4820   (push-mark (point))
4821   (push-mark (point-max))
4822   (goto-char (point-min)))
4823 @end group
4824 @end smallexample
4826 @need 1250
4827 Like all other functions, the @code{mark-whole-buffer} function fits
4828 into the template for a function definition.  The template looks like
4829 this:
4831 @smallexample
4832 @group
4833 (defun @var{name-of-function} (@var{argument-list})
4834   "@var{documentation}@dots{}"
4835   (@var{interactive-expression}@dots{})
4836   @var{body}@dots{})
4837 @end group
4838 @end smallexample
4840 Here is how the function works: the name of the function is
4841 @code{mark-whole-buffer}; it is followed by an empty argument list,
4842 @samp{()}, which means that the function does not require arguments.
4843 The documentation comes next.
4845 The next line is an @code{(interactive)} expression that tells Emacs
4846 that the function will be used interactively.  These details are similar
4847 to the @code{simplified-beginning-of-buffer} function described in the
4848 previous section.
4850 @need 1250
4851 @node Body of mark-whole-buffer,  , mark-whole-buffer overview, mark-whole-buffer
4852 @comment  node-name,  next,  previous,  up
4853 @subsection Body of @code{mark-whole-buffer}
4855 The body of the @code{mark-whole-buffer} function consists of three
4856 lines of code:
4858 @smallexample
4859 @group
4860 (push-mark (point))
4861 (push-mark (point-max))
4862 (goto-char (point-min))
4863 @end group
4864 @end smallexample
4866 The first of these lines is the expression, @code{(push-mark (point))}.
4868 This line does exactly the same job as the first line of the body of
4869 the @code{simplified-beginning-of-buffer} function, which is written
4870 @code{(push-mark)}.  In both cases, the Lisp interpreter sets a mark
4871 at the current position of the cursor.
4873 I don't know why the expression in @code{mark-whole-buffer} is written
4874 @code{(push-mark (point))} and the expression in
4875 @code{beginning-of-buffer} is written @code{(push-mark)}.  Perhaps
4876 whoever wrote the code did not know that the arguments for
4877 @code{push-mark} are optional and that if @code{push-mark} is not
4878 passed an argument, the function automatically sets mark at the
4879 location of point by default.  Or perhaps the expression was written
4880 so as to parallel the structure of the next line.  In any case, the
4881 line causes Emacs to determine the position of point and set a mark
4882 there.
4884 The next line of @code{mark-whole-buffer} is @code{(push-mark (point-max)}.
4885 This expression sets a mark at the point in the buffer
4886 that has the highest number.  This will be the end of the buffer (or,
4887 if the buffer is narrowed, the end of the accessible portion of the
4888 buffer.  @xref{Narrowing & Widening, , Narrowing and Widening}, for
4889 more about narrowing.)  After this mark has been set, the previous
4890 mark, the one set at point, is no longer set, but Emacs remembers its
4891 position, just as all other recent marks are always remembered.  This
4892 means that you can, if you wish, go back to that position by typing
4893 @kbd{C-u C-@key{SPC}} twice.
4895 (In GNU Emacs 21, the @code{(push-mark (point-max)} is slightly more
4896 complicated than shown here.  The line reads
4898 @smallexample
4899 (push-mark (point-max) nil t)
4900 @end smallexample
4902 @noindent
4903 (The expression works nearly the same as before.  It sets a mark at
4904 the highest numbered place in the buffer that it can.  However, in
4905 this version, @code{push-mark} has two additional arguments.  The
4906 second argument to @code{push-mark} is @code{nil}.  This tells the
4907 function it @emph{should} display a message that says `Mark set' when
4908 it pushes the mark.  The third argument is @code{t}.  This tells
4909 @code{push-mark} to activate the mark when Transient Mark mode is
4910 turned on.  Transient Mark mode highlights the currently active
4911 region.  It is usually turned off.)
4913 Finally, the last line of the function is @code{(goto-char
4914 (point-min)))}.  This is written exactly the same way as it is written
4915 in @code{beginning-of-buffer}.  The expression moves the cursor to
4916 the minimum point in the buffer, that is, to the beginning of the buffer
4917 (or to the beginning of the accessible portion of the buffer).  As a
4918 result of this, point is placed at the beginning of the buffer and mark
4919 is set at the end of the buffer.  The whole buffer is, therefore, the
4920 region.
4922 @node append-to-buffer, Buffer Related Review, mark-whole-buffer, Buffer Walk Through
4923 @comment  node-name,  next,  previous,  up
4924 @section The Definition of @code{append-to-buffer}
4925 @findex append-to-buffer
4927 The @code{append-to-buffer} command is very nearly as simple as the
4928 @code{mark-whole-buffer} command.  What it does is copy the region (that
4929 is, the part of the buffer between point and mark) from the current
4930 buffer to a specified buffer.
4932 @menu
4933 * append-to-buffer overview::
4934 * append interactive::          A two part interactive expression.
4935 * append-to-buffer body::       Incorporates a @code{let} expression.
4936 * append save-excursion::       How the @code{save-excursion} works.
4937 @end menu
4939 @node append-to-buffer overview, append interactive, append-to-buffer, append-to-buffer
4940 @ifnottex
4941 @unnumberedsubsec An Overview of @code{append-to-buffer}
4942 @end ifnottex
4944 @findex insert-buffer-substring
4945 The @code{append-to-buffer} command uses the
4946 @code{insert-buffer-substring} function to copy the region.
4947 @code{insert-buffer-substring} is described by its name: it takes a
4948 string of characters from part of a buffer, a ``substring'', and
4949 inserts them into another buffer.  Most of @code{append-to-buffer} is
4950 concerned with setting up the conditions for
4951 @code{insert-buffer-substring} to work: the code must specify both the
4952 buffer to which the text will go and the region that will be copied.
4953 Here is the complete text of the function:
4955 @smallexample
4956 @group
4957 (defun append-to-buffer (buffer start end)
4958   "Append to specified buffer the text of the region.
4959 It is inserted into that buffer before its point.
4960 @end group
4962 @group
4963 When calling from a program, give three arguments:
4964 a buffer or the name of one, and two character numbers
4965 specifying the portion of the current buffer to be copied."
4966   (interactive "BAppend to buffer:@: \nr")
4967   (let ((oldbuf (current-buffer)))
4968     (save-excursion
4969       (set-buffer (get-buffer-create buffer))
4970       (insert-buffer-substring oldbuf start end))))
4971 @end group
4972 @end smallexample
4974 The function can be understood by looking at it as a series of
4975 filled-in templates.
4977 The outermost template is for the function definition.  In this
4978 function, it looks like this (with several slots filled in):
4980 @smallexample
4981 @group
4982 (defun append-to-buffer (buffer start end)
4983   "@var{documentation}@dots{}"
4984   (interactive "BAppend to buffer:@: \nr")
4985   @var{body}@dots{})
4986 @end group
4987 @end smallexample
4989 The first line of the function includes its name and three arguments.
4990 The arguments are the @code{buffer} to which the text will be copied, and
4991 the @code{start} and @code{end} of the region in the current buffer that
4992 will be copied.
4994 The next part of the function is the documentation, which is clear and
4995 complete.
4997 @node append interactive, append-to-buffer body, append-to-buffer overview, append-to-buffer
4998 @comment  node-name,  next,  previous,  up
4999 @subsection The @code{append-to-buffer} Interactive Expression
5001 Since the @code{append-to-buffer} function will be used interactively,
5002 the function must have an @code{interactive} expression.  (For a
5003 review of @code{interactive}, see @ref{Interactive, , Making a
5004 Function Interactive}.)  The expression reads as follows:
5006 @smallexample
5007 (interactive "BAppend to buffer:@: \nr")
5008 @end smallexample
5010 @noindent
5011 This expression has an argument inside of quotation marks and that
5012 argument has two parts, separated by @samp{\n}.
5014 The first part is @samp{BAppend to buffer:@: }.  Here, the @samp{B}
5015 tells Emacs to ask for the name of the buffer that will be passed to the
5016 function.  Emacs will ask for the name by prompting the user in the
5017 minibuffer, using the string following the @samp{B}, which is the string
5018 @samp{Append to buffer:@: }.  Emacs then binds the variable @code{buffer}
5019 in the function's argument list to the specified buffer.
5021 The newline, @samp{\n}, separates the first part of the argument from
5022 the second part.  It is followed by an @samp{r} that tells Emacs to bind
5023 the two arguments that follow the symbol @code{buffer} in the function's
5024 argument list (that is, @code{start} and @code{end}) to the values of
5025 point and mark.
5027 @node append-to-buffer body, append save-excursion, append interactive, append-to-buffer
5028 @comment  node-name,  next,  previous,  up
5029 @subsection The Body of @code{append-to-buffer}
5031 The body of the @code{append-to-buffer} function begins with @code{let}.
5033 As we have seen before (@pxref{let, , @code{let}}), the purpose of a
5034 @code{let} expression is to create and give initial values to one or
5035 more variables that will only be used within the body of the
5036 @code{let}.  This means that such a variable will not be confused with
5037 any variable of the same name outside the @code{let} expression.
5039 We can see how the @code{let} expression fits into the function as a
5040 whole by showing a template for @code{append-to-buffer} with the
5041 @code{let} expression in outline:
5043 @smallexample
5044 @group
5045 (defun append-to-buffer (buffer start end)
5046   "@var{documentation}@dots{}"
5047   (interactive "BAppend to buffer:@: \nr")
5048   (let ((@var{variable} @var{value}))
5049         @var{body}@dots{})
5050 @end group
5051 @end smallexample
5053 The @code{let} expression has three elements:
5055 @enumerate
5056 @item
5057 The symbol @code{let};
5059 @item
5060 A varlist containing, in this case, a single two-element list,
5061 @code{(@var{variable} @var{value})};
5063 @item
5064 The body of the @code{let} expression.
5065 @end enumerate
5067 @need 800
5068 In the @code{append-to-buffer} function, the varlist looks like this:
5070 @smallexample
5071 (oldbuf (current-buffer))
5072 @end smallexample
5074 @noindent
5075 In this part of the @code{let} expression, the one variable,
5076 @code{oldbuf}, is bound to the value returned by the
5077 @code{(current-buffer)} expression.  The variable, @code{oldbuf}, is
5078 used to keep track of the buffer in which you are working and from
5079 which you will copy.
5081 The element or elements of a varlist are surrounded by a set of
5082 parentheses so the Lisp interpreter can distinguish the varlist from
5083 the body of the @code{let}.  As a consequence, the two-element list
5084 within the varlist is surrounded by a circumscribing set of parentheses.
5085 The line looks like this:
5087 @smallexample
5088 @group
5089 (let ((oldbuf (current-buffer)))
5090   @dots{} )
5091 @end group
5092 @end smallexample
5094 @noindent
5095 The two parentheses before @code{oldbuf} might surprise you if you did
5096 not realize that the first parenthesis before @code{oldbuf} marks the
5097 boundary of the varlist and the second parenthesis marks the beginning
5098 of the two-element list, @code{(oldbuf (current-buffer))}.
5100 @node append save-excursion,  , append-to-buffer body, append-to-buffer
5101 @comment  node-name,  next,  previous,  up
5102 @subsection @code{save-excursion} in @code{append-to-buffer}
5104 The body of the @code{let} expression in @code{append-to-buffer}
5105 consists of a @code{save-excursion} expression.
5107 The @code{save-excursion} function saves the locations of point and
5108 mark, and restores them to those positions after the expressions in the
5109 body of the @code{save-excursion} complete execution.  In addition,
5110 @code{save-excursion} keeps track of the original buffer, and
5111 restores it.  This is how @code{save-excursion} is used in
5112 @code{append-to-buffer}.
5114 @need 1500
5115 @cindex Indentation for formatting
5116 @cindex Formatting convention
5117 Incidentally, it is worth noting here that a Lisp function is normally
5118 formatted so that everything that is enclosed in a multi-line spread is
5119 indented more to the right than the first symbol.  In this function
5120 definition, the @code{let} is indented more than the @code{defun}, and
5121 the @code{save-excursion} is indented more than the @code{let}, like
5122 this:
5124 @smallexample
5125 @group
5126 (defun @dots{}
5127   @dots{}
5128   @dots{}
5129   (let@dots{}
5130     (save-excursion
5131       @dots{}
5132 @end group
5133 @end smallexample
5135 @need 1500
5136 @noindent
5137 This formatting convention makes it easy to see that the two lines in
5138 the body of the @code{save-excursion} are enclosed by the parentheses
5139 associated with @code{save-excursion}, just as the
5140 @code{save-excursion} itself is enclosed by the parentheses associated
5141 with the @code{let}:
5143 @smallexample
5144 @group
5145 (let ((oldbuf (current-buffer)))
5146   (save-excursion
5147     (set-buffer (get-buffer-create buffer))
5148     (insert-buffer-substring oldbuf start end))))
5149 @end group
5150 @end smallexample
5152 @need 1200
5153 The use of the @code{save-excursion} function can be viewed as a process
5154 of filling in the slots of a template:
5156 @smallexample
5157 @group
5158 (save-excursion
5159   @var{first-expression-in-body}
5160   @var{second-expression-in-body}
5161    @dots{}
5162   @var{last-expression-in-body})
5163 @end group
5164 @end smallexample
5166 @need 1200
5167 @noindent
5168 In this function, the body of the @code{save-excursion} contains only
5169 two expressions.  The body looks like this:
5171 @smallexample
5172 @group
5173 (set-buffer (get-buffer-create buffer))
5174 (insert-buffer-substring oldbuf start end)
5175 @end group
5176 @end smallexample
5178 When the @code{append-to-buffer} function is evaluated, the two
5179 expressions in the body of the @code{save-excursion} are evaluated in
5180 sequence.  The value of the last expression is returned as the value of
5181 the @code{save-excursion} function; the other expression is evaluated
5182 only for its side effects.
5184 The first line in the body of the @code{save-excursion} uses the
5185 @code{set-buffer} function to change the current buffer to the one
5186 specified in the first argument to @code{append-to-buffer}.  (Changing
5187 the buffer is the side effect; as we have said before, in Lisp, a side
5188 effect is often the primary thing we want.)  The second line does the
5189 primary work of the function.
5191 The @code{set-buffer} function changes Emacs' attention to the buffer to
5192 which the text will be copied and from which @code{save-excursion} will
5193 return.
5195 @need 800
5196 The line looks like this:
5198 @smallexample
5199 (set-buffer (get-buffer-create buffer))
5200 @end smallexample
5202 The innermost expression of this list is @code{(get-buffer-create
5203 buffer)}.  This expression uses the @code{get-buffer-create} function,
5204 which either gets the named buffer, or if it does not exist, creates one
5205 with the given name.  This means you can use @code{append-to-buffer} to
5206 put text into a buffer that did not previously exist.
5208 @code{get-buffer-create} also keeps @code{set-buffer} from getting an
5209 unnecessary error: @code{set-buffer} needs a buffer to go to; if you
5210 were to specify a buffer that does not exist, Emacs would baulk.
5211 Since @code{get-buffer-create} will create a buffer if none exists,
5212 @code{set-buffer} is always provided with a buffer.
5214 @need 1250
5215 The last line of @code{append-to-buffer} does the work of appending
5216 the text:
5218 @smallexample
5219 (insert-buffer-substring oldbuf start end)
5220 @end smallexample
5222 @noindent
5223 The @code{insert-buffer-substring} function copies a string @emph{from}
5224 the buffer specified as its first argument and inserts the string into
5225 the present buffer.  In this case, the argument to
5226 @code{insert-buffer-substring} is the value of the variable created and
5227 bound by the @code{let}, namely the value of @code{oldbuf}, which was
5228 the current buffer when you gave the @code{append-to-buffer} command.
5230 After @code{insert-buffer-substring} has done its work,
5231 @code{save-excursion} will restore the action to the original buffer and
5232 @code{append-to-buffer} will have done its job.
5234 @need 800
5235 Written in skeletal form, the workings of the body look like this:
5237 @smallexample
5238 @group
5239 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5240   (save-excursion                       ; @r{Keep track of buffer.}
5241     @var{change-buffer}
5242     @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})
5244   @var{change-back-to-original-buffer-when-finished}
5245 @var{let-the-local-meaning-of-}@code{oldbuf}@var{-disappear-when-finished}
5247 @end group
5248 @end smallexample
5250 In summary, @code{append-to-buffer} works as follows: it saves the value
5251 of the current buffer in the variable called @code{oldbuf}.  It gets the
5252 new buffer, creating one if need be, and switches Emacs to it.  Using
5253 the value of @code{oldbuf}, it inserts the region of text from the old
5254 buffer into the new buffer; and then using @code{save-excursion}, it
5255 brings you back to your original buffer.
5257 In looking at @code{append-to-buffer}, you have explored a fairly
5258 complex function.  It shows how to use @code{let} and
5259 @code{save-excursion}, and how to change to and come back from another
5260 buffer.  Many function definitions use @code{let},
5261 @code{save-excursion}, and @code{set-buffer} this way.
5263 @node Buffer Related Review, Buffer Exercises, append-to-buffer, Buffer Walk Through
5264 @comment  node-name,  next,  previous,  up
5265 @section Review
5267 Here is a brief summary of the various functions discussed in this chapter.
5269 @table @code
5270 @item describe-function
5271 @itemx describe-variable
5272 Print the documentation for a function or variable.
5273 Conventionally bound to @kbd{C-h f} and @kbd{C-h v}.
5275 @item find-tag
5276 Find the file containing the source for a function or variable and
5277 switch buffers to it, positioning point at the beginning of the item.
5278 Conventionally bound to @kbd{M-.} (that's a period following the
5279 @key{META} key).
5281 @item save-excursion
5282 Save the location of point and mark and restore their values after the
5283 arguments to @code{save-excursion} have been evaluated.  Also, remember
5284 the current buffer and return to it.
5286 @item push-mark
5287 Set mark at a location and record the value of the previous mark on the
5288 mark ring.  The mark is a location in the buffer that will keep its
5289 relative position even if text is added to or removed from the buffer.
5291 @item goto-char
5292 Set point to the location specified by the value of the argument, which
5293 can be a number, a marker,  or an expression that returns the number of
5294 a position, such as @code{(point-min)}.
5296 @item insert-buffer-substring
5297 Copy a region of text from a buffer that is passed to the function as
5298 an argument and insert the region into the current buffer.
5300 @item mark-whole-buffer
5301 Mark the whole buffer as a region.  Normally bound to @kbd{C-x h}.
5303 @item set-buffer
5304 Switch the attention of Emacs to another buffer, but do not change the
5305 window being displayed.  Used when the program rather than a human is
5306 to work on a different buffer.
5308 @item get-buffer-create
5309 @itemx get-buffer
5310 Find a named buffer or create one if a buffer of that name does not
5311 exist.  The @code{get-buffer} function returns @code{nil} if the named
5312 buffer does not exist.
5313 @end table
5315 @need 1500
5316 @node Buffer Exercises,  , Buffer Related Review, Buffer Walk Through
5317 @section Exercises
5319 @itemize @bullet
5320 @item
5321 Write your own @code{simplified-end-of-buffer} function definition;
5322 then test it to see whether it works.
5324 @item
5325 Use @code{if} and @code{get-buffer} to write a function that prints a
5326 message telling you whether a buffer exists.
5328 @item
5329 Using @code{find-tag}, find the source for the @code{copy-to-buffer}
5330 function.
5331 @end itemize
5333 @node More Complex, Narrowing & Widening, Buffer Walk Through, Top
5334 @comment  node-name,  next,  previous,  up
5335 @chapter A Few More Complex Functions
5337 In this chapter, we build on what we have learned in previous chapters
5338 by looking at more complex functions.  The @code{copy-to-buffer}
5339 function illustrates use of two @code{save-excursion} expressions in
5340 one definition, while the @code{insert-buffer} function illustrates
5341 use of an asterisk in an @code{interactive} expression, use of
5342 @code{or}, and the important distinction between a name and the object
5343 to which the name refers.
5345 @menu
5346 * copy-to-buffer::              With @code{set-buffer}, @code{get-buffer-create}.
5347 * insert-buffer::               Read-only, and with @code{or}.
5348 * beginning-of-buffer::         Shows @code{goto-char},
5349                                 @code{point-min}, and @code{push-mark}.
5350 * Second Buffer Related Review::
5351 * optional Exercise::
5352 @end menu
5354 @node copy-to-buffer, insert-buffer, More Complex, More Complex
5355 @comment  node-name,  next,  previous,  up
5356 @section The Definition of @code{copy-to-buffer}
5357 @findex copy-to-buffer
5359 After understanding how @code{append-to-buffer} works, it is easy to
5360 understand @code{copy-to-buffer}.  This function copies text into a
5361 buffer, but instead of adding to the second buffer, it replaces the
5362 previous text in the second buffer.  The code for the
5363 @code{copy-to-buffer} function is almost the same as the code for
5364 @code{append-to-buffer}, except that @code{erase-buffer} and a second
5365 @code{save-excursion} are used.  (@xref{append-to-buffer, , The
5366 Definition of @code{append-to-buffer}}, for the description of
5367 @code{append-to-buffer}.)
5369 @need 800
5370 The body of @code{copy-to-buffer} looks like this
5372 @smallexample
5373 @group
5374 @dots{}
5375 (interactive "BCopy to buffer:@: \nr")
5376   (let ((oldbuf (current-buffer)))
5377     (save-excursion
5378       (set-buffer (get-buffer-create buffer))
5379       (erase-buffer)
5380       (save-excursion
5381         (insert-buffer-substring oldbuf start end)))))
5382 @end group
5383 @end smallexample
5385 This code is similar to the code in @code{append-to-buffer}: it is
5386 only after changing to the buffer to which the text will be copied
5387 that the definition for this function diverges from the definition for
5388 @code{append-to-buffer}: the @code{copy-to-buffer} function erases the
5389 buffer's former contents.  (This is what is meant by `replacement'; to
5390 replace text, Emacs erases the previous text and then inserts new
5391 text.)  After erasing the previous contents of the buffer,
5392 @code{save-excursion} is used for a second time and the new text is
5393 inserted.
5395 Why is @code{save-excursion} used twice?  Consider again what the
5396 function does.
5398 @need 1250
5399 In outline, the body of @code{copy-to-buffer} looks like this:
5401 @smallexample
5402 @group
5403 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5404   (save-excursion         ; @r{First use of @code{save-excursion}.}
5405     @var{change-buffer}
5406       (erase-buffer)
5407       (save-excursion     ; @r{Second use of @code{save-excursion}.}
5408         @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})))
5409 @end group
5410 @end smallexample
5412 The first use of @code{save-excursion} returns Emacs to the buffer from
5413 which the text is being copied.  That is clear, and is just like its use
5414 in @code{append-to-buffer}.  Why the second use?  The reason is that
5415 @code{insert-buffer-substring} always leaves point at the @emph{end} of
5416 the region being inserted.  The second @code{save-excursion} causes
5417 Emacs to leave point at the beginning of the text being inserted.  In
5418 most circumstances, users prefer to find point at the beginning of
5419 inserted text.  (Of course, the @code{copy-to-buffer} function returns
5420 the user to the original buffer when done---but if the user @emph{then}
5421 switches to the copied-to buffer, point will go to the beginning of the
5422 text.  Thus, this use of a second @code{save-excursion} is a little
5423 nicety.)
5425 @node insert-buffer, beginning-of-buffer, copy-to-buffer, More Complex
5426 @comment  node-name,  next,  previous,  up
5427 @section The Definition of @code{insert-buffer}
5428 @findex insert-buffer
5430 @code{insert-buffer} is yet another buffer-related function.  This
5431 command copies another buffer @emph{into} the current buffer.  It is the
5432 reverse of @code{append-to-buffer} or @code{copy-to-buffer}, since they
5433 copy a region of text @emph{from} the current buffer to another buffer.
5435 Here is a discussion based on the original code.  The code was
5436 simplified in 2003 and is harder to understand.
5438 In addition, this code illustrates the use of @code{interactive} with a
5439 buffer that might be @dfn{read-only} and the important distinction
5440 between the name of an object and the object actually referred to.
5442 @menu
5443 * insert-buffer code::
5444 * insert-buffer interactive::   When you can read, but not write.
5445 * insert-buffer body::          The body has an @code{or} and a @code{let}.
5446 * if & or::                     Using an @code{if} instead of an @code{or}.
5447 * Insert or::                   How the @code{or} expression works.
5448 * Insert let::                  Two @code{save-excursion} expressions.
5449 @end menu
5451 @node insert-buffer code, insert-buffer interactive, insert-buffer, insert-buffer
5452 @ifnottex
5453 @unnumberedsubsec The Code for @code{insert-buffer}
5454 @end ifnottex
5456 @need 800
5457 Here is the code:
5459 @smallexample
5460 @group
5461 (defun insert-buffer (buffer)
5462   "Insert after point the contents of BUFFER.
5463 Puts mark after the inserted text.
5464 BUFFER may be a buffer or a buffer name."
5465   (interactive "*bInsert buffer:@: ")
5466 @end group
5467 @group
5468   (or (bufferp buffer)
5469       (setq buffer (get-buffer buffer)))
5470   (let (start end newmark)
5471     (save-excursion
5472       (save-excursion
5473         (set-buffer buffer)
5474         (setq start (point-min) end (point-max)))
5475 @end group
5476 @group
5477       (insert-buffer-substring buffer start end)
5478       (setq newmark (point)))
5479     (push-mark newmark)))
5480 @end group
5481 @end smallexample
5483 @need 1200
5484 As with other function definitions, you can use a template to see an
5485 outline of the function:
5487 @smallexample
5488 @group
5489 (defun insert-buffer (buffer)
5490   "@var{documentation}@dots{}"
5491   (interactive "*bInsert buffer:@: ")
5492   @var{body}@dots{})
5493 @end group
5494 @end smallexample
5496 @node insert-buffer interactive, insert-buffer body, insert-buffer code, insert-buffer
5497 @comment  node-name,  next,  previous,  up
5498 @subsection The Interactive Expression in @code{insert-buffer}
5499 @findex interactive, @r{example use of}
5501 In @code{insert-buffer}, the argument to the @code{interactive}
5502 declaration has two parts, an asterisk, @samp{*}, and @samp{bInsert
5503 buffer:@: }.
5505 @menu
5506 * Read-only buffer::            When a buffer cannot be modified.
5507 * b for interactive::           An existing buffer or else its name.
5508 @end menu
5510 @node Read-only buffer, b for interactive, insert-buffer interactive, insert-buffer interactive
5511 @comment  node-name,  next,  previous,  up
5512 @unnumberedsubsubsec A Read-only Buffer
5513 @cindex Read-only buffer
5514 @cindex Asterisk for read-only buffer
5515 @findex * @r{for read-only buffer}
5517 The asterisk is for the situation when the current buffer is a
5518 read-only buffer---a buffer that cannot be modified.  If
5519 @code{insert-buffer} is called when the current buffer is read-only, a
5520 message to this effect is printed in the echo area and the terminal
5521 may beep or blink at you; you will not be permitted to insert anything
5522 into current buffer.  The asterisk does not need to be followed by a
5523 newline to separate it from the next argument.
5525 @node b for interactive,  , Read-only buffer, insert-buffer interactive
5526 @comment  node-name,  next,  previous,  up
5527 @unnumberedsubsubsec @samp{b} in an Interactive Expression
5529 The next argument in the interactive expression starts with a lower
5530 case @samp{b}.  (This is different from the code for
5531 @code{append-to-buffer}, which uses an upper-case @samp{B}.
5532 @xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
5533 The lower-case @samp{b} tells the Lisp interpreter that the argument
5534 for @code{insert-buffer} should be an existing buffer or else its
5535 name.  (The upper-case @samp{B} option provides for the possibility
5536 that the buffer does not exist.)  Emacs will prompt you for the name
5537 of the buffer, offering you a default buffer, with name completion
5538 enabled.  If the buffer does not exist, you receive a message that
5539 says ``No match''; your terminal may beep at you as well.
5541 @node insert-buffer body, if & or, insert-buffer interactive, insert-buffer
5542 @comment  node-name,  next,  previous,  up
5543 @subsection The Body of the @code{insert-buffer} Function
5545 The body of the @code{insert-buffer} function has two major parts: an
5546 @code{or} expression and a @code{let} expression.  The purpose of the
5547 @code{or} expression is to ensure that the argument @code{buffer} is
5548 bound to a buffer and not just the name of a buffer.  The body of the
5549 @code{let} expression contains the code which copies the other buffer
5550 into the current buffer.
5552 @need 1250
5553 In outline, the two expressions fit into the @code{insert-buffer}
5554 function like this:
5556 @smallexample
5557 @group
5558 (defun insert-buffer (buffer)
5559   "@var{documentation}@dots{}"
5560   (interactive "*bInsert buffer:@: ")
5561   (or @dots{}
5562       @dots{}
5563 @end group
5564 @group
5565   (let (@var{varlist})
5566       @var{body-of-}@code{let}@dots{} )
5567 @end group
5568 @end smallexample
5570 To understand how the @code{or} expression ensures that the argument
5571 @code{buffer} is bound to a buffer and not to the name of a buffer, it
5572 is first necessary to understand the @code{or} function.
5574 Before doing this, let me rewrite this part of the function using
5575 @code{if} so that you can see what is done in a manner that will be familiar.
5577 @node if & or, Insert or, insert-buffer body, insert-buffer
5578 @comment  node-name,  next,  previous,  up
5579 @subsection @code{insert-buffer} With an @code{if} Instead of an @code{or}
5581 The job to be done is to make sure the value of @code{buffer} is a
5582 buffer itself and not the name of a buffer.  If the value is the name,
5583 then the buffer itself must be got.
5585 You can imagine yourself at a conference where an usher is wandering
5586 around holding a list with your name on it and looking for you: the
5587 usher is ``bound'' to your name, not to you; but when the usher finds
5588 you and takes your arm, the usher becomes ``bound'' to you.
5590 @need 800
5591 In Lisp, you might describe this situation like this:
5593 @smallexample
5594 @group
5595 (if (not (holding-on-to-guest))
5596     (find-and-take-arm-of-guest))
5597 @end group
5598 @end smallexample
5600 We want to do the same thing with a buffer---if we do not have the
5601 buffer itself, we want to get it.
5603 @need 1200
5604 Using a predicate called @code{bufferp} that tells us whether we have a
5605 buffer (rather than its name), we can write the code like this:
5607 @smallexample
5608 @group
5609 (if (not (bufferp buffer))              ; @r{if-part}
5610     (setq buffer (get-buffer buffer)))  ; @r{then-part}
5611 @end group
5612 @end smallexample
5614 @noindent
5615 Here, the true-or-false-test of the @code{if} expression is
5616 @w{@code{(not (bufferp buffer))}}; and the then-part is the expression
5617 @w{@code{(setq buffer (get-buffer buffer))}}.
5619 In the test, the function @code{bufferp} returns true if its argument is
5620 a buffer---but false if its argument is the name of the buffer.  (The
5621 last character of the function name @code{bufferp} is the character
5622 @samp{p}; as we saw earlier, such use of @samp{p} is a convention that
5623 indicates that the function is a predicate, which is a term that means
5624 that the function will determine whether some property is true or false.
5625 @xref{Wrong Type of Argument, , Using the Wrong Type Object as an
5626 Argument}.)
5628 @need 1200
5629 The function @code{not} precedes the expression @code{(bufferp buffer)},
5630 so the true-or-false-test looks like this:
5632 @smallexample
5633 (not (bufferp buffer))
5634 @end smallexample
5636 @noindent
5637 @code{not} is a function that returns true if its argument is false
5638 and false if its argument is true.  So if @code{(bufferp buffer)}
5639 returns true, the @code{not} expression returns false and vice-versa:
5640 what is ``not true'' is false and what is ``not false'' is true.
5642 Using this test, the @code{if} expression works as follows: when the
5643 value of the variable @code{buffer} is actually a buffer rather than
5644 its name, the true-or-false-test returns false and the @code{if}
5645 expression does not evaluate the then-part.  This is fine, since we do
5646 not need to do anything to the variable @code{buffer} if it really is
5647 a buffer.
5649 On the other hand, when the value of @code{buffer} is not a buffer
5650 itself, but the name of a buffer, the true-or-false-test returns true
5651 and the then-part of the expression is evaluated.  In this case, the
5652 then-part is @code{(setq buffer (get-buffer buffer))}.  This
5653 expression uses the @code{get-buffer} function to return an actual
5654 buffer itself, given its name.  The @code{setq} then sets the variable
5655 @code{buffer} to the value of the buffer itself, replacing its previous
5656 value (which was the name of the buffer).
5658 @node Insert or, Insert let, if & or, insert-buffer
5659 @comment  node-name,  next,  previous,  up
5660 @subsection The @code{or} in the Body
5662 The purpose of the @code{or} expression in the @code{insert-buffer}
5663 function is to ensure that the argument @code{buffer} is bound to a
5664 buffer and not just to the name of a buffer.  The previous section shows
5665 how the job could have been done using an @code{if} expression.
5666 However, the @code{insert-buffer} function actually uses @code{or}.
5667 To understand this, it is necessary to understand how @code{or} works.
5669 @findex or
5670 An @code{or} function can have any number of arguments.  It evaluates
5671 each argument in turn and returns the value of the first of its
5672 arguments that is not @code{nil}.  Also, and this is a crucial feature
5673 of @code{or}, it does not evaluate any subsequent arguments after
5674 returning the first non-@code{nil} value.
5676 @need 800
5677 The @code{or} expression looks like this:
5679 @smallexample
5680 @group
5681 (or (bufferp buffer)
5682     (setq buffer (get-buffer buffer)))
5683 @end group
5684 @end smallexample
5686 @noindent
5687 The first argument to @code{or} is the expression @code{(bufferp buffer)}.
5688 This expression returns true (a non-@code{nil} value) if the buffer is
5689 actually a buffer, and not just the name of a buffer.  In the @code{or}
5690 expression, if this is the case, the @code{or} expression returns this
5691 true value and does not evaluate the next expression---and this is fine
5692 with us, since we do not want to do anything to the value of
5693 @code{buffer} if it really is a buffer.
5695 On the other hand, if the value of @code{(bufferp buffer)} is @code{nil},
5696 which it will be if the value of @code{buffer} is the name of a buffer,
5697 the Lisp interpreter evaluates the next element of the @code{or}
5698 expression.  This is the expression @code{(setq buffer (get-buffer
5699 buffer))}.  This expression returns a non-@code{nil} value, which
5700 is the value to which it sets the variable @code{buffer}---and this
5701 value is a buffer itself, not the name of a buffer.
5703 The result of all this is that the symbol @code{buffer} is always
5704 bound to a buffer itself rather than to the name of a buffer.  All
5705 this is necessary because the @code{set-buffer} function in a
5706 following line only works with a buffer itself, not with the name to a
5707 buffer.
5709 @need 1250
5710 Incidentally, using @code{or}, the situation with the usher would be
5711 written like this:
5713 @smallexample
5714 (or (holding-on-to-guest) (find-and-take-arm-of-guest))
5715 @end smallexample
5717 @node Insert let,  , Insert or, insert-buffer
5718 @comment  node-name,  next,  previous,  up
5719 @subsection The @code{let} Expression in @code{insert-buffer}
5721 After ensuring that the variable @code{buffer} refers to a buffer itself
5722 and not just to the name of a buffer, the @code{insert-buffer function}
5723 continues with a @code{let} expression.  This specifies three local
5724 variables, @code{start}, @code{end}, and @code{newmark} and binds them
5725 to the initial value @code{nil}.  These variables are used inside the
5726 remainder of the @code{let} and temporarily hide any other occurrence of
5727 variables of the same name in Emacs until the end of the @code{let}.
5729 @need 1200
5730 The body of the @code{let} contains two @code{save-excursion}
5731 expressions.  First, we will look at the inner @code{save-excursion}
5732 expression in detail.  The expression looks like this:
5734 @smallexample
5735 @group
5736 (save-excursion
5737   (set-buffer buffer)
5738   (setq start (point-min) end (point-max)))
5739 @end group
5740 @end smallexample
5742 @noindent
5743 The expression @code{(set-buffer buffer)} changes Emacs' attention
5744 from the current buffer to the one from which the text will copied.
5745 In that buffer, the variables @code{start} and @code{end} are set to
5746 the beginning and end of the buffer, using the commands
5747 @code{point-min} and @code{point-max}.  Note that we have here an
5748 illustration of how @code{setq} is able to set two variables in the
5749 same expression.  The first argument of @code{setq} is set to the
5750 value of its second, and its third argument is set to the value of its
5751 fourth.
5753 After the body of the inner @code{save-excursion} is evaluated, the
5754 @code{save-excursion} restores the original buffer, but @code{start} and
5755 @code{end} remain set to the values of the beginning and end of the
5756 buffer from which the text will be copied.
5758 @need 1250
5759 The outer @code{save-excursion} expression looks like this:
5761 @smallexample
5762 @group
5763 (save-excursion
5764   (@var{inner-}@code{save-excursion}@var{-expression}
5765      (@var{go-to-new-buffer-and-set-}@code{start}@var{-and-}@code{end})
5766   (insert-buffer-substring buffer start end)
5767   (setq newmark (point)))
5768 @end group
5769 @end smallexample
5771 @noindent
5772 The @code{insert-buffer-substring} function copies the text
5773 @emph{into} the current buffer @emph{from} the region indicated by
5774 @code{start} and @code{end} in @code{buffer}.  Since the whole of the
5775 second buffer lies between @code{start} and @code{end}, the whole of
5776 the second buffer is copied into the buffer you are editing.  Next,
5777 the value of point, which will be at the end of the inserted text, is
5778 recorded in the variable @code{newmark}.
5780 After the body of the outer @code{save-excursion} is evaluated, point
5781 and mark are relocated to their original places.
5783 However, it is convenient to locate a mark at the end of the newly
5784 inserted text and locate point at its beginning.  The @code{newmark}
5785 variable records the end of the inserted text.  In the last line of
5786 the @code{let} expression, the @code{(push-mark newmark)} expression
5787 function sets a mark to this location.  (The previous location of the
5788 mark is still accessible; it is recorded on the mark ring and you can
5789 go back to it with @kbd{C-u C-@key{SPC}}.)  Meanwhile, point is
5790 located at the beginning of the inserted text, which is where it was
5791 before you called the insert function, the position of which was saved
5792 by the first @code{save-excursion}.
5794 @need 1250
5795 The whole @code{let} expression looks like this:
5797 @smallexample
5798 @group
5799 (let (start end newmark)
5800   (save-excursion
5801     (save-excursion
5802       (set-buffer buffer)
5803       (setq start (point-min) end (point-max)))
5804     (insert-buffer-substring buffer start end)
5805     (setq newmark (point)))
5806   (push-mark newmark))
5807 @end group
5808 @end smallexample
5810 Like the @code{append-to-buffer} function, the @code{insert-buffer}
5811 function uses @code{let}, @code{save-excursion}, and
5812 @code{set-buffer}.  In addition, the function illustrates one way to
5813 use @code{or}.  All these functions are building blocks that we will
5814 find and use again and again.
5816 @node beginning-of-buffer, Second Buffer Related Review, insert-buffer, More Complex
5817 @comment  node-name,  next,  previous,  up
5818 @section Complete Definition of @code{beginning-of-buffer}
5819 @findex beginning-of-buffer
5821 The basic structure of the @code{beginning-of-buffer} function has
5822 already been discussed.  (@xref{simplified-beginning-of-buffer, , A
5823 Simplified @code{beginning-of-buffer} Definition}.)
5824 This section describes the complex part of the definition.
5826 As previously described, when invoked without an argument,
5827 @code{beginning-of-buffer} moves the cursor to the beginning of the
5828 buffer, leaving the mark at the previous position.  However, when the
5829 command is invoked with a number between one and ten, the function
5830 considers that number to be a fraction of the length of the buffer,
5831 measured in tenths, and Emacs moves the cursor that fraction of the way
5832 from the beginning of the buffer.  Thus, you can either call this
5833 function with the key command @kbd{M-<}, which will move the cursor to
5834 the beginning of the buffer, or with a key command such as @kbd{C-u 7
5835 M-<} which will move the cursor to a point 70% of the way through the
5836 buffer.  If a number bigger than ten is used for the argument, it moves
5837 to the end of the buffer.
5839 The @code{beginning-of-buffer} function can be called with or without an
5840 argument.  The use of the argument is optional.
5842 @menu
5843 * Optional Arguments::
5844 * beginning-of-buffer opt arg::  Example with optional argument.
5845 * beginning-of-buffer complete::
5846 @end menu
5848 @node Optional Arguments, beginning-of-buffer opt arg, beginning-of-buffer, beginning-of-buffer
5849 @subsection Optional Arguments
5851 Unless told otherwise, Lisp expects that a function with an argument in
5852 its function definition will be called with a value for that argument.
5853 If that does not happen, you get an error and a message that says
5854 @samp{Wrong number of arguments}.
5856 @cindex Optional arguments
5857 @cindex Keyword
5858 @findex optional
5859 However, optional arguments are a feature of Lisp: a @dfn{keyword} may
5860 be used to tell the Lisp interpreter that an argument is optional.
5861 The keyword is @code{&optional}.  (The @samp{&} in front of
5862 @samp{optional} is part of the keyword.)  In a function definition, if
5863 an argument follows the keyword @code{&optional}, a value does not
5864 need to be passed to that argument when the function is called.
5866 @need 1200
5867 The first line of the function definition of @code{beginning-of-buffer}
5868 therefore looks like this:
5870 @smallexample
5871 (defun beginning-of-buffer (&optional arg)
5872 @end smallexample
5874 @need 1250
5875 In outline, the whole function looks like this:
5877 @smallexample
5878 @group
5879 (defun beginning-of-buffer (&optional arg)
5880   "@var{documentation}@dots{}"
5881   (interactive "P")
5882   (push-mark)
5883   (goto-char
5884     (@var{if-there-is-an-argument}
5885         @var{figure-out-where-to-go}
5886       @var{else-go-to}
5887       (point-min))))
5888 @end group
5889 @end smallexample
5891 The function is similar to the @code{simplified-beginning-of-buffer}
5892 function except that the @code{interactive} expression has @code{"P"}
5893 as an argument and the @code{goto-char} function is followed by an
5894 if-then-else expression that figures out where to put the cursor if
5895 there is an argument.
5897 The @code{"P"} in the @code{interactive} expression tells Emacs to pass
5898 a prefix argument, if there is one, to the function.  A prefix argument
5899 is made by typing the @key{META} key followed by a number, or by typing
5900 @kbd{C-u} and then a number (if you don't type a number, @kbd{C-u}
5901 defaults to 4).
5903 The true-or-false-test of the @code{if} expression is simple: it is
5904 simply the argument @code{arg}.  If @code{arg} has a value that is not
5905 @code{nil}, which will be the case if @code{beginning-of-buffer} is
5906 called with an argument, then this true-or-false-test will return true
5907 and the then-part of the @code{if} expression will be evaluated.  On the
5908 other hand, if @code{beginning-of-buffer} is not called with an
5909 argument, the value of @code{arg} will be @code{nil} and the else-part
5910 of the @code{if} expression will be evaluated.  The else-part is simply
5911 @code{point-min}, and when this is the outcome, the whole
5912 @code{goto-char} expression is @code{(goto-char (point-min))}, which is
5913 how we saw the @code{beginning-of-buffer} function in its simplified
5914 form.
5916 @node beginning-of-buffer opt arg, beginning-of-buffer complete, Optional Arguments, beginning-of-buffer
5917 @subsection @code{beginning-of-buffer} with an Argument
5919 When @code{beginning-of-buffer} is called with an argument, an
5920 expression is evaluated which calculates what value to pass to
5921 @code{goto-char}.  This expression is rather complicated at first sight.
5922 It includes an inner @code{if} expression and much arithmetic.  It looks
5923 like this:
5925 @smallexample
5926 @group
5927 (if (> (buffer-size) 10000)
5928     ;; @r{Avoid overflow for large buffer sizes!}
5929     (* (prefix-numeric-value arg) (/ (buffer-size) 10))
5930   (/
5931    (+ 10
5932       (*
5933        (buffer-size) (prefix-numeric-value arg))) 10))
5934 @end group
5935 @end smallexample
5937 @menu
5938 * Disentangle beginning-of-buffer::
5939 * Large buffer case::
5940 * Small buffer case::
5941 @end menu
5943 @node Disentangle beginning-of-buffer, Large buffer case, beginning-of-buffer opt arg, beginning-of-buffer opt arg
5944 @ifnottex
5945 @unnumberedsubsubsec Disentangle @code{beginning-of-buffer}
5946 @end ifnottex
5948 Like other complex-looking expressions, the conditional expression
5949 within @code{beginning-of-buffer} can be disentangled by looking at it
5950 as parts of a template, in this case, the template for an if-then-else
5951 expression.  In skeletal form, the expression looks like this:
5953 @smallexample
5954 @group
5955 (if (@var{buffer-is-large}
5956     @var{divide-buffer-size-by-10-and-multiply-by-arg}
5957   @var{else-use-alternate-calculation}
5958 @end group
5959 @end smallexample
5961 The true-or-false-test of this inner @code{if} expression checks the
5962 size of the buffer.  The reason for this is that the old Version 18
5963 Emacs used numbers that are no bigger than eight million or so
5964 and in the computation that followed, the programmer feared that Emacs
5965 might try to use over-large numbers if the buffer were large.  The
5966 term `overflow', mentioned in the comment, means numbers that are over
5967 large.  Version 21 Emacs uses larger numbers, but this code has not
5968 been touched, if only because people now look at buffers that are far,
5969 far larger than ever before.
5971 There are two cases:  if the buffer is large and if it is not.
5973 @node Large buffer case, Small buffer case, Disentangle beginning-of-buffer, beginning-of-buffer opt arg
5974 @comment  node-name,  next,  previous,  up
5975 @unnumberedsubsubsec What happens in a large buffer
5977 In @code{beginning-of-buffer}, the inner @code{if} expression tests
5978 whether the size of the buffer is greater than 10,000 characters.  To do
5979 this, it uses the @code{>} function and the @code{buffer-size} function.
5981 @need 800
5982 The line looks like this:
5984 @smallexample
5985 (if (> (buffer-size) 10000)
5986 @end smallexample
5988 @need 1200
5989 @noindent
5990 When the buffer is large, the then-part of the @code{if} expression is
5991 evaluated.  It reads like this (after formatting for easy reading):
5993 @smallexample
5994 @group
5996   (prefix-numeric-value arg)
5997   (/ (buffer-size) 10))
5998 @end group
5999 @end smallexample
6001 @noindent
6002 This expression is a multiplication, with two arguments to the function
6003 @code{*}.
6005 The first argument is @code{(prefix-numeric-value arg)}.  When
6006 @code{"P"} is used as the argument for @code{interactive}, the value
6007 passed to the function as its argument is passed a ``raw prefix
6008 argument'', and not a number.  (It is a number in a list.)  To perform
6009 the arithmetic, a conversion is necessary, and
6010 @code{prefix-numeric-value} does the job.
6012 @findex / @r{(division)}
6013 @cindex Division
6014 The second argument is @code{(/ (buffer-size) 10)}.  This expression
6015 divides the numeric value of the buffer by ten.  This produces a number
6016 that tells how many characters make up one tenth of the buffer size.
6017 (In Lisp, @code{/} is used for division, just as @code{*} is
6018 used for multiplication.)
6020 @need 1200
6021 In the multiplication expression as a whole, this amount is multiplied
6022 by the value of the prefix argument---the multiplication looks like this:
6024 @smallexample
6025 @group
6026 (* @var{numeric-value-of-prefix-arg}
6027    @var{number-of-characters-in-one-tenth-of-the-buffer})
6028 @end group
6029 @end smallexample
6031 @noindent
6032 If, for example, the prefix argument is @samp{7}, the one-tenth value
6033 will be multiplied by 7 to give a position 70% of the way through the
6034 buffer.
6036 @need 1200
6037 The result of all this is that if the buffer is large, the
6038 @code{goto-char} expression reads like this:
6040 @smallexample
6041 @group
6042 (goto-char (* (prefix-numeric-value arg)
6043               (/ (buffer-size) 10)))
6044 @end group
6045 @end smallexample
6047 This puts the cursor where we want it.
6049 @node Small buffer case,  , Large buffer case, beginning-of-buffer opt arg
6050 @comment  node-name,  next,  previous,  up
6051 @unnumberedsubsubsec What happens in a small buffer
6053 If the buffer contains fewer than 10,000 characters, a slightly
6054 different computation is performed.  You might think this is not
6055 necessary, since the first computation could do the job.  However, in
6056 a small buffer, the first method may not put the cursor on exactly the
6057 desired line; the second method does a better job.
6059 @need 800
6060 The code looks like this:
6062 @c Keep this on one line.
6063 @smallexample
6064 (/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10))
6065 @end smallexample
6067 @need 1200
6068 @noindent
6069 This is code in which you figure out what happens by discovering how the
6070 functions are embedded in parentheses.  It is easier to read if you
6071 reformat it with each expression indented more deeply than its
6072 enclosing expression:
6074 @smallexample
6075 @group
6076   (/
6077    (+ 10
6078       (*
6079        (buffer-size)
6080        (prefix-numeric-value arg)))
6081    10))
6082 @end group
6083 @end smallexample
6085 @need 1200
6086 @noindent
6087 Looking at parentheses, we see that the innermost operation is
6088 @code{(prefix-numeric-value arg)}, which converts the raw argument to a
6089 number.  This number is multiplied by the buffer size in the following
6090 expression:
6092 @smallexample
6093 (* (buffer-size) (prefix-numeric-value arg))
6094 @end smallexample
6096 @noindent
6097 This multiplication creates a number that may be larger than the size of
6098 the buffer---seven times larger if the argument is 7, for example.  Ten
6099 is then added to this number and finally the large number is divided by
6100 ten to provide a value that is one character larger than the percentage
6101 position in the buffer.
6103 The number that results from all this is passed to @code{goto-char} and
6104 the cursor is moved to that point.
6106 @need 1500
6107 @node beginning-of-buffer complete,  , beginning-of-buffer opt arg, beginning-of-buffer
6108 @comment  node-name,  next,  previous,  up
6109 @subsection The Complete @code{beginning-of-buffer}
6111 @need 1000
6112 Here is the complete text of the @code{beginning-of-buffer} function:
6113 @sp 1
6115 @smallexample
6116 @group
6117 (defun beginning-of-buffer (&optional arg)
6118   "Move point to the beginning of the buffer;
6119 leave mark at previous position.
6120 With arg N, put point N/10 of the way
6121 from the true beginning.
6122 @end group
6123 @group
6124 Don't use this in Lisp programs!
6125 \(goto-char (point-min)) is faster
6126 and does not set the mark."
6127   (interactive "P")
6128   (push-mark)
6129 @end group
6130 @group
6131   (goto-char
6132    (if arg
6133        (if (> (buffer-size) 10000)
6134            ;; @r{Avoid overflow for large buffer sizes!}
6135            (* (prefix-numeric-value arg)
6136               (/ (buffer-size) 10))
6137 @end group
6138 @group
6139          (/ (+ 10 (* (buffer-size)
6140                      (prefix-numeric-value arg)))
6141             10))
6142      (point-min)))
6143   (if arg (forward-line 1)))
6144 @end group
6145 @end smallexample
6147 @noindent
6148 Except for two small points, the previous discussion shows how this
6149 function works.  The first point deals with a detail in the
6150 documentation string, and the second point concerns the last line of
6151 the function.
6153 @need 800
6154 In the documentation string, there is reference to an expression:
6156 @smallexample
6157 \(goto-char (point-min))
6158 @end smallexample
6160 @noindent
6161 A @samp{\} is used before the first parenthesis of this expression.
6162 This @samp{\} tells the Lisp interpreter that the expression should be
6163 printed as shown in the documentation rather than evaluated as a
6164 symbolic expression, which is what it looks like.
6166 @need 1200
6167 Finally, the last line of the @code{beginning-of-buffer} command says to
6168 move point to the beginning of the next line if the command is
6169 invoked with an argument:
6171 @smallexample
6172 (if arg (forward-line 1)))
6173 @end smallexample
6175 @noindent
6176 This puts the cursor at the beginning of the first line after the
6177 appropriate tenths position in the buffer.  This is a flourish that
6178 means that the cursor is always located @emph{at least} the requested
6179 tenths of the way through the buffer, which is a nicety that is,
6180 perhaps, not necessary, but which, if it did not occur, would be sure to
6181 draw complaints.
6183 @node Second Buffer Related Review, optional Exercise, beginning-of-buffer, More Complex
6184 @comment  node-name,  next,  previous,  up
6185 @section Review
6187 Here is a brief summary of some of the topics covered in this chapter.
6189 @table @code
6190 @item or
6191 Evaluate each argument in sequence, and return the value of the first
6192 argument that is not @code{nil}; if none return a value that is not
6193 @code{nil}, return @code{nil}.  In brief, return the first true value
6194 of the arguments; return a true value if one @emph{or} any of the
6195 other are true.
6197 @item and
6198 Evaluate each argument in sequence, and if any are @code{nil}, return
6199 @code{nil}; if none are @code{nil}, return the value of the last
6200 argument.  In brief, return a true value only if all the arguments are
6201 true; return a true value if one @emph{and} each of the others is
6202 true.
6204 @item &optional
6205 A keyword used to indicate that an argument to a function definition
6206 is optional; this means that the function can be evaluated without the
6207 argument, if desired.
6209 @item prefix-numeric-value
6210 Convert the `raw prefix argument' produced by @code{(interactive
6211 "P")} to a numeric value.
6213 @item forward-line
6214 Move point forward to the beginning of the next line, or if the argument
6215 is greater than one, forward that many lines.  If it can't move as far
6216 forward as it is supposed to, @code{forward-line} goes forward as far as
6217 it can and then returns a count of the number of additional lines it was
6218 supposed to move but couldn't.
6220 @item erase-buffer
6221 Delete the entire contents of the current buffer.
6223 @item bufferp
6224 Return @code{t} if its argument is a buffer; otherwise return @code{nil}.
6225 @end table
6227 @node optional Exercise,  , Second Buffer Related Review, More Complex
6228 @section @code{optional} Argument Exercise
6230 Write an interactive function with an optional argument that tests
6231 whether its argument, a number, is greater than or equal to, or else,
6232 less than the value of @code{fill-column}, and tells you which, in a
6233 message.  However, if you do not pass an argument to the function, use
6234 56 as a default value.
6236 @node Narrowing & Widening, car cdr & cons, More Complex, Top
6237 @comment  node-name,  next,  previous,  up
6238 @chapter Narrowing and Widening
6239 @cindex Focusing attention (narrowing)
6240 @cindex Narrowing
6241 @cindex Widening
6243 Narrowing is a feature of Emacs that makes it possible for you to focus
6244 on a specific part of a buffer, and work without accidentally changing
6245 other parts.  Narrowing is normally disabled since it can confuse
6246 novices.
6248 @menu
6249 * Narrowing advantages::        The advantages of narrowing
6250 * save-restriction::            The @code{save-restriction} special form.
6251 * what-line::                   The number of the line that point is on.
6252 * narrow Exercise::
6253 @end menu
6255 @node Narrowing advantages, save-restriction, Narrowing & Widening, Narrowing & Widening
6256 @ifnottex
6257 @unnumberedsec The Advantages of Narrowing
6258 @end ifnottex
6260 With narrowing, the rest of a buffer is made invisible, as if it weren't
6261 there.  This is an advantage if, for example, you want to replace a word
6262 in one part of a buffer but not in another: you narrow to the part you want
6263 and the replacement is carried out only in that section, not in the rest
6264 of the buffer.  Searches will only work within a narrowed region, not
6265 outside of one, so if you are fixing a part of a document, you can keep
6266 yourself from accidentally finding parts you do not need to fix by
6267 narrowing just to the region you want.
6268 (The key binding for @code{narrow-to-region} is @kbd{C-x n n}.)
6270 However, narrowing does make the rest of the buffer invisible, which
6271 can scare people who inadvertently invoke narrowing and think they
6272 have deleted a part of their file.  Moreover, the @code{undo} command
6273 (which is usually bound to @kbd{C-x u}) does not turn off narrowing
6274 (nor should it), so people can become quite desperate if they do not
6275 know that they can return the rest of a buffer to visibility with the
6276 @code{widen} command.
6277 (The key binding for @code{widen} is @kbd{C-x n w}.)
6279 Narrowing is just as useful to the Lisp interpreter as to a human.
6280 Often, an Emacs Lisp function is designed to work on just part of a
6281 buffer; or conversely, an Emacs Lisp function needs to work on all of a
6282 buffer that has been narrowed.  The @code{what-line} function, for
6283 example, removes the narrowing from a buffer, if it has any narrowing
6284 and when it has finished its job, restores the narrowing to what it was.
6285 On the other hand, the @code{count-lines} function, which is called by
6286 @code{what-line}, uses narrowing to restrict itself to just that portion
6287 of the buffer in which it is interested and then restores the previous
6288 situation.
6290 @node save-restriction, what-line, Narrowing advantages, Narrowing & Widening
6291 @comment  node-name,  next,  previous,  up
6292 @section The @code{save-restriction} Special Form
6293 @findex save-restriction
6295 In Emacs Lisp, you can use the @code{save-restriction} special form to
6296 keep track of whatever narrowing is in effect, if any.  When the Lisp
6297 interpreter meets with @code{save-restriction}, it executes the code
6298 in the body of the @code{save-restriction} expression, and then undoes
6299 any changes to narrowing that the code caused.  If, for example, the
6300 buffer is narrowed and the code that follows @code{save-restriction}
6301 gets rid of the narrowing, @code{save-restriction} returns the buffer
6302 to its narrowed region afterwards.  In the @code{what-line} command,
6303 any narrowing the buffer may have is undone by the @code{widen}
6304 command that immediately follows the @code{save-restriction} command.
6305 Any original narrowing is restored just before the completion of the
6306 function.
6308 @need 1250
6309 The template for a @code{save-restriction} expression is simple:
6311 @smallexample
6312 @group
6313 (save-restriction
6314   @var{body}@dots{} )
6315 @end group
6316 @end smallexample
6318 @noindent
6319 The body of the @code{save-restriction} is one or more expressions that
6320 will be evaluated in sequence by the Lisp interpreter.
6322 Finally, a point to note: when you use both @code{save-excursion} and
6323 @code{save-restriction}, one right after the other, you should use
6324 @code{save-excursion} outermost.  If you write them in reverse order,
6325 you may fail to record narrowing in the buffer to which Emacs switches
6326 after calling @code{save-excursion}.  Thus, when written together,
6327 @code{save-excursion} and @code{save-restriction} should be written
6328 like this:
6330 @smallexample
6331 @group
6332 (save-excursion
6333   (save-restriction
6334     @var{body}@dots{}))
6335 @end group
6336 @end smallexample
6338 In other circumstances, when not written together, the
6339 @code{save-excursion} and @code{save-restriction} special forms must
6340 be written in the order appropriate to the function.
6342 @need 1250
6343 For example,
6345 @smallexample
6346 @group
6347   (save-restriction
6348     (widen)
6349     (save-excursion
6350     @var{body}@dots{}))
6351 @end group
6352 @end smallexample
6354 @node what-line, narrow Exercise, save-restriction, Narrowing & Widening
6355 @comment  node-name,  next,  previous,  up
6356 @section @code{what-line}
6357 @findex what-line
6358 @cindex Widening, example of
6360 The @code{what-line} command tells you the number of the line in which
6361 the cursor is located.  The function illustrates the use of the
6362 @code{save-restriction} and @code{save-excursion} commands.  Here is the
6363 original text of the function:
6365 @smallexample
6366 @group
6367 (defun what-line ()
6368   "Print the current line number (in the buffer) of point."
6369   (interactive)
6370   (save-restriction
6371     (widen)
6372     (save-excursion
6373       (beginning-of-line)
6374       (message "Line %d"
6375                (1+ (count-lines 1 (point)))))))
6376 @end group
6377 @end smallexample
6379 (In recent versions of GNU Emacs, the @code{what-line} function has
6380 been expanded to tell you your line number in a narrowed buffer as
6381 well as your line number in a widened buffer.  The recent version is
6382 more complex than the version shown here.  If you feel adventurous,
6383 you might want to look at it after figuring out how this version
6384 works.  The newer version uses a conditional to determine whether the
6385 buffer has been narrowed, and rather than use @code{beginning-of-line}
6386 to move point to the beginning of the current line, if need be, the
6387 function uses @code{(forward-line 0)}.)
6389 The function as shown here has a documentation line and is
6390 interactive, as you would expect.  The next two lines use the
6391 functions @code{save-restriction} and @code{widen}.
6393 The @code{save-restriction} special form notes whatever narrowing is in
6394 effect, if any, in the current buffer and restores that narrowing after
6395 the code in the body of the @code{save-restriction} has been evaluated.
6397 The @code{save-restriction} special form is followed by @code{widen}.
6398 This function undoes any narrowing the current buffer may have had
6399 when @code{what-line} was called.  (The narrowing that was there is
6400 the narrowing that @code{save-restriction} remembers.)  This widening
6401 makes it possible for the line counting commands to count from the
6402 beginning of the buffer.  Otherwise, they would have been limited to
6403 counting within the accessible region.  Any original narrowing is
6404 restored just before the completion of the function by the
6405 @code{save-restriction} special form.
6407 The call to @code{widen} is followed by @code{save-excursion}, which
6408 saves the location of the cursor (i.e., of point) and of the mark, and
6409 restores them after the code in the body of the @code{save-excursion}
6410 uses the @code{beginning-of-line} function to move point.
6412 (Note that the @code{(widen)} expression comes between the
6413 @code{save-restriction} and @code{save-excursion} special forms.  When
6414 you write the two @code{save- @dots{}} expressions in sequence, write
6415 @code{save-excursion} outermost.)
6417 @need 1200
6418 The last two lines of the @code{what-line} function are functions to
6419 count the number of lines in the buffer and then print the number in the
6420 echo area.
6422 @smallexample
6423 @group
6424 (message "Line %d"
6425          (1+ (count-lines 1 (point)))))))
6426 @end group
6427 @end smallexample
6429 The @code{message} function prints a one-line message at the bottom of the
6430 Emacs screen.  The first argument is inside of quotation marks and is
6431 printed as a string of characters.  However, it may contain @samp{%d},
6432 @samp{%s}, or @samp{%c} to print arguments that follow the string.
6433 @samp{%d} prints the argument as a decimal, so the message will say
6434 something such as @samp{Line 243}.
6436 @need 1200
6438 The number that is printed in place of the @samp{%d} is computed by the
6439 last line of the function:
6441 @smallexample
6442 (1+ (count-lines 1 (point)))
6443 @end smallexample
6445 @noindent
6446 What this does is count the lines from the first position of the
6447 buffer, indicated by the @code{1}, up to @code{(point)}, and then add
6448 one to that number.  (The @code{1+} function adds one to its
6449 argument.)  We add one to it because line 2 has only one line before
6450 it, and @code{count-lines} counts only the lines @emph{before} the
6451 current line.
6453 After @code{count-lines} has done its job, and the message has been
6454 printed in the echo area, the @code{save-excursion} restores point and
6455 mark to their original positions; and @code{save-restriction} restores
6456 the original narrowing, if any.
6458 @node narrow Exercise,  , what-line, Narrowing & Widening
6459 @section Exercise with Narrowing
6461 Write a function that will display the first 60 characters of the
6462 current buffer, even if you have narrowed the buffer to its latter
6463 half so that the first line is inaccessible.  Restore point, mark, and
6464 narrowing.  For this exercise, you need to use a whole potpourri of
6465 functions, including @code{save-restriction}, @code{widen},
6466 @code{goto-char}, @code{point-min}, @code{message}, and
6467 @code{buffer-substring}.
6469 @cindex Properties, mention of @code{buffer-substring-no-properties}
6470 (@code{buffer-substring} is a previously unmentioned function you will
6471 have to investigate yourself; or perhaps you will have to use
6472 @code{buffer-substring-no-properties} @dots{}, yet another function
6473 and one that introduces text properties, a feature otherwise not
6474 discussed here.  @xref{Text Properties, , Text Properties, elisp, The
6475 GNU Emacs Lisp Reference Manual}.  Additionally, do you really need
6476 @code{goto-char} or @code{point-min}?  Or can you write the function
6477 without them?)
6479 @node car cdr & cons, Cutting & Storing Text, Narrowing & Widening, Top
6480 @comment  node-name,  next,  previous,  up
6481 @chapter @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
6482 @findex car, @r{introduced}
6483 @findex cdr, @r{introduced}
6485 In Lisp, @code{car}, @code{cdr}, and @code{cons} are fundamental
6486 functions.  The @code{cons} function is used to construct lists, and
6487 the @code{car} and @code{cdr} functions are used to take them apart.
6489 In the walk through of the @code{copy-region-as-kill} function, we
6490 will see @code{cons} as well as two variants on @code{cdr},
6491 namely, @code{setcdr} and @code{nthcdr}.  (@xref{copy-region-as-kill}.)
6493 @menu
6494 * Strange Names::               An historical aside: why the strange names?
6495 * car & cdr::                   Functions for extracting part of a list.
6496 * cons::                        Constructing a list.
6497 * nthcdr::                      Calling @code{cdr} repeatedly.
6498 * nth::
6499 * setcar::                      Changing the first element of a list.
6500 * setcdr::                      Changing the rest of a list.
6501 * cons Exercise::
6502 @end menu
6504 @node Strange Names, car & cdr, car cdr & cons, car cdr & cons
6505 @ifnottex
6506 @unnumberedsec Strange Names
6507 @end ifnottex
6509 The name of the @code{cons} function is not unreasonable: it is an
6510 abbreviation of the word `construct'.  The origins of the names for
6511 @code{car} and @code{cdr}, on the other hand, are esoteric: @code{car}
6512 is an acronym from the phrase `Contents of the Address part of the
6513 Register'; and @code{cdr} (pronounced `could-er') is an acronym from
6514 the phrase `Contents of the Decrement part of the Register'.  These
6515 phrases refer to specific pieces of hardware on the very early
6516 computer on which the original Lisp was developed.  Besides being
6517 obsolete, the phrases have been completely irrelevant for more than 25
6518 years to anyone thinking about Lisp.  Nonetheless, although a few
6519 brave scholars have begun to use more reasonable names for these
6520 functions, the old terms are still in use.  In particular, since the
6521 terms are used in the Emacs Lisp source code, we will use them in this
6522 introduction.
6524 @node car & cdr, cons, Strange Names, car cdr & cons
6525 @comment  node-name,  next,  previous,  up
6526 @section @code{car} and @code{cdr}
6528 The @sc{car} of a list is, quite simply, the first item in the list.
6529 Thus the @sc{car} of the list @code{(rose violet daisy buttercup)} is
6530 @code{rose}.
6532 @need 1200
6533 If you are reading this in Info in GNU Emacs, you can see this by
6534 evaluating the following:
6536 @smallexample
6537 (car '(rose violet daisy buttercup))
6538 @end smallexample
6540 @noindent
6541 After evaluating the expression, @code{rose} will appear in the echo
6542 area.
6544 Clearly, a more reasonable name for the @code{car} function would be
6545 @code{first} and this is often suggested.
6547 @code{car} does not remove the first item from the list; it only reports
6548 what it is.  After @code{car} has been applied to a list, the list is
6549 still the same as it was.  In the jargon, @code{car} is
6550 `non-destructive'.  This feature turns out to be important.
6552 The @sc{cdr} of a list is the rest of the list, that is, the
6553 @code{cdr} function returns the part of the list that follows the
6554 first item.  Thus, while the @sc{car} of the list @code{'(rose violet
6555 daisy buttercup)} is @code{rose}, the rest of the list, the value
6556 returned by the @code{cdr} function, is @code{(violet daisy
6557 buttercup)}.
6559 @need 800
6560 You can see this by evaluating the following in the usual way:
6562 @smallexample
6563 (cdr '(rose violet daisy buttercup))
6564 @end smallexample
6566 @noindent
6567 When you evaluate this, @code{(violet daisy buttercup)} will appear in
6568 the echo area.
6570 Like @code{car}, @code{cdr} does not remove any elements from the
6571 list---it just returns a report of what the second and subsequent
6572 elements are.
6574 Incidentally, in the example, the list of flowers is quoted.  If it were
6575 not, the Lisp interpreter would try to evaluate the list by calling
6576 @code{rose} as a function.  In this example, we do not want to do that.
6578 Clearly, a more reasonable name for @code{cdr} would be @code{rest}.
6580 (There is a lesson here: when you name new functions, consider very
6581 carefully what you are doing, since you may be stuck with the names
6582 for far longer than you expect.  The reason this document perpetuates
6583 these names is that the Emacs Lisp source code uses them, and if I did
6584 not use them, you would have a hard time reading the code; but do,
6585 please, try to avoid using these terms yourself.  The people who come
6586 after you will be grateful to you.)
6588 When @code{car} and @code{cdr} are applied to a list made up of symbols,
6589 such as the list @code{(pine fir oak maple)}, the element of the list
6590 returned by the function @code{car} is the symbol @code{pine} without
6591 any parentheses around it.  @code{pine} is the first element in the
6592 list.  However, the @sc{cdr} of the list is a list itself, @code{(fir
6593 oak maple)}, as you can see by evaluating the following expressions in
6594 the usual way:
6596 @smallexample
6597 @group
6598 (car '(pine fir oak maple))
6600 (cdr '(pine fir oak maple))
6601 @end group
6602 @end smallexample
6604 On the other hand, in a list of lists, the first element is itself a
6605 list.  @code{car} returns this first element as a list.  For example,
6606 the following list contains three sub-lists, a list of carnivores, a
6607 list of herbivores and a list of sea mammals:
6609 @smallexample
6610 @group
6611 (car '((lion tiger cheetah)
6612        (gazelle antelope zebra)
6613        (whale dolphin seal)))
6614 @end group
6615 @end smallexample
6617 @noindent
6618 In this example, the first element or @sc{car} of the list is the list of
6619 carnivores, @code{(lion tiger cheetah)}, and the rest of the list is
6620 @code{((gazelle antelope zebra) (whale dolphin seal))}.
6622 @smallexample
6623 @group
6624 (cdr '((lion tiger cheetah)
6625        (gazelle antelope zebra)
6626        (whale dolphin seal)))
6627 @end group
6628 @end smallexample
6630 It is worth saying again that @code{car} and @code{cdr} are
6631 non-destructive---that is, they do not modify or change lists to which
6632 they are applied.  This is very important for how they are used.
6634 Also, in the first chapter, in the discussion about atoms, I said that
6635 in Lisp, ``certain kinds of atom, such as an array, can be separated
6636 into parts; but the mechanism for doing this is different from the
6637 mechanism for splitting a list.  As far as Lisp is concerned, the
6638 atoms of a list are unsplittable.''  (@xref{Lisp Atoms}.)  The
6639 @code{car} and @code{cdr} functions are used for splitting lists and
6640 are considered fundamental to Lisp.  Since they cannot split or gain
6641 access to the parts of an array, an array is considered an atom.
6642 Conversely, the other fundamental function, @code{cons}, can put
6643 together or construct a list, but not an array.  (Arrays are handled
6644 by array-specific functions.  @xref{Arrays, , Arrays, elisp, The GNU
6645 Emacs Lisp Reference Manual}.)
6647 @node cons, nthcdr, car & cdr, car cdr & cons
6648 @comment  node-name,  next,  previous,  up
6649 @section @code{cons}
6650 @findex cons, @r{introduced}
6652 The @code{cons} function constructs lists; it is the inverse of
6653 @code{car} and @code{cdr}.  For example, @code{cons} can be used to make
6654 a four element list from the three element list, @code{(fir oak maple)}:
6656 @smallexample
6657 (cons 'pine '(fir oak maple))
6658 @end smallexample
6660 @need 800
6661 @noindent
6662 After evaluating this list, you will see
6664 @smallexample
6665 (pine fir oak maple)
6666 @end smallexample
6668 @noindent
6669 appear in the echo area.  @code{cons} causes the creation of a new
6670 list in which the element is followed by the elements of the original
6671 list.
6673 We often say that `@code{cons} puts a new element at the beginning of
6674 a list; it attaches or pushes elements onto the list', but this
6675 phrasing can be misleading, since @code{cons} does not change an
6676 existing list, but creates a new one.
6678 Like @code{car} and @code{cdr}, @code{cons} is non-destructive.
6680 @menu
6681 * Build a list::
6682 * length::                      How to find the length of a list.
6683 @end menu
6685 @node Build a list, length, cons, cons
6686 @ifnottex
6687 @unnumberedsubsec Build a list
6688 @end ifnottex
6690 @code{cons} must have a list to attach to.@footnote{Actually, you can
6691 @code{cons} an element to an atom to produce a dotted pair.  Dotted
6692 pairs are not discussed here; see @ref{Dotted Pair Notation, , Dotted
6693 Pair Notation, elisp, The GNU Emacs Lisp Reference Manual}.}  You
6694 cannot start from absolutely nothing.  If you are building a list, you
6695 need to provide at least an empty list at the beginning.  Here is a
6696 series of @code{cons} expressions that build up a list of flowers.  If
6697 you are reading this in Info in GNU Emacs, you can evaluate each of
6698 the expressions in the usual way; the value is printed in this text
6699 after @samp{@result{}}, which you may read as `evaluates to'.
6701 @smallexample
6702 @group
6703 (cons 'buttercup ())
6704      @result{} (buttercup)
6705 @end group
6707 @group
6708 (cons 'daisy '(buttercup))
6709      @result{} (daisy buttercup)
6710 @end group
6712 @group
6713 (cons 'violet '(daisy buttercup))
6714      @result{} (violet daisy buttercup)
6715 @end group
6717 @group
6718 (cons 'rose '(violet daisy buttercup))
6719      @result{} (rose violet daisy buttercup)
6720 @end group
6721 @end smallexample
6723 @noindent
6724 In the first example, the empty list is shown as @code{()} and a list
6725 made up of @code{buttercup} followed by the empty list is constructed.
6726 As you can see, the empty list is not shown in the list that was
6727 constructed.  All that you see is @code{(buttercup)}.  The empty list is
6728 not counted as an element of a list because there is nothing in an empty
6729 list.  Generally speaking, an empty list is invisible.
6731 The second example, @code{(cons 'daisy '(buttercup))} constructs a new,
6732 two element list by putting @code{daisy} in front of @code{buttercup};
6733 and the third example constructs a three element list by putting
6734 @code{violet} in front of @code{daisy} and @code{buttercup}.
6736 @node length,  , Build a list, cons
6737 @comment  node-name,  next,  previous,  up
6738 @subsection Find the Length of a List: @code{length}
6739 @findex length
6741 You can find out how many elements there are in a list by using the Lisp
6742 function @code{length}, as in the following examples:
6744 @smallexample
6745 @group
6746 (length '(buttercup))
6747      @result{} 1
6748 @end group
6750 @group
6751 (length '(daisy buttercup))
6752      @result{} 2
6753 @end group
6755 @group
6756 (length (cons 'violet '(daisy buttercup)))
6757      @result{} 3
6758 @end group
6759 @end smallexample
6761 @noindent
6762 In the third example, the @code{cons} function is used to construct a
6763 three element list which is then passed to the @code{length} function as
6764 its argument.
6766 @need 1200
6767 We can also use @code{length} to count the number of elements in an
6768 empty list:
6770 @smallexample
6771 @group
6772 (length ())
6773      @result{} 0
6774 @end group
6775 @end smallexample
6777 @noindent
6778 As you would expect, the number of elements in an empty list is zero.
6780 An interesting experiment is to find out what happens if you try to find
6781 the length of no list at all; that is, if you try to call @code{length}
6782 without giving it an argument, not even an empty list:
6784 @smallexample
6785 (length )
6786 @end smallexample
6788 @need 800
6789 @noindent
6790 What you see, if you evaluate this, is the error message
6792 @smallexample
6793 Wrong number of arguments: #<subr length>, 0
6794 @end smallexample
6796 @noindent
6797 This means that the function receives the wrong number of
6798 arguments, zero, when it expects some other number of arguments.  In
6799 this case, one argument is expected, the argument being a list whose
6800 length the function is measuring.  (Note that @emph{one} list is
6801 @emph{one} argument, even if the list has many elements inside it.)
6803 The part of the error message that says @samp{#<subr length>} is the
6804 name of the function.  This is written with a special notation,
6805 @samp{#<subr}, that indicates that the function @code{length} is one
6806 of the primitive functions written in C rather than in Emacs Lisp.
6807 (@samp{subr} is an abbreviation for `subroutine'.)  @xref{What Is a
6808 Function, , What Is a Function?, elisp , The GNU Emacs Lisp Reference
6809 Manual}, for more about subroutines.
6811 @node nthcdr, nth, cons, car cdr & cons
6812 @comment  node-name,  next,  previous,  up
6813 @section @code{nthcdr}
6814 @findex nthcdr
6816 The @code{nthcdr} function is associated with the @code{cdr} function.
6817 What it does is take the @sc{cdr} of a list repeatedly.
6819 If you take the @sc{cdr} of the list @code{(pine fir
6820 oak maple)}, you will be returned the list @code{(fir oak maple)}.  If you
6821 repeat this on what was returned, you will be returned the list
6822 @code{(oak maple)}.  (Of course, repeated @sc{cdr}ing on the original
6823 list will just give you the original @sc{cdr} since the function does
6824 not change the list.  You need to evaluate the @sc{cdr} of the
6825 @sc{cdr} and so on.)  If you continue this, eventually you will be
6826 returned an empty list, which in this case, instead of being shown as
6827 @code{()} is shown as @code{nil}.
6829 @need 1200
6830 For review, here is a series of repeated @sc{cdr}s, the text following
6831 the @samp{@result{}} shows what is returned.
6833 @smallexample
6834 @group
6835 (cdr '(pine fir oak maple))
6836      @result{}(fir oak maple)
6837 @end group
6839 @group
6840 (cdr '(fir oak maple))
6841      @result{} (oak maple)
6842 @end group
6844 @group
6845 (cdr '(oak maple))
6846      @result{}(maple)
6847 @end group
6849 @group
6850 (cdr '(maple))
6851      @result{} nil
6852 @end group
6854 @group
6855 (cdr 'nil)
6856      @result{} nil
6857 @end group
6859 @group
6860 (cdr ())
6861      @result{} nil
6862 @end group
6863 @end smallexample
6865 @need 1200
6866 You can also do several @sc{cdr}s without printing the values in
6867 between, like this:
6869 @smallexample
6870 @group
6871 (cdr (cdr '(pine fir oak maple)))
6872      @result{} (oak maple)
6873 @end group
6874 @end smallexample
6876 @noindent
6877 In this example, the Lisp interpreter evaluates the innermost list first.
6878 The innermost list is quoted, so it just passes the list as it is to the
6879 innermost @code{cdr}.  This @code{cdr} passes a list made up of the
6880 second and subsequent elements of the list to the outermost @code{cdr},
6881 which produces a list composed of the third and subsequent elements of
6882 the original list.  In this example, the @code{cdr} function is repeated
6883 and returns a list that consists of the original list without its
6884 first two elements.
6886 The @code{nthcdr} function does the same as repeating the call to
6887 @code{cdr}.  In the following example, the argument 2 is passed to the
6888 function @code{nthcdr}, along with the list, and the value returned is
6889 the list without its first two items, which is exactly the same
6890 as repeating @code{cdr} twice on the list:
6892 @smallexample
6893 @group
6894 (nthcdr 2 '(pine fir oak maple))
6895      @result{} (oak maple)
6896 @end group
6897 @end smallexample
6899 @need 1200
6900 Using the original four element list, we can see what happens when
6901 various numeric arguments are passed to @code{nthcdr}, including 0, 1,
6902 and 5:
6904 @smallexample
6905 @group
6906 ;; @r{Leave the list as it was.}
6907 (nthcdr 0 '(pine fir oak maple))
6908      @result{} (pine fir oak maple)
6909 @end group
6911 @group
6912 ;; @r{Return a copy without the first element.}
6913 (nthcdr 1 '(pine fir oak maple))
6914      @result{} (fir oak maple)
6915 @end group
6917 @group
6918 ;; @r{Return a copy of the list without three elements.}
6919 (nthcdr 3 '(pine fir oak maple))
6920      @result{} (maple)
6921 @end group
6923 @group
6924 ;; @r{Return a copy lacking all four elements.}
6925 (nthcdr 4 '(pine fir oak maple))
6926      @result{} nil
6927 @end group
6929 @group
6930 ;; @r{Return a copy lacking all elements.}
6931 (nthcdr 5 '(pine fir oak maple))
6932      @result{} nil
6933 @end group
6934 @end smallexample
6936 @node nth, setcar, nthcdr, car cdr & cons
6937 @comment  node-name,  next,  previous,  up
6938 @section @code{nth}
6939 @findex nth
6941 The @code{nthcdr} function takes the @sc{cdr} of a list repeatedly.
6942 The @code{nth} function takes the @sc{car} of the result returned by
6943 @code{nthcdr}.  It returns the Nth element of the list.
6945 @need 1500
6946 Thus, if it were not defined in C for speed, the definition of
6947 @code{nth} would be:
6949 @smallexample
6950 @group
6951 (defun nth (n list)
6952   "Returns the Nth element of LIST.
6953 N counts from zero.  If LIST is not that long, nil is returned."
6954   (car (nthcdr n list)))
6955 @end group
6956 @end smallexample
6958 @noindent
6959 (Originally, @code{nth} was defined in Emacs Lisp in @file{subr.el},
6960 but its definition was redone in C in the 1980s.)
6962 The @code{nth} function returns a single element of a list.
6963 This can be very convenient.
6965 Note that the elements are numbered from zero, not one.  That is to
6966 say, the first element of a list, its @sc{car} is the zeroth element.
6967 This is called `zero-based' counting and often bothers people who
6968 are accustomed to the first element in a list being number one, which
6969 is `one-based'.
6971 @need 1250
6972 For example:
6974 @smallexample
6975 @group
6976 (nth 0 '("one" "two" "three"))
6977     @result{} "one"
6979 (nth 1 '("one" "two" "three"))
6980     @result{} "two"
6981 @end group
6982 @end smallexample
6984 It is worth mentioning that @code{nth}, like @code{nthcdr} and
6985 @code{cdr}, does not change the original list---the function is
6986 non-destructive.  This is in sharp contrast to the @code{setcar} and
6987 @code{setcdr} functions.
6989 @node setcar, setcdr, nth, car cdr & cons
6990 @comment  node-name,  next,  previous,  up
6991 @section @code{setcar}
6992 @findex setcar
6994 As you might guess from their names, the @code{setcar} and @code{setcdr}
6995 functions set the @sc{car} or the @sc{cdr} of a list to a new value.
6996 They actually change the original list, unlike @code{car} and @code{cdr}
6997 which leave the original list as it was.  One way to find out how this
6998 works is to experiment.  We will start with the @code{setcar} function.
7000 @need 1200
7001 First, we can make a list and then set the value of a variable to the
7002 list, using the @code{setq} function.  Here is a list of animals:
7004 @smallexample
7005 (setq animals '(antelope giraffe lion tiger))
7006 @end smallexample
7008 @noindent
7009 If you are reading this in Info inside of GNU Emacs, you can evaluate
7010 this expression in the usual fashion, by positioning the cursor after
7011 the expression and typing @kbd{C-x C-e}.  (I'm doing this right here as
7012 I write this.  This is one of the advantages of having the interpreter
7013 built into the computing environment.)
7015 @need 1200
7016 When we evaluate the variable @code{animals}, we see that it is bound to
7017 the list @code{(antelope giraffe lion tiger)}:
7019 @smallexample
7020 @group
7021 animals
7022      @result{} (antelope giraffe lion tiger)
7023 @end group
7024 @end smallexample
7026 @noindent
7027 Put another way, the variable @code{animals} points to the list
7028 @code{(antelope giraffe lion tiger)}.
7030 Next, evaluate the function @code{setcar} while passing it two
7031 arguments, the variable @code{animals} and the quoted symbol
7032 @code{hippopotamus}; this is done by writing the three element list
7033 @code{(setcar animals 'hippopotamus)} and then evaluating it in the
7034 usual fashion:
7036 @smallexample
7037 (setcar animals 'hippopotamus)
7038 @end smallexample
7040 @need 1200
7041 @noindent
7042 After evaluating this expression, evaluate the variable @code{animals}
7043 again.  You will see that the list of animals has changed:
7045 @smallexample
7046 @group
7047 animals
7048      @result{} (hippopotamus giraffe lion tiger)
7049 @end group
7050 @end smallexample
7052 @noindent
7053 The first element on the list, @code{antelope} is replaced by
7054 @code{hippopotamus}.
7056 So we can see that @code{setcar} did not add a new element to the list
7057 as @code{cons} would have; it replaced @code{giraffe} with
7058 @code{hippopotamus}; it @emph{changed} the list.
7060 @node setcdr, cons Exercise, setcar, car cdr & cons
7061 @comment  node-name,  next,  previous,  up
7062 @section @code{setcdr}
7063 @findex setcdr
7065 The @code{setcdr} function is similar to the @code{setcar} function,
7066 except that the function replaces the second and subsequent elements of
7067 a list rather than the first element.
7069 (To see how to change the last element of a list, look ahead to
7070 @ref{kill-new function, , The @code{kill-new} function}, which uses
7071 the @code{nthcdr} and @code{setcdr} functions.)
7073 @need 1200
7074 To see how this works, set the value of the variable to a list of
7075 domesticated animals by evaluating the following expression:
7077 @smallexample
7078 (setq domesticated-animals '(horse cow sheep goat))
7079 @end smallexample
7081 @need 1200
7082 @noindent
7083 If you now evaluate the list, you will be returned the list
7084 @code{(horse cow sheep goat)}:
7086 @smallexample
7087 @group
7088 domesticated-animals
7089      @result{} (horse cow sheep goat)
7090 @end group
7091 @end smallexample
7093 @need 1200
7094 Next, evaluate @code{setcdr} with two arguments, the name of the
7095 variable which has a list as its value, and the list to which the
7096 @sc{cdr} of the first list will be set;
7098 @smallexample
7099 (setcdr domesticated-animals '(cat dog))
7100 @end smallexample
7102 @noindent
7103 If you evaluate this expression, the list @code{(cat dog)} will appear
7104 in the echo area.  This is the value returned by the function.  The
7105 result we are interested in is the ``side effect'', which we can see by
7106 evaluating the variable @code{domesticated-animals}:
7108 @smallexample
7109 @group
7110 domesticated-animals
7111      @result{} (horse cat dog)
7112 @end group
7113 @end smallexample
7115 @noindent
7116 Indeed, the list is changed from @code{(horse cow sheep goat)} to
7117 @code{(horse cat dog)}.  The @sc{cdr} of the list is changed from
7118 @code{(cow sheep goat)} to @code{(cat dog)}.
7120 @node cons Exercise,  , setcdr, car cdr & cons
7121 @section Exercise
7123 Construct a list of four birds by evaluating several expressions with
7124 @code{cons}.  Find out what happens when you @code{cons} a list onto
7125 itself.  Replace the first element of the list of four birds with a
7126 fish.  Replace the rest of that list with a list of other fish.
7128 @node Cutting & Storing Text, List Implementation, car cdr & cons, Top
7129 @comment  node-name,  next,  previous,  up
7130 @chapter Cutting and Storing Text
7131 @cindex Cutting and storing text
7132 @cindex Storing and cutting text
7133 @cindex Killing text
7134 @cindex Clipping text
7135 @cindex Erasing text
7136 @cindex Deleting text
7138 Whenever you cut or clip text out of a buffer with a `kill' command in
7139 GNU Emacs, it is stored in a list and you can bring it back with a
7140 `yank' command.
7142 (The use of the word `kill' in Emacs for processes which specifically
7143 @emph{do not} destroy the values of the entities is an unfortunate
7144 historical accident.  A much more appropriate word would be `clip' since
7145 that is what the kill commands do; they clip text out of a buffer and
7146 put it into storage from which it can be brought back.  I have often
7147 been tempted to replace globally all occurrences of `kill' in the Emacs
7148 sources with `clip' and all occurrences of `killed' with `clipped'.)
7150 @menu
7151 * Storing Text::                Text is stored in a list.
7152 * zap-to-char::                 Cutting out text up to a character.
7153 * kill-region::                 Cutting text out of a region.
7154 * Digression into C::           Minor note on C programming language macros.
7155 * defvar::                      How to give a variable an initial value.
7156 * copy-region-as-kill::         A definition for copying text.
7157 * cons & search-fwd Review::
7158 * search Exercises::
7159 @end menu
7161 @node Storing Text, zap-to-char, Cutting & Storing Text, Cutting & Storing Text
7162 @ifnottex
7163 @unnumberedsec Storing Text in a List
7164 @end ifnottex
7166 When text is cut out of a buffer, it is stored on a list.  Successive
7167 pieces of text are stored on the list successively, so the list might
7168 look like this:
7170 @smallexample
7171 ("a piece of text" "previous piece")
7172 @end smallexample
7174 @need 1200
7175 @noindent
7176 The function @code{cons} can be used to to create a new list from a
7177 piece of text (an `atom', to use the jargon) and an existing list,
7178 like this:
7180 @smallexample
7181 @group
7182 (cons "another piece"
7183       '("a piece of text" "previous piece"))
7184 @end group
7185 @end smallexample
7187 @need 1200
7188 @noindent
7189 If you evaluate this expression, a list of three elements will appear in
7190 the echo area:
7192 @smallexample
7193 ("another piece" "a piece of text" "previous piece")
7194 @end smallexample
7196 With the @code{car} and @code{nthcdr} functions, you can retrieve
7197 whichever piece of text you want.  For example, in the following code,
7198 @code{nthcdr 1 @dots{}} returns the list with the first item removed;
7199 and the @code{car} returns the first element of that remainder---the
7200 second element of the original list:
7202 @smallexample
7203 @group
7204 (car (nthcdr 1 '("another piece"
7205                  "a piece of text"
7206                  "previous piece")))
7207      @result{} "a piece of text"
7208 @end group
7209 @end smallexample
7211 The actual functions in Emacs are more complex than this, of course.
7212 The code for cutting and retrieving text has to be written so that
7213 Emacs can figure out which element in the list you want---the first,
7214 second, third, or whatever.  In addition, when you get to the end of
7215 the list, Emacs should give you the first element of the list, rather
7216 than nothing at all.
7218 The list that holds the pieces of text is called the @dfn{kill ring}.
7219 This chapter leads up to a description of the kill ring and how it is
7220 used by first tracing how the @code{zap-to-char} function works.  This
7221 function uses (or `calls') a function that invokes a function that
7222 manipulates the kill ring.  Thus, before reaching the mountains, we
7223 climb the foothills.
7225 A subsequent chapter describes how text that is cut from the buffer is
7226 retrieved.  @xref{Yanking, , Yanking Text Back}.
7228 @node zap-to-char, kill-region, Storing Text, Cutting & Storing Text
7229 @comment  node-name,  next,  previous,  up
7230 @section @code{zap-to-char}
7231 @findex zap-to-char
7233 The @code{zap-to-char} function barely changed between GNU Emacs
7234 version 19 and GNU Emacs version 21.  However, @code{zap-to-char}
7235 calls another function, @code{kill-region}, which enjoyed a major rewrite
7236 on the way to version 21.
7238 The @code{kill-region} function in Emacs 19 is complex, but does not
7239 use code that is important at this time.  We will skip it.
7241 The @code{kill-region} function in Emacs 21 is easier to read than the
7242 same function in Emacs 19 and introduces a very important concept,
7243 that of error handling.  We will walk through the function.
7245 But first, let us look at the interactive @code{zap-to-char} function.
7247 @menu
7248 * Complete zap-to-char::        The complete implementation.
7249 * zap-to-char interactive::     A three part interactive expression.
7250 * zap-to-char body::            A short overview.
7251 * search-forward::              How to search for a string.
7252 * progn::                       The @code{progn} special form.
7253 * Summing up zap-to-char::      Using @code{point} and @code{search-forward}.
7254 @end menu
7256 @node Complete zap-to-char, zap-to-char interactive, zap-to-char, zap-to-char
7257 @ifnottex
7258 @unnumberedsubsec The Complete @code{zap-to-char} Implementation
7259 @end ifnottex
7261 The GNU Emacs version 19 and version 21 implementations of the
7262 @code{zap-to-char} function are nearly identical in form, and they
7263 work alike.  The function removes the text in the region between the
7264 location of the cursor (i.e., of point) up to and including the next
7265 occurrence of a specified character.  The text that @code{zap-to-char}
7266 removes is put in the kill ring; and it can be retrieved from the kill
7267 ring by typing @kbd{C-y} (@code{yank}).  If the command is given an
7268 argument, it removes text through that number of occurrences.  Thus,
7269 if the cursor were at the beginning of this sentence and the character
7270 were @samp{s}, @samp{Thus} would be removed.  If the argument were
7271 two, @samp{Thus, if the curs} would be removed, up to and including
7272 the @samp{s} in @samp{cursor}.
7274 If the specified character is not found, @code{zap-to-char} will say
7275 ``Search failed'', tell you the character you typed, and not remove
7276 any text.
7278 In order to determine how much text to remove, @code{zap-to-char} uses
7279 a search function.  Searches are used extensively in code that
7280 manipulates text, and we will focus attention on them as well as on the
7281 deletion command.
7283 @need 800
7284 Here is the complete text of the version 19 implementation of the function:
7286 @c v 19
7287 @smallexample
7288 @group
7289 (defun zap-to-char (arg char)  ; version 19 implementation
7290   "Kill up to and including ARG'th occurrence of CHAR.
7291 Goes backward if ARG is negative; error if CHAR not found."
7292   (interactive "*p\ncZap to char: ")
7293   (kill-region (point)
7294                (progn
7295                  (search-forward
7296                   (char-to-string char) nil nil arg)
7297                  (point))))
7298 @end group
7299 @end smallexample
7301 @node zap-to-char interactive, zap-to-char body, Complete zap-to-char, zap-to-char
7302 @comment  node-name,  next,  previous,  up
7303 @subsection The @code{interactive} Expression
7305 @need 800
7306 The interactive expression in the @code{zap-to-char} command looks like
7307 this:
7309 @smallexample
7310 (interactive "*p\ncZap to char: ")
7311 @end smallexample
7313 The part within quotation marks, @code{"*p\ncZap to char:@: "}, specifies
7314 three different things.  First, and most simply, the asterisk, @samp{*},
7315 causes an error to be signalled if the buffer is read-only.  This means that
7316 if you try @code{zap-to-char} in a read-only buffer you will not be able to
7317 remove text, and you will receive a message that says ``Buffer is
7318 read-only''; your terminal may beep at you as well.
7320 The version 21 implementation does not have the asterisk, @samp{*}.  The
7321 function works the same as in version 19: in both cases, it cannot
7322 remove text from a read-only buffer but the function does copy the
7323 text that would have been removed to the kill ring.  Also, in both
7324 cases, you see an error message.
7326 However, the version 19 implementation copies text from a read-only
7327 buffer only because of a mistake in the implementation of
7328 @code{interactive}.  According to the documentation for
7329 @code{interactive}, the asterisk, @samp{*}, should prevent the
7330 @code{zap-to-char} function from doing anything at all when the buffer
7331 is read only.  In version 19, the function should not copy the text to
7332 the kill ring.  It is a bug that it does.
7334 In version 21, the function is designed to copy the text to the kill
7335 ring; moreover, @code{interactive} is implemented correctly.  So the
7336 asterisk, @samp{*}, had to be removed from the interactive
7337 specification.  However, if you insert an @samp{*} yourself and
7338 evaluate the function definition, then the next time you run the
7339 @code{zap-to-char} function on a read-only buffer, you will not copy
7340 any text.
7342 That change aside, and a change to the documentation, the two versions
7343 of the  @code{zap-to-char} function are identical.
7345 Let us continue with the interactive specification.
7347 The second part of @code{"*p\ncZap to char:@: "} is the @samp{p}.
7348 This part is separated from the next part by a newline, @samp{\n}.
7349 The @samp{p} means that the first argument to the function will be
7350 passed the value of a `processed prefix'.  The prefix argument is
7351 passed by typing @kbd{C-u} and a number, or @kbd{M-} and a number.  If
7352 the function is called interactively without a prefix, 1 is passed to
7353 this argument.
7355 The third part of @code{"*p\ncZap to char:@: "} is @samp{cZap to char:@:
7356 }.  In this part, the lower case @samp{c} indicates that
7357 @code{interactive} expects a prompt and that the argument will be a
7358 character.  The prompt follows the @samp{c} and is the string @samp{Zap
7359 to char:@: } (with a space after the colon to make it look good).
7361 What all this does is prepare the arguments to @code{zap-to-char} so they
7362 are of the right type, and give the user a prompt.
7364 @node zap-to-char body, search-forward, zap-to-char interactive, zap-to-char
7365 @comment  node-name,  next,  previous,  up
7366 @subsection The Body of @code{zap-to-char}
7368 The body of the @code{zap-to-char} function contains the code that
7369 kills (that is, removes) the text in the region from the current
7370 position of the cursor up to and including the specified character.
7371 The first part of the code looks like this:
7373 @smallexample
7374 (kill-region (point) @dots{}
7375 @end smallexample
7377 @noindent
7378 @code{(point)} is the current position of the cursor.
7380 The next part of the code is an expression using @code{progn}.  The body
7381 of the @code{progn} consists of calls to @code{search-forward} and
7382 @code{point}.
7384 It is easier to understand how @code{progn} works after learning about
7385 @code{search-forward}, so we will look at @code{search-forward} and
7386 then at @code{progn}.
7388 @node search-forward, progn, zap-to-char body, zap-to-char
7389 @comment  node-name,  next,  previous,  up
7390 @subsection The @code{search-forward} Function
7391 @findex search-forward
7393 The @code{search-forward} function is used to locate the
7394 zapped-for-character in @code{zap-to-char}.  If the search is
7395 successful, @code{search-forward} leaves point immediately after the
7396 last character in the target string.  (In @code{zap-to-char}, the
7397 target string is just one character long.)  If the search is
7398 backwards, @code{search-forward} leaves point just before the first
7399 character in the target.  Also, @code{search-forward} returns @code{t}
7400 for true.  (Moving point is therefore a `side effect'.)
7402 @need 1250
7403 In @code{zap-to-char}, the @code{search-forward} function looks like this:
7405 @smallexample
7406 (search-forward (char-to-string char) nil nil arg)
7407 @end smallexample
7409 The @code{search-forward} function takes four arguments:
7411 @enumerate
7412 @item
7413 The first argument is the target, what is searched for.  This must be a
7414 string, such as @samp{"z"}.
7416 As it happens, the argument passed to @code{zap-to-char} is a single
7417 character.  Because of the way computers are built, the Lisp
7418 interpreter may treat a single character as being different from a
7419 string of characters.  Inside the computer, a single character has a
7420 different electronic format than a string of one character.  (A single
7421 character can often be recorded in the computer using exactly one
7422 byte; but a string may be longer, and the computer needs to be ready
7423 for this.)  Since the @code{search-forward} function searches for a
7424 string, the character that the @code{zap-to-char} function receives as
7425 its argument must be converted inside the computer from one format to
7426 the other; otherwise the @code{search-forward} function will fail.
7427 The @code{char-to-string} function is used to make this conversion.
7429 @item
7430 The second argument bounds the search; it is specified as a position in
7431 the buffer.  In this case, the search can go to the end of the buffer,
7432 so no bound is set and the second argument is @code{nil}.
7434 @item
7435 The third argument tells the function what it should do if the search
7436 fails---it can signal an error (and print a message) or it can return
7437 @code{nil}.  A @code{nil} as the third argument causes the function to
7438 signal an error when the search fails.
7440 @item
7441 The fourth argument to @code{search-forward} is the repeat count---how
7442 many occurrences of the string to look for.  This argument is optional
7443 and if the function is called without a repeat count, this argument is
7444 passed the value 1.  If this argument is negative, the search goes
7445 backwards.
7446 @end enumerate
7448 @need 800
7449 In template form, a @code{search-forward} expression looks like this:
7451 @smallexample
7452 @group
7453 (search-forward "@var{target-string}"
7454                 @var{limit-of-search}
7455                 @var{what-to-do-if-search-fails}
7456                 @var{repeat-count})
7457 @end group
7458 @end smallexample
7460 We will look at @code{progn} next.
7462 @node progn, Summing up zap-to-char, search-forward, zap-to-char
7463 @comment  node-name,  next,  previous,  up
7464 @subsection The @code{progn} Special Form
7465 @findex progn
7467 @code{progn} is a special form that causes each of its arguments to be
7468 evaluated in sequence and then returns the value of the last one.  The
7469 preceding expressions are evaluated only for the side effects they
7470 perform.  The values produced by them are discarded.
7472 @need 800
7473 The template for a @code{progn} expression is very simple:
7475 @smallexample
7476 @group
7477 (progn
7478   @var{body}@dots{})
7479 @end group
7480 @end smallexample
7482 In @code{zap-to-char}, the @code{progn} expression has to do two things:
7483 put point in exactly the right position; and return the location of
7484 point so that @code{kill-region} will know how far to kill to.
7486 The first argument to the @code{progn} is @code{search-forward}.  When
7487 @code{search-forward} finds the string, the function leaves point
7488 immediately after the last character in the target string.  (In this
7489 case the target string is just one character long.)  If the search is
7490 backwards, @code{search-forward} leaves point just before the first
7491 character in the target.  The movement of point is a side effect.
7493 The second and last argument to @code{progn} is the expression
7494 @code{(point)}.  This expression returns the value of point, which in
7495 this case will be the location to which it has been moved by
7496 @code{search-forward}.  This value is returned by the @code{progn}
7497 expression and is passed to @code{kill-region} as @code{kill-region}'s
7498 second argument.
7500 @node Summing up zap-to-char,  , progn, zap-to-char
7501 @comment  node-name,  next,  previous,  up
7502 @subsection Summing up @code{zap-to-char}
7504 Now that we have seen how @code{search-forward} and @code{progn} work,
7505 we can see how the @code{zap-to-char} function works as a whole.
7507 The first argument to @code{kill-region} is the position of the cursor
7508 when the @code{zap-to-char} command is given---the value of point at
7509 that time.  Within the @code{progn}, the search function then moves
7510 point to just after the zapped-to-character and @code{point} returns the
7511 value of this location.  The @code{kill-region} function puts together
7512 these two values of point, the first one as the beginning of the region
7513 and the second one as the end of the region, and removes the region.
7515 The @code{progn} special form is necessary because the @code{kill-region}
7516 command takes two arguments; and it would fail if @code{search-forward}
7517 and @code{point} expressions were  written in sequence as two
7518 additional arguments.  The @code{progn} expression is a single argument
7519 to @code{kill-region} and returns the one value that @code{kill-region}
7520 needs for its second argument.
7522 @node kill-region, Digression into C, zap-to-char, Cutting & Storing Text
7523 @comment  node-name,  next,  previous,  up
7524 @section @code{kill-region}
7525 @findex kill-region
7527 The @code{zap-to-char} function uses the @code{kill-region} function.
7528 This function clips text from a region and copies that text to
7529 the kill ring, from which it may be retrieved.
7531 The Emacs 21 version of that function uses @code{condition-case} and
7532 @code{copy-region-as-kill}, both of which we will explain.
7533 @code{condition-case} is an important special form.
7535 In essence, the @code{kill-region} function calls
7536 @code{condition-case}, which takes three arguments.  In this function,
7537 the first argument does nothing.  The second argument contains the
7538 code that does the work when all goes well.  The third argument
7539 contains the code that is called in the event of an error.
7541 @menu
7542 * Complete kill-region::        The function definition.
7543 * condition-case::              Dealing with a problem.
7544 * delete-and-extract-region::   Doing the work.
7545 @end menu
7547 @node Complete kill-region, condition-case, kill-region, kill-region
7548 @ifnottex
7549 @unnumberedsubsec The Complete @code{kill-region} Definition
7550 @end ifnottex
7552 @need 1200
7553 We will go through the @code{condition-case} code in a moment.  First,
7554 let us look at the original definition of @code{kill-region}, with
7555 comments added (the newer definition has an optional third argument
7556 and is more complex):
7558 @c v 21
7559 @smallexample
7560 @group
7561 (defun kill-region (beg end)
7562   "Kill between point and mark.
7563 The text is deleted but saved in the kill ring."
7564   (interactive "r")
7565 @end group
7567 @group
7568   ;; 1. `condition-case' takes three arguments.
7569   ;;    If the first argument is nil, as it is here,
7570   ;;    information about the error signal is not
7571   ;;    stored for use by another function.
7572   (condition-case nil
7573 @end group
7575 @group
7576       ;; 2. The second argument to `condition-case'
7577       ;;    tells the Lisp interpreter what to do when all goes well.
7578 @end group
7580 @group
7581       ;;    The `delete-and-extract-region' function usually does the
7582       ;;    work.  If the beginning and ending of the region are both
7583       ;;    the same, then the variable `string' will be empty, or nil
7584       (let ((string (delete-and-extract-region beg end)))
7585 @end group
7587 @group
7588         ;; `when' is an `if' clause that cannot take an `else-part'.
7589         ;; Emacs normally sets the value of `last-command' to the
7590         ;; previous command.
7591 @end group
7592 @group
7593         ;; `kill-append' concatenates the new string and the old.
7594         ;; `kill-new' inserts text into a new item in the kill ring.
7595         (when string
7596           (if (eq last-command 'kill-region)
7597               ;; if true, prepend string
7598               (kill-append string (< end beg))
7599             (kill-new string)))
7600         (setq this-command 'kill-region))
7601 @end group
7603 @group
7604     ;; 3. The third argument to `condition-case' tells the interpreter
7605     ;;    what to do with an error.
7606 @end group
7607 @group
7608     ;;    The third argument has a conditions part and a body part.
7609     ;;    If the conditions are met (in this case,
7610     ;;             if text or buffer is read-only)
7611     ;;    then the body is executed.
7612 @end group
7613 @group
7614     ((buffer-read-only text-read-only) ;; this is the if-part
7615      ;; then...
7616      (copy-region-as-kill beg end)
7617 @end group
7618 @group
7619      (if kill-read-only-ok            ;; usually this variable is nil
7620          (message "Read only text copied to kill ring")
7621        ;; or else, signal an error if the buffer is read-only;
7622        (barf-if-buffer-read-only)
7623        ;; and, in any case, signal that the text is read-only.
7624        (signal 'text-read-only (list (current-buffer)))))))
7625 @end group
7626 @end smallexample
7628 @node condition-case, delete-and-extract-region, Complete kill-region, kill-region
7629 @comment  node-name,  next,  previous,  up
7630 @subsection @code{condition-case}
7631 @findex condition-case
7633 As we have seen earlier (@pxref{Making Errors, , Generate an Error
7634 Message}), when the Emacs Lisp interpreter has trouble evaluating an
7635 expression, it provides you with help; in the jargon, this is called
7636 ``signaling an error''.  Usually, the computer stops the program and
7637 shows you a message.
7639 However, some programs undertake complicated actions.  They should not
7640 simply stop on an error.  In the @code{kill-region} function, the most
7641 likely error is that you will try to kill text that is read-only and
7642 cannot be removed.  So the @code{kill-region} function contains code
7643 to handle this circumstance.  This code, which makes up the body of
7644 the @code{kill-region} function, is inside of a @code{condition-case}
7645 special form.
7647 @need 800
7648 The template for @code{condition-case} looks like this:
7650 @smallexample
7651 @group
7652 (condition-case
7653   @var{var}
7654   @var{bodyform}
7655   @var{error-handler}@dots{})
7656 @end group
7657 @end smallexample
7659 The second argument, @var{bodyform}, is straightforward.  The
7660 @code{condition-case} special form causes the Lisp interpreter to
7661 evaluate the code in @var{bodyform}.  If no error occurs, the special
7662 form returns the code's value and produces the side-effects, if any.
7664 In short, the @var{bodyform} part of a @code{condition-case}
7665 expression determines what should happen when everything works
7666 correctly.
7668 However, if an error occurs, among its other actions, the function
7669 generating the error signal will define one or more error condition
7670 names.
7672 An error handler is the third argument to @code{condition case}.
7673 An error handler has two parts, a @var{condition-name} and a
7674 @var{body}.  If the @var{condition-name} part of an error handler
7675 matches a condition name generated by an error, then the @var{body}
7676 part of the error handler is run.
7678 As you will expect, the @var{condition-name} part of an error handler
7679 may be either a single condition name or a list of condition names.
7681 Also, a complete @code{condition-case} expression may contain more
7682 than one error handler.  When an error occurs, the first applicable
7683 handler is run.
7685 Lastly, the first argument to the @code{condition-case} expression,
7686 the @var{var} argument, is sometimes bound to a variable that
7687 contains information about the error.  However, if that argument is
7688 nil, as is the case in @code{kill-region}, that information is
7689 discarded.
7691 @need 1200
7692 In brief, in the @code{kill-region} function, the code
7693 @code{condition-case} works like this:
7695 @smallexample
7696 @group
7697 @var{If no errors}, @var{run only this code}
7698     @var{but}, @var{if errors}, @var{run this other code}.
7699 @end group
7700 @end smallexample
7702 @node delete-and-extract-region,  , condition-case, kill-region
7703 @comment  node-name,  next,  previous,  up
7704 @subsection @code{delete-and-extract-region}
7705 @findex delete-and-extract-region
7707 A @code{condition-case} expression has two parts, a part that is
7708 evaluated in the expectation that all will go well, but which may
7709 generate an error; and a part that is evaluated when there is an
7710 error.
7712 First, let us look at the code in @code{kill-region} that is run in
7713 the expectation that all goes well.  This is the core of the function.
7714 The code looks like this:
7716 @smallexample
7717 @group
7718 (let ((string (delete-and-extract-region beg end)))
7719   (when string
7720     (if (eq last-command 'kill-region)
7721         (kill-append string (< end beg))
7722       (kill-new string)))
7723   (setq this-command 'kill-region))
7724 @end group
7725 @end smallexample
7727 It looks complicated because we have the new functions
7728 @code{delete-and-extract-region}, @code{kill-append}, and
7729 @code{kill-new} as well as the new variables,
7730 @code{last-command} and @code{this-command}.
7732 The @code{delete-and-extract-region} function is straightforward.  It
7733 is a built-in function that deletes the text in a region (a side
7734 effect) and also returns that text.  This is the function that
7735 actually removes the text.  (And if it cannot do that, it signals the
7736 error.)
7738 In this @code{let} expression, the text that
7739 @code{delete-and-extract-region} returns is placed in the local
7740 variable called @samp{string}.  This is the text that is removed from
7741 the buffer.  (To be more precise, the variable is set to point to the
7742 address of the extracted text; to say it is `placed in' the variable
7743 is simply a shorthand.)
7745 If the variable @samp{string} does point to text, that text is added
7746 to the kill ring.  The variable will have a @code{nil} value if no
7747 text was removed.
7749 The code uses @code{when} to determine whether the variable
7750 @samp{string} points to text.  A @code{when} statement is simply a
7751 programmers' convenience.  A @code{when} statement is an @code{if}
7752 statement without the possibility of an else clause.  In your mind, you
7753 can replace @code{when} with @code{if} and understand what goes on.
7754 That is what the Lisp interpreter does.
7756 @cindex Macro, lisp
7757 @cindex Lisp macro
7758 Technically speaking, @code{when} is a Lisp macro.  A Lisp @dfn{macro}
7759 enables you to define new control constructs and other language
7760 features.  It tells the interpreter how to compute another Lisp
7761 expression which will in turn compute the value.  In this case, the
7762 `other expression' is an @code{if} expression.  For more about Lisp
7763 macros, see @ref{Macros, , Macros, elisp, The GNU Emacs Lisp Reference
7764 Manual}.  The C programming language also provides macros.  These are
7765 different, but also useful.  We will briefly look at C macros in
7766 @ref{Digression into C}.
7768 @need 1200
7769 If the string has content, then another conditional expression is
7770 executed.  This is an @code{if} with both a then-part and an else-part.
7772 @smallexample
7773 @group
7774 (if (eq last-command 'kill-region)
7775     (kill-append string (< end beg))
7776   (kill-new string)))
7777 @end group
7778 @end smallexample
7780 The then-part is evaluated if the previous command was another call to
7781 @code{kill-region}; if not, the else-part is evaluated.
7783 @code{last-command} is a variable that comes with Emacs that we have
7784 not seen before.  Normally, whenever a function is executed, Emacs
7785 sets the value of @code{last-command} to the previous command.
7787 @need 1200
7788 In this segment of the definition, the @code{if} expression checks
7789 whether the previous command was @code{kill-region}.  If it was,
7791 @smallexample
7792 (kill-append string (< end beg))
7793 @end smallexample
7795 @noindent
7796 concatenates a copy of the newly clipped text to the just previously
7797 clipped text in the kill ring.  (If the @w{@code{(< end beg))}}
7798 expression is true, @code{kill-append} prepends the string to the just
7799 previously clipped text.  For a detailed discussion, see
7800 @ref{kill-append function, , The @code{kill-append} function}.)
7802 If you then yank back the text, i.e., `paste' it, you get both
7803 pieces of text at once.  That way, if you delete two words in a row,
7804 and then yank them back, you get both words, in their proper order,
7805 with one yank.  (The @w{@code{(< end beg))}} expression makes sure the
7806 order is correct.)
7808 On the other hand, if the previous command is not @code{kill-region},
7809 then the @code{kill-new} function is called, which adds the text to
7810 the kill ring as the latest item, and sets the
7811 @code{kill-ring-yank-pointer} variable to point to it.
7813 @node Digression into C, defvar, kill-region, Cutting & Storing Text
7814 @comment  node-name,  next,  previous,  up
7815 @section Digression into C
7816 @findex delete-and-extract-region
7817 @cindex C, a digression into
7818 @cindex Digression into C
7820 The @code{zap-to-char} command uses the
7821 @code{delete-and-extract-region} function, which in turn uses two
7822 other functions, @code{copy-region-as-kill} and
7823 @code{del_range_1}.  The @code{copy-region-as-kill} function will be
7824 described in a following section; it puts a copy of the region in the
7825 kill ring so it can be yanked back.  (@xref{copy-region-as-kill, ,
7826 @code{copy-region-as-kill}}.)
7828 The @code{delete-and-extract-region} function removes the contents of
7829 a region and you cannot get them back.
7831 Unlike the other code discussed here, @code{delete-and-extract-region}
7832 is not written in Emacs Lisp; it is written in C and is one of the
7833 primitives of the GNU Emacs system.  Since it is very simple, I will
7834 digress briefly from Lisp and describe it here.
7836 @need 1500
7837 Like many of the other Emacs primitives,
7838 @code{delete-and-extract-region} is written as an instance of a C
7839 macro, a macro being a template for code.  The complete macro looks
7840 like this:
7842 @c /usr/local/src/emacs/src/editfns.c
7843 @smallexample
7844 @group
7845 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
7846        Sdelete_and_extract_region, 2, 2, 0,
7847   "Delete the text between START and END and return it.")
7848   (start, end)
7849      Lisp_Object start, end;
7851   validate_region (&start, &end);
7852   return del_range_1 (XINT (start), XINT (end), 1, 1);
7854 @end group
7855 @end smallexample
7857 Without going into the details of the macro writing process, let me
7858 point out that this macro starts with the word @code{DEFUN}.  The word
7859 @code{DEFUN} was chosen since the code serves the same purpose as
7860 @code{defun} does in Lisp.  The word @code{DEFUN} is followed by seven
7861 parts inside of parentheses:
7863 @itemize @bullet
7864 @item
7865 The first part is the name given to the function in Lisp,
7866 @code{delete-and-extract-region}.
7868 @item
7869 The second part is the name of the function in C,
7870 @code{Fdelete_and_extract_region}.  By convention, it starts with
7871 @samp{F}.  Since C does not use hyphens in names, underscores are used
7872 instead.
7874 @item
7875 The third part is the name for the C constant structure that records
7876 information on this function for internal use.  It is the name of the
7877 function in C but begins with an @samp{S} instead of an @samp{F}.
7879 @item
7880 The fourth and fifth parts specify the minimum and maximum number of
7881 arguments the function can have.  This function demands exactly 2
7882 arguments.
7884 @item
7885 The sixth part is nearly like the argument that follows the
7886 @code{interactive} declaration in a function written in Lisp: a letter
7887 followed, perhaps, by a prompt.  The only difference from the Lisp is
7888 when the macro is called with no arguments.  Then you write a @code{0}
7889 (which is a `null string'), as in this macro.
7891 If you were to specify arguments, you would place them between
7892 quotation marks.  The C macro for @code{goto-char} includes
7893 @code{"NGoto char: "} in this position to indicate that the function
7894 expects a raw prefix, in this case, a numerical location in a buffer,
7895 and provides a prompt.
7897 @item
7898 The seventh part is a documentation string, just like the one for a
7899 function written in Emacs Lisp, except that every newline must be
7900 written explicitly as @samp{\n} followed by a backslash and carriage
7901 return.
7903 @need 1000
7904 Thus, the first two lines of documentation for  @code{goto-char} are
7905 written like this:
7907 @smallexample
7908 @group
7909   "Set point to POSITION, a number or marker.\n\
7910 Beginning of buffer is position (point-min), end is (point-max).
7911 @end group
7912 @end smallexample
7913 @end itemize
7915 @need 1200
7916 In a C macro, the formal parameters come next, with a statement of
7917 what kind of object they are, followed by what might be called the `body'
7918 of the macro.  For @code{delete-and-extract-region} the `body'
7919 consists of the following two lines:
7921 @smallexample
7922 @group
7923 validate_region (&start, &end);
7924 return del_range_1 (XINT (start), XINT (end), 1, 1);
7925 @end group
7926 @end smallexample
7928 The first function, @code{validate_region} checks whether the values
7929 passed as the beginning and end of the region are the proper type and
7930 are within range.  The second function, @code{del_range_1}, actually
7931 deletes the text.
7933 @code{del_range_1} is a complex function we will not look into.  It
7934 updates the buffer and does other things.
7936 However, it is worth looking at the two arguments passed to
7937 @code{del_range}.  These are @w{@code{XINT (start)}} and @w{@code{XINT
7938 (end)}}.
7940 As far as the C language is concerned, @code{start} and @code{end} are
7941 two integers that mark the beginning and end of the region to be
7942 deleted@footnote{More precisely, and requiring more expert knowledge
7943 to understand, the two integers are of type `Lisp_Object', which can
7944 also be a C union instead of an integer type.}.
7946 In early versions of Emacs, these two numbers were thirty-two bits
7947 long, but the code is slowly being generalized to handle other
7948 lengths.  Three of the available bits are used to specify the type of
7949 information and a fourth bit is used for handling the computer's
7950 memory; the remaining bits are used as `content'.
7952 @samp{XINT} is a C macro that extracts the relevant number from the
7953 longer collection of bits; the four other bits are discarded.
7955 @need 800
7956 The command in @code{delete-and-extract-region} looks like this:
7958 @smallexample
7959 del_range_1 (XINT (start), XINT (end), 1, 1);
7960 @end smallexample
7962 @noindent
7963 It deletes the region between the beginning position, @code{start},
7964 and the ending position, @code{end}.
7966 From the point of view of the person writing Lisp, Emacs is all very
7967 simple; but hidden underneath is a great deal of complexity to make it
7968 all work.
7970 @node defvar, copy-region-as-kill, Digression into C, Cutting & Storing Text
7971 @comment  node-name,  next,  previous,  up
7972 @section Initializing a Variable with @code{defvar}
7973 @findex defvar
7974 @cindex Initializing a variable
7975 @cindex Variable initialization
7977 Unlike the @code{delete-and-extract-region} function, the
7978 @code{copy-region-as-kill} function is written in Emacs Lisp.  Two
7979 functions within it, @code{kill-append} and @code{kill-new}, copy a
7980 region in a buffer and save it in a variable called the
7981 @code{kill-ring}.  This section describes how the @code{kill-ring}
7982 variable is created and initialized using the @code{defvar} special
7983 form.
7985 (Again we note that the term @code{kill-ring} is a misnomer.  The text
7986 that is clipped out of the buffer can be brought back; it is not a ring
7987 of corpses, but a ring of resurrectable text.)
7989 In Emacs Lisp, a variable such as the @code{kill-ring} is created and
7990 given an initial value by using the @code{defvar} special form.  The
7991 name comes from ``define variable''.
7993 The @code{defvar} special form is similar to @code{setq} in that it sets
7994 the value of a variable.  It is unlike @code{setq} in two ways: first,
7995 it only sets the value of the variable if the variable does not already
7996 have a value.  If the variable already has a value, @code{defvar} does
7997 not override the existing value.  Second, @code{defvar} has a
7998 documentation string.
8000 (Another special form, @code{defcustom}, is designed for variables
8001 that people customize.  It has more features than @code{defvar}.
8002 (@xref{defcustom, , Setting Variables with @code{defcustom}}.)
8004 @menu
8005 * See variable current value::
8006 * defvar and asterisk::         An old-time convention.
8007 @end menu
8009 @node See variable current value, defvar and asterisk, defvar, defvar
8010 @ifnottex
8011 @unnumberedsubsec Seeing the Current Value of a Variable
8012 @end ifnottex
8014 You can see the current value of a variable, any variable, by using
8015 the @code{describe-variable} function, which is usually invoked by
8016 typing @kbd{C-h v}.  If you type @kbd{C-h v} and then @code{kill-ring}
8017 (followed by @key{RET}) when prompted, you will see what is in your
8018 current kill ring---this may be quite a lot!  Conversely, if you have
8019 been doing nothing this Emacs session except read this document, you
8020 may have nothing in it.  Also, you will see the documentation for
8021 @code{kill-ring}:
8023 @smallexample
8024 @group
8025 Documentation:
8026 List of killed text sequences.
8027 Since the kill ring is supposed to interact nicely with cut-and-paste
8028 facilities offered by window systems, use of this variable should
8029 @end group
8030 @group
8031 interact nicely with `interprogram-cut-function' and
8032 `interprogram-paste-function'.  The functions `kill-new',
8033 `kill-append', and `current-kill' are supposed to implement this
8034 interaction; you may want to use them instead of manipulating the kill
8035 ring directly.
8036 @end group
8037 @end smallexample
8039 @need 800
8040 The kill ring is defined by a @code{defvar} in the following way:
8042 @smallexample
8043 @group
8044 (defvar kill-ring nil
8045   "List of killed text sequences.
8046 @dots{}")
8047 @end group
8048 @end smallexample
8050 @noindent
8051 In this variable definition, the variable is given an initial value of
8052 @code{nil}, which makes sense, since if you have saved nothing, you want
8053 nothing back if you give a @code{yank} command.  The documentation
8054 string is written just like the documentation string of a @code{defun}.
8055 As with the documentation string of the @code{defun}, the first line of
8056 the documentation should be a complete sentence, since some commands,
8057 like @code{apropos}, print only the first line of documentation.
8058 Succeeding lines should not be indented; otherwise they look odd when
8059 you use @kbd{C-h v} (@code{describe-variable}).
8061 @node defvar and asterisk,  , See variable current value, defvar
8062 @subsection @code{defvar} and an asterisk
8063 @findex defvar @r{for a user customizable variable}
8064 @findex defvar @r{with an asterisk}
8066 In the past, Emacs used the @code{defvar} special form both for
8067 internal variables that you would not expect a user to change and for
8068 variables that you do expect a user to change.  Although you can still
8069 use @code{defvar} for user customizable variables, please use
8070 @code{defcustom} instead, since that special form provides a path into
8071 the Customization commands.  (@xref{defcustom, , Specifying Variables
8072 using @code{defcustom}}.)
8074 When you specified a variable using the @code{defvar} special form,
8075 you could distinguish a readily settable variable from others by
8076 typing an asterisk, @samp{*}, in the first column of its documentation
8077 string.  For example:
8079 @smallexample
8080 @group
8081 (defvar shell-command-default-error-buffer nil
8082   "*Buffer name for `shell-command' @dots{} error output.
8083 @dots{} ")
8084 @end group
8085 @end smallexample
8087 @findex set-variable
8088 @noindent
8089 You could (and still can) use the @code{set-variable} command to
8090 change the value of @code{shell-command-default-error-buffer}
8091 temporarily.  However, options set using @code{set-variable} are set
8092 only for the duration of your editing session.  The new values are not
8093 saved between sessions.  Each time Emacs starts, it reads the original
8094 value, unless you change the value within your @file{.emacs} file,
8095 either by setting it manually or by using @code{customize}.
8096 @xref{Emacs Initialization, , Your @file{.emacs} File}.
8098 For me, the major use of the @code{set-variable} command is to suggest
8099 variables that I might want to set in my @file{.emacs} file.  There
8100 are now more than 700 such variables --- far too many to remember
8101 readily.  Fortunately, you can press @key{TAB} after calling the
8102 @code{M-x set-variable} command to see the list of variables.
8103 (@xref{Examining, , Examining and Setting Variables, emacs,
8104 The GNU Emacs Manual}.)
8106 @node copy-region-as-kill, cons & search-fwd Review, defvar, Cutting & Storing Text
8107 @comment  node-name,  next,  previous,  up
8108 @section @code{copy-region-as-kill}
8109 @findex copy-region-as-kill
8110 @findex nthcdr
8112 The @code{copy-region-as-kill} function copies a region of text from a
8113 buffer and (via either @code{kill-append} or @code{kill-new}) saves it
8114 in the @code{kill-ring}.
8116 If you call @code{copy-region-as-kill} immediately after a
8117 @code{kill-region} command, Emacs appends the newly copied text to the
8118 previously copied text.  This means that if you yank back the text, you
8119 get it all, from both this and the previous operation.  On the other
8120 hand, if some other command precedes the @code{copy-region-as-kill},
8121 the function copies the text into a separate entry in the kill ring.
8123 @menu
8124 * Complete copy-region-as-kill::  The complete function definition.
8125 * copy-region-as-kill body::    The body of @code{copy-region-as-kill}.
8126 @end menu
8128 @node Complete copy-region-as-kill, copy-region-as-kill body, copy-region-as-kill, copy-region-as-kill
8129 @ifnottex
8130 @unnumberedsubsec The complete @code{copy-region-as-kill} function definition
8131 @end ifnottex
8133 @need 1200
8134 Here is the complete text of the version 21 @code{copy-region-as-kill}
8135 function:
8137 @c !!! for no text properties, use buffer-substring-no-properties
8139 @smallexample
8140 @group
8141 (defun copy-region-as-kill (beg end)
8142   "Save the region as if killed, but don't kill it.
8143 In Transient Mark mode, deactivate the mark.
8144 If `interprogram-cut-function' is non-nil, also save
8145 the text for a window system cut and paste."
8146   (interactive "r")
8147 @end group
8148 @group
8149   (if (eq last-command 'kill-region)
8150       (kill-append (buffer-substring beg end) (< end beg))
8151     (kill-new (buffer-substring beg end)))
8152 @end group
8153 @group
8154   (if transient-mark-mode
8155       (setq deactivate-mark t))
8156   nil)
8157 @end group
8158 @end smallexample
8160 @need 800
8161 As usual, this function can be divided into its component parts:
8163 @smallexample
8164 @group
8165 (defun copy-region-as-kill (@var{argument-list})
8166   "@var{documentation}@dots{}"
8167   (interactive "r")
8168   @var{body}@dots{})
8169 @end group
8170 @end smallexample
8172 The arguments are @code{beg} and @code{end} and the function is
8173 interactive with @code{"r"}, so the two arguments must refer to the
8174 beginning and end of the region.  If you have been reading though this
8175 document from the beginning, understanding these parts of a function is
8176 almost becoming routine.
8178 The documentation is somewhat confusing unless you remember that the
8179 word `kill' has a meaning different from its usual meaning.  The
8180 `Transient Mark' and @code{interprogram-cut-function} comments explain
8181 certain side-effects.
8183 After you once set a mark, a buffer always contains a region.  If you
8184 wish, you can use Transient Mark mode to highlight the region
8185 temporarily.  (No one wants to highlight the region all the time, so
8186 Transient Mark mode highlights it only at appropriate times.  Many
8187 people turn off Transient Mark mode, so the region is never
8188 highlighted.)
8190 Also, a windowing system allows you to copy, cut, and paste among
8191 different programs.  In the X windowing system, for example, the
8192 @code{interprogram-cut-function} function is @code{x-select-text},
8193 which works with the windowing system's equivalent of the Emacs kill
8194 ring.
8196 The body of the @code{copy-region-as-kill} function starts with an
8197 @code{if} clause.  What this clause does is distinguish between two
8198 different situations: whether or not this command is executed
8199 immediately after a previous @code{kill-region} command.  In the first
8200 case, the new region is appended to the previously copied text.
8201 Otherwise, it is inserted into the beginning of the kill ring as a
8202 separate piece of text from the previous piece.
8204 The last two lines of the function prevent the region from lighting up
8205 if Transient Mark mode is turned on.
8207 The body of @code{copy-region-as-kill} merits discussion in detail.
8209 @node copy-region-as-kill body,  , Complete copy-region-as-kill, copy-region-as-kill
8210 @comment  node-name,  next,  previous,  up
8211 @subsection The Body of @code{copy-region-as-kill}
8213 The @code{copy-region-as-kill} function works in much the same way as
8214 the @code{kill-region} function (@pxref{kill-region,
8215 ,@code{kill-region}}).  Both are written so that two or more kills in
8216 a row combine their text into a single entry.  If you yank back the
8217 text from the kill ring, you get it all in one piece.  Moreover, kills
8218 that kill forward from the current position of the cursor are added to
8219 the end of the previously copied text and commands that copy text
8220 backwards add it to the beginning of the previously copied text.  This
8221 way, the words in the text stay in the proper order.
8223 Like @code{kill-region}, the @code{copy-region-as-kill} function makes
8224 use of the @code{last-command} variable that keeps track of the
8225 previous Emacs command.
8227 @menu
8228 * last-command & this-command::
8229 * kill-append function::
8230 * kill-new function::
8231 @end menu
8233 @node last-command & this-command, kill-append function, copy-region-as-kill body, copy-region-as-kill body
8234 @ifnottex
8235 @unnumberedsubsubsec @code{last-command} and @code{this-command}
8236 @end ifnottex
8238 Normally, whenever a function is executed, Emacs sets the value of
8239 @code{this-command} to the function being executed (which in this case
8240 would be @code{copy-region-as-kill}).  At the same time, Emacs sets
8241 the value of @code{last-command} to the previous value of
8242 @code{this-command}.
8244 In the first part of the body of the @code{copy-region-as-kill}
8245 function, an @code{if} expression determines whether the value of
8246 @code{last-command} is @code{kill-region}.  If so, the then-part of
8247 the @code{if} expression is evaluated; it uses the @code{kill-append}
8248 function to concatenate the text copied at this call to the function
8249 with the text already in the first element (the @sc{car}) of the kill
8250 ring.  On the other hand, if the value of @code{last-command} is not
8251 @code{kill-region}, then the @code{copy-region-as-kill} function
8252 attaches a new element to the kill ring using the @code{kill-new}
8253 function.
8255 @need 1250
8256 The @code{if} expression reads as follows; it uses @code{eq}, which is
8257 a function we have not yet seen:
8259 @smallexample
8260 @group
8261   (if (eq last-command 'kill-region)
8262       ;; @r{then-part}
8263       (kill-append (buffer-substring beg end) (< end beg))
8264     ;; @r{else-part}
8265     (kill-new (buffer-substring beg end)))
8266 @end group
8267 @end smallexample
8269 @findex eq @r{(example of use)}
8270 @noindent
8271 The @code{eq} function tests whether its first argument is the same Lisp
8272 object as its second argument.  The @code{eq} function is similar to the
8273 @code{equal} function in that it is used to test for equality, but
8274 differs in that it determines whether two representations are actually
8275 the same object inside the computer, but with different names.
8276 @code{equal} determines whether the structure and contents of two
8277 expressions are the same.
8279 If the previous command was @code{kill-region}, then the Emacs Lisp
8280 interpreter calls the @code{kill-append} function
8282 @node kill-append function, kill-new function, last-command & this-command, copy-region-as-kill body
8283 @unnumberedsubsubsec The @code{kill-append} function
8284 @findex kill-append
8286 @need 800
8287 The @code{kill-append} function looks like this:
8289 @smallexample
8290 @group
8291 (defun kill-append (string before-p)
8292   "Append STRING to the end of the latest kill in the kill ring.
8293 If BEFORE-P is non-nil, prepend STRING to the kill.
8294 If `interprogram-cut-function' is set, pass the resulting kill to
8295 it."
8296   (kill-new (if before-p
8297                 (concat string (car kill-ring))
8298               (concat (car kill-ring) string))
8299             t))
8300 @end group
8301 @end smallexample
8303 @noindent
8304 The @code{kill-append} function is fairly straightforward.  It uses
8305 the @code{kill-new} function, which we will discuss in more detail in
8306 a moment.
8308 First, let us look at the conditional that is one of the two arguments
8309 to @code{kill-new}.  It uses @code{concat} to concatenate the new text
8310 to the @sc{car} of the kill ring.  Whether it prepends or appends the
8311 text depends on the results of an @code{if} expression:
8313 @smallexample
8314 @group
8315 (if before-p                            ; @r{if-part}
8316     (concat string (car kill-ring))     ; @r{then-part}
8317   (concat (car kill-ring) string))      ; @r{else-part}
8318 @end group
8319 @end smallexample
8321 @noindent
8322 If the region being killed is before the region that was killed in the
8323 last command, then it should be prepended before the material that was
8324 saved in the previous kill; and conversely, if the killed text follows
8325 what was just killed, it should be appended after the previous text.
8326 The @code{if} expression depends on the predicate @code{before-p} to
8327 decide whether the newly saved text should be put before or after the
8328 previously saved text.
8330 The symbol @code{before-p} is the name of one of the arguments to
8331 @code{kill-append}.  When the @code{kill-append} function is
8332 evaluated, it is bound to the value returned by evaluating the actual
8333 argument.  In this case, this is the expression @code{(< end beg)}.
8334 This expression does not directly determine whether the killed text in
8335 this command is located before or after the kill text of the last
8336 command; what it does is determine whether the value of the variable
8337 @code{end} is less than the value of the variable @code{beg}.  If it
8338 is, it means that the user is most likely heading towards the
8339 beginning of the buffer.  Also, the result of evaluating the predicate
8340 expression, @code{(< end beg)}, will be true and the text will be
8341 prepended before the previous text.  On the other hand, if the value of
8342 the variable @code{end} is greater than the value of the variable
8343 @code{beg}, the text will be appended after the previous text.
8345 @need 800
8346 When the newly saved text will be prepended, then the string with the new
8347 text will be concatenated before the old text:
8349 @smallexample
8350 (concat string (car kill-ring))
8351 @end smallexample
8353 @need 1200
8354 @noindent
8355 But if the text will be appended, it will be concatenated
8356 after the old text:
8358 @smallexample
8359 (concat (car kill-ring) string))
8360 @end smallexample
8362 To understand how this works, we first need to review the
8363 @code{concat} function.  The @code{concat} function links together or
8364 unites two strings of text.  The result is a string.  For example:
8366 @smallexample
8367 @group
8368 (concat "abc" "def")
8369      @result{} "abcdef"
8370 @end group
8372 @group
8373 (concat "new "
8374         (car '("first element" "second element")))
8375      @result{} "new first element"
8377 (concat (car
8378         '("first element" "second element")) " modified")
8379      @result{} "first element modified"
8380 @end group
8381 @end smallexample
8383 We can now make sense of @code{kill-append}: it modifies the contents
8384 of the kill ring.  The kill ring is a list, each element of which is
8385 saved text.  The @code{kill-append} function uses the @code{kill-new}
8386 function which in turn uses the @code{setcar} function.
8388 @node kill-new function,  , kill-append function, copy-region-as-kill body
8389 @unnumberedsubsubsec The @code{kill-new} function
8390 @findex kill-new
8392 @need 1200
8393 The @code{kill-new} function looks like this:
8395 @smallexample
8396 @group
8397 (defun kill-new (string &optional replace)
8398   "Make STRING the latest kill in the kill ring.
8399 Set the kill-ring-yank pointer to point to it.
8400 If `interprogram-cut-function' is non-nil, apply it to STRING.
8401 Optional second argument REPLACE non-nil means that STRING will replace
8402 the front of the kill ring, rather than being added to the list."
8403 @end group
8404 @group
8405   (and (fboundp 'menu-bar-update-yank-menu)
8406        (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8407 @end group
8408 @group
8409   (if (and replace kill-ring)
8410       (setcar kill-ring string)
8411     (setq kill-ring (cons string kill-ring))
8412     (if (> (length kill-ring) kill-ring-max)
8413         (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8414 @end group
8415 @group
8416   (setq kill-ring-yank-pointer kill-ring)
8417   (if interprogram-cut-function
8418       (funcall interprogram-cut-function string (not replace))))
8419 @end group
8420 @end smallexample
8422 As usual, we can look at this function in parts.
8424 @need 1200
8425 The first line of the documentation makes sense:
8427 @smallexample
8428 Make STRING the latest kill in the kill ring.
8429 @end smallexample
8431 @noindent
8432 Let's skip over the rest of the documentation for the moment.
8434 Also, let's skip over the first two lines of code, those involving
8435 @code{menu-bar-update-yank-menu}.  We will explain them below.
8437 @need 1200
8438 The critical lines are these:
8440 @smallexample
8441 @group
8442   (if (and replace kill-ring)
8443       ;; @r{then}
8444       (setcar kill-ring string)
8445 @end group
8446 @group
8447     ;; @r{else}
8448     (setq kill-ring (cons string kill-ring))
8449     (if (> (length kill-ring) kill-ring-max)
8450         ;; @r{avoid overly long kill ring}
8451         (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8452 @end group
8453 @group
8454   (setq kill-ring-yank-pointer kill-ring)
8455   (if interprogram-cut-function
8456       (funcall interprogram-cut-function string (not replace))))
8457 @end group
8458 @end smallexample
8460 The conditional test is @w{@code{(and replace kill-ring)}}.
8461 This will be true when two conditions are met:  the kill ring has
8462 something in it, and the @code{replace} variable is true.
8464 @need 1250
8465 The @code{kill-append} function sets @code{replace} to be true; then,
8466 when the kill ring has at least one item in it, the @code{setcar}
8467 expression is executed:
8469 @smallexample
8470 (setcar kill-ring string)
8471 @end smallexample
8473 The @code{setcar} function actually changes the first element of the
8474 @code{kill-ring} list to the value of @code{string}.  It replaces the
8475 first element.
8477 On the other hand, if the kill ring is empty, or replace is false, the
8478 else-part of the condition is executed:
8480 @smallexample
8481 @group
8482 (setq kill-ring (cons string kill-ring))
8483 (if (> (length kill-ring) kill-ring-max)
8484     (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8485 @end group
8486 @end smallexample
8488 @noindent
8489 This expression first constructs a new version of the kill ring by
8490 prepending @code{string} to the existing kill ring as a new element.
8491 Then it executes a second @code{if} clause.  This second @code{if}
8492 clause keeps the kill ring from growing too long.
8494 Let's look at these two expressions in order.
8496 The @code{setq} line of the else-part sets the new value of the kill
8497 ring to what results from adding the string being killed to the old kill
8498 ring.
8500 @need 800
8501 We can see how this works with an example:
8503 @smallexample
8504 (setq example-list '("here is a clause" "another clause"))
8505 @end smallexample
8507 @need 1200
8508 @noindent
8509 After evaluating this expression with @kbd{C-x C-e}, you can evaluate
8510 @code{example-list} and see what it returns:
8512 @smallexample
8513 @group
8514 example-list
8515      @result{} ("here is a clause" "another clause")
8516 @end group
8517 @end smallexample
8519 @need 1200
8520 @noindent
8521 Now, we can add a new element on to this list by evaluating the
8522 following expression:
8523 @findex cons, @r{example}
8525 @smallexample
8526 (setq example-list (cons "a third clause" example-list))
8527 @end smallexample
8529 @need 800
8530 @noindent
8531 When we evaluate @code{example-list}, we find its value is:
8533 @smallexample
8534 @group
8535 example-list
8536      @result{} ("a third clause" "here is a clause" "another clause")
8537 @end group
8538 @end smallexample
8540 @noindent
8541 Thus, the third clause was added to the list by @code{cons}.
8543 @need 1200
8544 This is exactly similar to what the @code{setq} and @code{cons} do in
8545 the function.  Here is the line again:
8547 @smallexample
8548 (setq kill-ring (cons string kill-ring))
8549 @end smallexample
8551 @need 1200
8552 Now for the second part of the @code{if} clause.  This expression
8553 keeps the kill ring from growing too long.  It looks like this:
8555 @smallexample
8556 @group
8557 (if (> (length kill-ring) kill-ring-max)
8558     (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8559 @end group
8560 @end smallexample
8562 The code checks whether the length of the kill ring is greater than
8563 the maximum permitted length.  This is the value of
8564 @code{kill-ring-max} (which is 60, by default).  If the length of the
8565 kill ring is too long, then this code sets the last element of the
8566 kill ring to @code{nil}.  It does this by using two functions,
8567 @code{nthcdr} and @code{setcdr}.
8569 We looked at @code{setcdr} earlier (@pxref{setcdr, , @code{setcdr}}).
8570 It sets the @sc{cdr} of a list, just as @code{setcar} sets the
8571 @sc{car} of a list.  In this case, however, @code{setcdr} will not be
8572 setting the @sc{cdr} of the whole kill ring; the @code{nthcdr}
8573 function is used to cause it to set the @sc{cdr} of the next to last
8574 element of the kill ring---this means that since the @sc{cdr} of the
8575 next to last element is the last element of the kill ring, it will set
8576 the last element of the kill ring.
8578 @findex nthcdr, @r{example}
8579 The @code{nthcdr} function works by repeatedly taking the @sc{cdr} of a
8580 list---it takes the @sc{cdr} of the @sc{cdr} of the @sc{cdr}
8581 @dots{}  It does this @var{N} times and returns the results.
8583 @findex setcdr, @r{example}
8584 Thus, if we had a four element list that was supposed to be three
8585 elements long, we could set the @sc{cdr} of the next to last element
8586 to @code{nil}, and thereby shorten the list.  (If you sent the last
8587 element to some other value than @code{nil}, which you could do, then
8588 you would not have shortened the list.)
8590 You can see shortening by evaluating the following three expressions
8591 in turn.  First set the value of @code{trees} to @code{(maple oak pine
8592 birch)}, then set the @sc{cdr} of its second @sc{cdr} to @code{nil}
8593 and then find the value of @code{trees}:
8595 @smallexample
8596 @group
8597 (setq trees '(maple oak pine birch))
8598      @result{} (maple oak pine birch)
8599 @end group
8601 @group
8602 (setcdr (nthcdr 2 trees) nil)
8603      @result{} nil
8605 trees
8606      @result{} (maple oak pine)
8607 @end group
8608 @end smallexample
8610 @noindent
8611 (The value returned by the @code{setcdr} expression is @code{nil} since
8612 that is what the @sc{cdr} is set to.)
8614 To repeat, in @code{kill-new}, the @code{nthcdr} function takes the
8615 @sc{cdr} a number of times that is one less than the maximum permitted
8616 size of the kill ring and sets the @sc{cdr} of that element (which
8617 will be the rest of the elements in the kill ring) to @code{nil}.
8618 This prevents the kill ring from growing too long.
8620 @need 800
8621 The next to last expression in the @code{kill-new} function is
8623 @smallexample
8624 (setq kill-ring-yank-pointer kill-ring)
8625 @end smallexample
8627 The @code{kill-ring-yank-pointer} is a global variable that is set to be
8628 the @code{kill-ring}.
8630 Even though the @code{kill-ring-yank-pointer} is called a
8631 @samp{pointer}, it is a variable just like the kill ring.  However, the
8632 name has been chosen to help humans understand how the variable is used.
8633 The variable is used in functions such as @code{yank} and
8634 @code{yank-pop} (@pxref{Yanking, , Yanking Text Back}).
8636 @need 1200
8637 Now, to return to the first two lines in the body of the function:
8639 @smallexample
8640 @group
8641   (and (fboundp 'menu-bar-update-yank-menu)
8642        (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8643 @end group
8644 @end smallexample
8646 @noindent
8647 This is an expression whose first element is the function @code{and}.
8649 @findex and, @r{introduced}
8650 The @code{and} special form evaluates each of its arguments until one of
8651 the arguments returns a value of @code{nil}, in which case the
8652 @code{and} expression returns @code{nil}; however, if none of the
8653 arguments returns a value of @code{nil}, the value resulting from
8654 evaluating the last argument is returned.  (Since such a value is not
8655 @code{nil}, it is considered true in Emacs Lisp.)  In other words, an
8656 @code{and} expression returns a true value only if all its arguments
8657 are true.
8658 @findex and
8660 In this case, the expression tests first to see whether
8661 @code{menu-bar-update-yank-menu} exists as a function, and if so,
8662 calls it.  The @code{fboundp} function returns true if the symbol it
8663 is testing has a function definition that `is not void'.  If the
8664 symbol's function definition were void, we would receive an error
8665 message, as we did when we created errors intentionally (@pxref{Making
8666 Errors, , Generate an Error Message}).
8668 @need 1200
8669 Essentially, the @code{and} is an @code{if} expression that reads like
8670 this:
8672 @smallexample
8673 @group
8674 if @var{the-menu-bar-function-exists}
8675   then @var{execute-it}
8676 @end group
8677 @end smallexample
8679 @code{menu-bar-update-yank-menu} is one of the functions that make it
8680 possible to use the `Select and Paste' menu in the Edit item of a menu
8681 bar; using a mouse, you can look at the various pieces of text you
8682 have saved and select one piece to paste.
8684 Finally, the last expression in the @code{kill-new} function adds the
8685 newly copied string to whatever facility exists for copying and
8686 pasting among different programs running in a windowing system.  In
8687 the X Windowing system, for example, the @code{x-select-text} function
8688 takes the string and stores it in memory operated by X.  You can paste
8689 the string in another program, such as an Xterm.
8691 @need 1200
8692 The expression looks like this:
8694 @smallexample
8695 @group
8696   (if interprogram-cut-function
8697       (funcall interprogram-cut-function string (not replace))))
8698 @end group
8699 @end smallexample
8701 If an @code{interprogram-cut-function} exists, then Emacs executes
8702 @code{funcall}, which in turn calls its first argument as a function
8703 and passes the remaining arguments to it.  (Incidentally, as far as I
8704 can see, this @code{if} expression could be replaced by an @code{and}
8705 expression similar to the one in the first part of the function.)
8707 We are not going to discuss windowing systems and other programs
8708 further, but merely note that this is a mechanism that enables GNU
8709 Emacs to work easily and well with other programs.
8711 This code for placing text in the kill ring, either concatenated with
8712 an existing element or as a new element, leads us to the code for
8713 bringing back text that has been cut out of the buffer---the yank
8714 commands.  However, before discussing the yank commands, it is better
8715 to learn how lists are implemented in a computer.  This will make
8716 clear such mysteries as the use of the term `pointer'.
8718 @need 1250
8719 @node cons & search-fwd Review, search Exercises, copy-region-as-kill, Cutting & Storing Text
8720 @comment  node-name,  next,  previous,  up
8721 @section Review
8723 Here is a brief summary of some recently introduced functions.
8725 @table @code
8726 @item car
8727 @itemx cdr
8728 @code{car} returns the first element of a list; @code{cdr} returns the
8729 second and subsequent elements of a list.
8731 @need 1250
8732 For example:
8734 @smallexample
8735 @group
8736 (car '(1 2 3 4 5 6 7))
8737      @result{} 1
8738 (cdr '(1 2 3 4 5 6 7))
8739      @result{} (2 3 4 5 6 7)
8740 @end group
8741 @end smallexample
8743 @item cons
8744 @code{cons} constructs a list by prepending its first argument to its
8745 second argument.
8747 @need 1250
8748 For example:
8750 @smallexample
8751 @group
8752 (cons 1 '(2 3 4))
8753      @result{} (1 2 3 4)
8754 @end group
8755 @end smallexample
8757 @item nthcdr
8758 Return the result of taking @sc{cdr} `n' times on a list.
8759 @iftex
8761 @tex
8762 $n^{th}$
8763 @end tex
8764 @code{cdr}.
8765 @end iftex
8766 The `rest of the rest', as it were.
8768 @need 1250
8769 For example:
8771 @smallexample
8772 @group
8773 (nthcdr 3 '(1 2 3 4 5 6 7))
8774      @result{} (4 5 6 7)
8775 @end group
8776 @end smallexample
8778 @item setcar
8779 @itemx setcdr
8780 @code{setcar} changes the first element of a list; @code{setcdr}
8781 changes the second and subsequent elements of a list.
8783 @need 1250
8784 For example:
8786 @smallexample
8787 @group
8788 (setq triple '(1 2 3))
8790 (setcar triple '37)
8792 triple
8793      @result{} (37 2 3)
8795 (setcdr triple '("foo" "bar"))
8797 triple
8798      @result{} (37 "foo" "bar")
8799 @end group
8800 @end smallexample
8802 @item progn
8803 Evaluate each argument in sequence and then return the value of the
8804 last.
8806 @need 1250
8807 For example:
8809 @smallexample
8810 @group
8811 (progn 1 2 3 4)
8812      @result{} 4
8813 @end group
8814 @end smallexample
8816 @item save-restriction
8817 Record whatever narrowing is in effect in the current buffer, if any,
8818 and restore that narrowing after evaluating the arguments.
8820 @item search-forward
8821 Search for a string, and if the string is found, move point.
8823 @need 1250
8824 @noindent
8825 Takes four arguments:
8827 @enumerate
8828 @item
8829 The string to search for.
8831 @item
8832 Optionally, the limit of the search.
8834 @item
8835 Optionally, what to do if the search fails, return @code{nil} or an
8836 error message.
8838 @item
8839 Optionally, how many times to repeat the search; if negative, the
8840 search goes backwards.
8841 @end enumerate
8843 @item kill-region
8844 @itemx delete-and-extract-region
8845 @itemx copy-region-as-kill
8847 @code{kill-region} cuts the text between point and mark from the
8848 buffer and stores that text in the kill ring, so you can get it back
8849 by yanking.
8851 @code{delete-and-extract-region} removes the text between point and
8852 mark from the buffer and throws it away.  You cannot get it back.
8854 @code{copy-region-as-kill} copies the text between point and mark into
8855 the kill ring, from which you can get it by yanking.  The function
8856 does not cut or remove the text from the buffer.
8857 @end table
8859 @need 1500
8860 @node search Exercises,  , cons & search-fwd Review, Cutting & Storing Text
8861 @section Searching Exercises
8863 @itemize @bullet
8864 @item
8865 Write an interactive function that searches for a string.  If the
8866 search finds the string, leave point after it and display a message
8867 that says ``Found!''.  (Do not use @code{search-forward} for the name
8868 of this function; if you do, you will overwrite the existing version of
8869 @code{search-forward} that comes with Emacs.  Use a name such as
8870 @code{test-search} instead.)
8872 @item
8873 Write a function that prints the third element of the kill ring in the
8874 echo area, if any; if the kill ring does not contain a third element,
8875 print an appropriate message.
8876 @end itemize
8878 @node List Implementation, Yanking, Cutting & Storing Text, Top
8879 @comment  node-name,  next,  previous,  up
8880 @chapter How Lists are Implemented
8881 @cindex Lists in a computer
8883 In Lisp, atoms are recorded in a straightforward fashion; if the
8884 implementation is not straightforward in practice, it is, nonetheless,
8885 straightforward in theory.  The atom @samp{rose}, for example, is
8886 recorded as the four contiguous letters @samp{r}, @samp{o}, @samp{s},
8887 @samp{e}.  A list, on the other hand, is kept differently.  The mechanism
8888 is equally simple, but it takes a moment to get used to the idea.  A
8889 list is kept using a series of pairs of pointers.  In the series, the
8890 first pointer in each pair points to an atom or to another list, and the
8891 second pointer in each pair points to the next pair, or to the symbol
8892 @code{nil}, which marks the end of the list.
8894 A pointer itself is quite simply the electronic address of what is
8895 pointed to.  Hence, a list is kept as a series of electronic addresses.
8897 @menu
8898 * Lists diagrammed::
8899 * Symbols as Chest::            Exploring a powerful metaphor.
8900 * List Exercise::
8901 @end menu
8903 @node Lists diagrammed, Symbols as Chest, List Implementation, List Implementation
8904 @ifnottex
8905 @unnumberedsec Lists diagrammed
8906 @end ifnottex
8908 For example, the list @code{(rose violet buttercup)} has three elements,
8909 @samp{rose}, @samp{violet}, and @samp{buttercup}.  In the computer, the
8910 electronic address of @samp{rose} is recorded in a segment of computer
8911 memory along with the address that gives the electronic address of where
8912 the atom @samp{violet} is located; and that address (the one that tells
8913 where @samp{violet} is located) is kept along with an address that tells
8914 where the address for the atom @samp{buttercup} is located.
8916 @need 1200
8917 This sounds more complicated than it is and is easier seen in a diagram:
8919 @c clear print-postscript-figures
8920 @c !!! cons-cell-diagram #1
8921 @ifnottex
8922 @smallexample
8923 @group
8924     ___ ___      ___ ___      ___ ___
8925    |___|___|--> |___|___|--> |___|___|--> nil
8926      |            |            |
8927      |            |            |
8928       --> rose     --> violet   --> buttercup
8929 @end group
8930 @end smallexample
8931 @end ifnottex
8932 @ifset print-postscript-figures
8933 @sp 1
8934 @tex
8935 @image{cons-1}
8936 %%%% old method of including an image
8937 % \input /usr/local/lib/tex/inputs/psfig.tex
8938 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-1.eps}}
8939 % \catcode`\@=0 %
8940 @end tex
8941 @sp 1
8942 @end ifset
8943 @ifclear print-postscript-figures
8944 @iftex
8945 @smallexample
8946 @group
8947     ___ ___      ___ ___      ___ ___
8948    |___|___|--> |___|___|--> |___|___|--> nil
8949      |            |            |
8950      |            |            |
8951       --> rose     --> violet   --> buttercup
8952 @end group
8953 @end smallexample
8954 @end iftex
8955 @end ifclear
8957 @noindent
8958 In the diagram, each box represents a word of computer memory that
8959 holds a Lisp object, usually in the form of a memory address.  The boxes,
8960 i.e.@: the addresses, are in pairs.  Each arrow points to what the address
8961 is the address of, either an atom or another pair of addresses.  The
8962 first box is the electronic address of @samp{rose} and the arrow points
8963 to @samp{rose}; the second box is the address of the next pair of boxes,
8964 the first part of which is the address of @samp{violet} and the second
8965 part of which is the address of the next pair.  The very last box
8966 points to the symbol @code{nil}, which marks the end of the list.
8968 @need 1200
8969 When a variable is set to a list with a function such as @code{setq},
8970 it stores the address of the first box in the variable.  Thus,
8971 evaluation of the expression
8973 @smallexample
8974 (setq bouquet '(rose violet buttercup))
8975 @end smallexample
8977 @need 1250
8978 @noindent
8979 creates a situation like this:
8981 @c cons-cell-diagram #2
8982 @ifnottex
8983 @smallexample
8984 @group
8985 bouquet
8986      |
8987      |     ___ ___      ___ ___      ___ ___
8988       --> |___|___|--> |___|___|--> |___|___|--> nil
8989             |            |            |
8990             |            |            |
8991              --> rose     --> violet   --> buttercup
8992 @end group
8993 @end smallexample
8994 @end ifnottex
8995 @ifset print-postscript-figures
8996 @sp 1
8997 @tex
8998 @image{cons-2}
8999 %%%% old method of including an image
9000 % \input /usr/local/lib/tex/inputs/psfig.tex
9001 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2.eps}}
9002 % \catcode`\@=0 %
9003 @end tex
9004 @sp 1
9005 @end ifset
9006 @ifclear print-postscript-figures
9007 @iftex
9008 @smallexample
9009 @group
9010 bouquet
9011      |
9012      |     ___ ___      ___ ___      ___ ___
9013       --> |___|___|--> |___|___|--> |___|___|--> nil
9014             |            |            |
9015             |            |            |
9016              --> rose     --> violet   --> buttercup
9017 @end group
9018 @end smallexample
9019 @end iftex
9020 @end ifclear
9022 @noindent
9023 In this example, the symbol @code{bouquet} holds the address of the first
9024 pair of boxes.
9026 @need 1200
9027 This same list can be illustrated in a different sort of box notation
9028 like this:
9030 @c cons-cell-diagram #2a
9031 @ifnottex
9032 @smallexample
9033 @group
9034 bouquet
9036  |    --------------       ---------------       ----------------
9037  |   | car   | cdr  |     | car    | cdr  |     | car     | cdr  |
9038   -->| rose  |   o------->| violet |   o------->| butter- |  nil |
9039      |       |      |     |        |      |     | cup     |      |
9040       --------------       ---------------       ----------------
9041 @end group
9042 @end smallexample
9043 @end ifnottex
9044 @ifset print-postscript-figures
9045 @sp 1
9046 @tex
9047 @image{cons-2a}
9048 %%%% old method of including an image
9049 % \input /usr/local/lib/tex/inputs/psfig.tex
9050 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2a.eps}}
9051 % \catcode`\@=0 %
9052 @end tex
9053 @sp 1
9054 @end ifset
9055 @ifclear print-postscript-figures
9056 @iftex
9057 @smallexample
9058 @group
9059 bouquet
9061  |    --------------       ---------------       ----------------
9062  |   | car   | cdr  |     | car    | cdr  |     | car     | cdr  |
9063   -->| rose  |   o------->| violet |   o------->| butter- |  nil |
9064      |       |      |     |        |      |     | cup     |      |
9065       --------------       ---------------       ----------------
9066 @end group
9067 @end smallexample
9068 @end iftex
9069 @end ifclear
9071 (Symbols consist of more than pairs of addresses, but the structure of
9072 a symbol is made up of addresses.  Indeed, the symbol @code{bouquet}
9073 consists of a group of address-boxes, one of which is the address of
9074 the printed word @samp{bouquet}, a second of which is the address of a
9075 function definition attached to the symbol, if any, a third of which
9076 is the address of the first pair of address-boxes for the list
9077 @code{(rose violet buttercup)}, and so on.  Here we are showing that
9078 the symbol's third address-box points to the first pair of
9079 address-boxes for the list.)
9081 If a symbol is set to the @sc{cdr} of a list, the list itself is not
9082 changed; the symbol simply has an address further down the list.  (In
9083 the jargon, @sc{car} and @sc{cdr} are `non-destructive'.)  Thus,
9084 evaluation of the following expression
9086 @smallexample
9087 (setq flowers (cdr bouquet))
9088 @end smallexample
9090 @need 800
9091 @noindent
9092 produces this:
9094 @c cons-cell-diagram #3
9095 @ifnottex
9096 @sp 1
9097 @smallexample
9098 @group
9099 bouquet        flowers
9100   |              |
9101   |     ___ ___  |     ___ ___      ___ ___
9102    --> |   |   |  --> |   |   |    |   |   |
9103        |___|___|----> |___|___|--> |___|___|--> nil
9104          |              |            |
9105          |              |            |
9106           --> rose       --> violet   --> buttercup
9107 @end group
9108 @end smallexample
9109 @sp 1
9110 @end ifnottex
9111 @ifset print-postscript-figures
9112 @sp 1
9113 @tex
9114 @image{cons-3}
9115 %%%% old method of including an image
9116 % \input /usr/local/lib/tex/inputs/psfig.tex
9117 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-3.eps}}
9118 % \catcode`\@=0 %
9119 @end tex
9120 @sp 1
9121 @end ifset
9122 @ifclear print-postscript-figures
9123 @iftex
9124 @sp 1
9125 @smallexample
9126 @group
9127 bouquet        flowers
9128   |              |
9129   |     ___ ___  |     ___ ___      ___ ___
9130    --> |   |   |  --> |   |   |    |   |   |
9131        |___|___|----> |___|___|--> |___|___|--> nil
9132          |              |            |
9133          |              |            |
9134           --> rose       --> violet   --> buttercup
9135 @end group
9136 @end smallexample
9137 @sp 1
9138 @end iftex
9139 @end ifclear
9141 @noindent
9142 The value of @code{flowers} is @code{(violet buttercup)}, which is
9143 to say, the symbol @code{flowers} holds the address of the pair of
9144 address-boxes, the first of which holds the address of @code{violet},
9145 and the second of which holds the address of @code{buttercup}.
9147 A pair of address-boxes is called a @dfn{cons cell} or @dfn{dotted
9148 pair}.  @xref{Cons Cell Type, , Cons Cell and List Types, elisp, The GNU Emacs Lisp
9149 Reference Manual}, and @ref{Dotted Pair Notation, , Dotted Pair
9150 Notation, elisp, The GNU Emacs Lisp Reference Manual}, for more
9151 information about cons cells and dotted pairs.
9153 @need 1200
9154 The function @code{cons} adds a new pair of addresses to the front of
9155 a series of addresses like that shown above.  For example, evaluating
9156 the expression
9158 @smallexample
9159 (setq bouquet (cons 'lily bouquet))
9160 @end smallexample
9162 @need 1500
9163 @noindent
9164 produces:
9166 @c cons-cell-diagram #4
9167 @ifnottex
9168 @sp 1
9169 @smallexample
9170 @group
9171 bouquet                       flowers
9172   |                             |
9173   |     ___ ___        ___ ___  |     ___ ___       ___ ___
9174    --> |   |   |      |   |   |  --> |   |   |     |   |   |
9175        |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9176          |              |              |             |
9177          |              |              |             |
9178           --> lily      --> rose       --> violet    --> buttercup
9179 @end group
9180 @end smallexample
9181 @sp 1
9182 @end ifnottex
9183 @ifset print-postscript-figures
9184 @sp 1
9185 @tex
9186 @image{cons-4}
9187 %%%% old method of including an image
9188 % \input /usr/local/lib/tex/inputs/psfig.tex
9189 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-4.eps}}
9190 % \catcode`\@=0 %
9191 @end tex
9192 @sp 1
9193 @end ifset
9194 @ifclear print-postscript-figures
9195 @iftex
9196 @sp 1
9197 @smallexample
9198 @group
9199 bouquet                       flowers
9200   |                             |
9201   |     ___ ___        ___ ___  |     ___ ___       ___ ___
9202    --> |   |   |      |   |   |  --> |   |   |     |   |   |
9203        |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9204          |              |              |             |
9205          |              |              |             |
9206           --> lily      --> rose       --> violet    --> buttercup
9207 @end group
9208 @end smallexample
9209 @sp 1
9210 @end iftex
9211 @end ifclear
9213 @need 1200
9214 @noindent
9215 However, this does not change the value of the symbol
9216 @code{flowers}, as you can see by evaluating the following,
9218 @smallexample
9219 (eq (cdr (cdr bouquet)) flowers)
9220 @end smallexample
9222 @noindent
9223 which returns @code{t} for true.
9225 Until it is reset, @code{flowers} still has the value
9226 @code{(violet buttercup)}; that is, it has the address of the cons
9227 cell whose first address is of @code{violet}.  Also, this does not
9228 alter any of the pre-existing cons cells; they are all still there.
9230 Thus, in Lisp, to get the @sc{cdr} of a list, you just get the address
9231 of the next cons cell in the series; to get the @sc{car} of a list,
9232 you get the address of the first element of the list; to @code{cons} a
9233 new element on a list, you add a new cons cell to the front of the list.
9234 That is all there is to it!  The underlying structure of Lisp is
9235 brilliantly simple!
9237 And what does the last address in a series of cons cells refer to?  It
9238 is the address of the empty list, of @code{nil}.
9240 In summary, when a Lisp variable is set to a value, it is provided with
9241 the address of the list to which the variable refers.
9243 @node Symbols as Chest, List Exercise, Lists diagrammed, List Implementation
9244 @section Symbols as a Chest of Drawers
9245 @cindex Symbols as a Chest of Drawers
9246 @cindex Chest of Drawers, metaphor for a symbol
9247 @cindex Drawers, Chest of, metaphor for a symbol
9249 In an earlier section, I suggested that you might imagine a symbol as
9250 being a chest of drawers.  The function definition is put in one
9251 drawer, the value in another, and so on.  What is put in the drawer
9252 holding the value can be changed without affecting the contents of the
9253 drawer holding the function definition, and vice-versa.
9255 Actually, what is put in each drawer is the address of the value or
9256 function definition.  It is as if you found an old chest in the attic,
9257 and in one of its drawers you found a map giving you directions to
9258 where the buried treasure lies.
9260 (In addition to its name, symbol definition, and variable value, a
9261 symbol has a `drawer' for a @dfn{property list} which can be used to
9262 record other information.  Property lists are not discussed here; see
9263 @ref{Property Lists, , Property Lists, elisp, The GNU Emacs Lisp
9264 Reference Manual}.)
9266 @need 1500
9267 Here is a fanciful representation:
9269 @c chest-of-drawers diagram
9270 @ifnottex
9271 @sp 1
9272 @smallexample
9273 @group
9274             Chest of Drawers            Contents of Drawers
9276             __   o0O0o   __
9277           /                 \
9278          ---------------------
9279         |    directions to    |            [map to]
9280         |     symbol name     |             bouquet
9281         |                     |
9282         +---------------------+
9283         |    directions to    |
9284         |  symbol definition  |             [none]
9285         |                     |
9286         +---------------------+
9287         |    directions to    |            [map to]
9288         |    variable value   |             (rose violet buttercup)
9289         |                     |
9290         +---------------------+
9291         |    directions to    |
9292         |    property list    |             [not described here]
9293         |                     |
9294         +---------------------+
9295         |/                   \|
9296 @end group
9297 @end smallexample
9298 @sp 1
9299 @end ifnottex
9300 @ifset print-postscript-figures
9301 @sp 1
9302 @tex
9303 @image{drawers}
9304 %%%% old method of including an image
9305 % \input /usr/local/lib/tex/inputs/psfig.tex
9306 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/drawers.eps}}
9307 % \catcode`\@=0 %
9308 @end tex
9309 @sp 1
9310 @end ifset
9311 @ifclear print-postscript-figures
9312 @iftex
9313 @sp 1
9314 @smallexample
9315 @group
9316             Chest of Drawers            Contents of Drawers
9318             __   o0O0o   __
9319           /                 \
9320          ---------------------
9321         |    directions to    |            [map to]
9322         |     symbol name     |             bouquet
9323         |                     |
9324         +---------------------+
9325         |    directions to    |
9326         |  symbol definition  |             [none]
9327         |                     |
9328         +---------------------+
9329         |    directions to    |            [map to]
9330         |    variable value   |             (rose violet buttercup)
9331         |                     |
9332         +---------------------+
9333         |    directions to    |
9334         |    property list    |             [not described here]
9335         |                     |
9336         +---------------------+
9337         |/                   \|
9338 @end group
9339 @end smallexample
9340 @sp 1
9341 @end iftex
9342 @end ifclear
9344 @node List Exercise,  , Symbols as Chest, List Implementation
9345 @section Exercise
9347 Set @code{flowers} to @code{violet} and @code{buttercup}.  Cons two
9348 more flowers on to this list and set this new list to
9349 @code{more-flowers}.  Set the @sc{car} of @code{flowers} to a fish.
9350 What does the @code{more-flowers} list now contain?
9352 @node Yanking, Loops & Recursion, List Implementation, Top
9353 @comment  node-name,  next,  previous,  up
9354 @chapter Yanking Text Back
9355 @findex yank
9356 @findex rotate-yank-pointer
9357 @cindex Text retrieval
9358 @cindex Retrieving text
9359 @cindex Pasting text
9361 Whenever you cut text out of a buffer with a `kill' command in GNU Emacs,
9362 you can bring it back with a `yank' command.  The text that is cut out of
9363 the buffer is put in the kill ring and the yank commands insert the
9364 appropriate contents of the kill ring back into a buffer (not necessarily
9365 the original buffer).
9367 A simple @kbd{C-y} (@code{yank}) command inserts the first item from
9368 the kill ring into the current buffer.  If the @kbd{C-y} command is
9369 followed immediately by @kbd{M-y}, the first element is replaced by
9370 the second element.  Successive @kbd{M-y} commands replace the second
9371 element with the third, fourth, or fifth element, and so on.  When the
9372 last element in the kill ring is reached, it is replaced by the first
9373 element and the cycle is repeated.  (Thus the kill ring is called a
9374 `ring' rather than just a `list'.  However, the actual data structure
9375 that holds the text is a list.
9376 @xref{Kill Ring, , Handling the Kill Ring}, for the details of how the
9377 list is handled as a ring.)
9379 @menu
9380 * Kill Ring Overview::          The kill ring is a list.
9381 * kill-ring-yank-pointer::      The @code{kill-ring-yank-pointer} variable.
9382 * yank nthcdr Exercises::
9383 @end menu
9385 @node Kill Ring Overview, kill-ring-yank-pointer, Yanking, Yanking
9386 @comment  node-name,  next,  previous,  up
9387 @section Kill Ring Overview
9388 @cindex Kill ring overview
9390 The kill ring is a list of textual strings.  This is what it looks like:
9392 @smallexample
9393 ("some text" "a different piece of text" "yet more text")
9394 @end smallexample
9396 If this were the contents of my kill ring and I pressed @kbd{C-y}, the
9397 string of characters saying @samp{some text} would be inserted in this
9398 buffer where my cursor is located.
9400 The @code{yank} command is also used for duplicating text by copying it.
9401 The copied text is not cut from the buffer, but a copy of it is put on the
9402 kill ring and is inserted by yanking it back.
9404 Three functions are used for bringing text back from the kill ring:
9405 @code{yank}, which is usually bound to @kbd{C-y}; @code{yank-pop},
9406 which is usually bound to @kbd{M-y}; and @code{rotate-yank-pointer},
9407 which is used by the two other functions.
9409 These functions refer to the kill ring through a variable called the
9410 @code{kill-ring-yank-pointer}.  Indeed, the insertion code for both the
9411 @code{yank} and @code{yank-pop} functions is:
9413 @smallexample
9414 (insert (car kill-ring-yank-pointer))
9415 @end smallexample
9417 To begin to understand how @code{yank} and @code{yank-pop} work, it is
9418 first necessary to look at the @code{kill-ring-yank-pointer} variable
9419 and the @code{rotate-yank-pointer} function.
9421 @node kill-ring-yank-pointer, yank nthcdr Exercises, Kill Ring Overview, Yanking
9422 @comment  node-name,  next,  previous,  up
9423 @section The @code{kill-ring-yank-pointer} Variable
9425 @code{kill-ring-yank-pointer} is a variable, just as @code{kill-ring} is
9426 a variable.  It points to something by being bound to the value of what
9427 it points to, like any other Lisp variable.
9429 @need 1000
9430 Thus, if the value of the kill ring is:
9432 @smallexample
9433 ("some text" "a different piece of text" "yet more text")
9434 @end smallexample
9436 @need 1250
9437 @noindent
9438 and the @code{kill-ring-yank-pointer} points to the second clause, the
9439 value of @code{kill-ring-yank-pointer} is:
9441 @smallexample
9442 ("a different piece of text" "yet more text")
9443 @end smallexample
9445 As explained in the previous chapter (@pxref{List Implementation}), the
9446 computer does not keep two different copies of the text being pointed to
9447 by both the @code{kill-ring} and the @code{kill-ring-yank-pointer}.  The
9448 words ``a different piece of text'' and ``yet more text'' are not
9449 duplicated.  Instead, the two Lisp variables point to the same pieces of
9450 text.  Here is a diagram:
9452 @c cons-cell-diagram #5
9453 @ifnottex
9454 @smallexample
9455 @group
9456 kill-ring     kill-ring-yank-pointer
9457     |               |
9458     |      ___ ___  |     ___ ___      ___ ___
9459      ---> |   |   |  --> |   |   |    |   |   |
9460           |___|___|----> |___|___|--> |___|___|--> nil
9461             |              |            |
9462             |              |            |
9463             |              |             --> "yet more text"
9464             |              |
9465             |               --> "a different piece of text
9466             |
9467              --> "some text"
9468 @end group
9469 @end smallexample
9470 @sp 1
9471 @end ifnottex
9472 @ifset print-postscript-figures
9473 @sp 1
9474 @tex
9475 @image{cons-5}
9476 %%%% old method of including an image
9477 % \input /usr/local/lib/tex/inputs/psfig.tex
9478 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-5.eps}}
9479 % \catcode`\@=0 %
9480 @end tex
9481 @sp 1
9482 @end ifset
9483 @ifclear print-postscript-figures
9484 @iftex
9485 @smallexample
9486 @group
9487 kill-ring     kill-ring-yank-pointer
9488     |               |
9489     |      ___ ___  |     ___ ___      ___ ___
9490      ---> |   |   |  --> |   |   |    |   |   |
9491           |___|___|----> |___|___|--> |___|___|--> nil
9492             |              |            |
9493             |              |            |
9494             |              |             --> "yet more text"
9495             |              |
9496             |               --> "a different piece of text
9497             |
9498              --> "some text"
9499 @end group
9500 @end smallexample
9501 @sp 1
9502 @end iftex
9503 @end ifclear
9505 Both the variable @code{kill-ring} and the variable
9506 @code{kill-ring-yank-pointer} are pointers.  But the kill ring itself is
9507 usually described as if it were actually what it is composed of.  The
9508 @code{kill-ring} is spoken of as if it were the list rather than that it
9509 points to the list.  Conversely, the @code{kill-ring-yank-pointer} is
9510 spoken of as pointing to a list.
9512 These two ways of talking about the same thing sound confusing at first but
9513 make sense on reflection.  The kill ring is generally thought of as the
9514 complete structure of data that holds the information of what has recently
9515 been cut out of the Emacs buffers.  The @code{kill-ring-yank-pointer}
9516 on the other hand, serves to indicate---that is, to `point to'---that part
9517 of the kill ring of which the first element (the @sc{car}) will be
9518 inserted.
9520 The @code{rotate-yank-pointer} function changes the element in the
9521 kill ring to which the @code{kill-ring-yank-pointer} points; when the
9522 pointer is set to point to the next element beyond the end of the kill
9523 ring, it automatically sets it to point to the first element of the
9524 kill ring.  This is how the list is transformed into a ring.  The
9525 @code{rotate-yank-pointer} function itself is not difficult, but
9526 contains many details.  It and the much simpler @code{yank} and
9527 @code{yank-pop} functions are described in an appendix.
9528 @xref{Kill Ring, , Handling the Kill Ring}.
9530 @need 1500
9531 @node yank nthcdr Exercises,  , kill-ring-yank-pointer, Yanking
9532 @section Exercises with @code{yank} and @code{nthcdr}
9534 @itemize @bullet
9535 @item
9536 Using @kbd{C-h v} (@code{describe-variable}), look at the value of
9537 your kill ring.  Add several items to your kill ring; look at its
9538 value again.  Using @kbd{M-y} (@code{yank-pop)}, move all the way
9539 around the kill ring.  How many items were in your kill ring?  Find
9540 the value of @code{kill-ring-max}.  Was your kill ring full, or could
9541 you have kept more blocks of text within it?
9543 @item
9544 Using @code{nthcdr} and @code{car}, construct a series of expressions
9545 to return the first, second, third, and fourth elements of a list.
9546 @end itemize
9548 @node Loops & Recursion, Regexp Search, Yanking, Top
9549 @comment  node-name,  next,  previous,  up
9550 @chapter Loops and Recursion
9551 @cindex Loops and recursion
9552 @cindex Recursion and loops
9553 @cindex Repetition (loops)
9555 Emacs Lisp has two primary ways to cause an expression, or a series of
9556 expressions, to be evaluated repeatedly: one uses a @code{while}
9557 loop, and the other uses @dfn{recursion}.
9559 Repetition can be very valuable.  For example, to move forward four
9560 sentences, you need only write a program that will move forward one
9561 sentence and then repeat the process four times.  Since a computer does
9562 not get bored or tired, such repetitive action does not have the
9563 deleterious effects that excessive or the wrong kinds of repetition can
9564 have on humans.
9566 People mostly write Emacs Lisp functions using @code{while} loops and
9567 their kin; but you can use recursion, which provides a very powerful
9568 way to think about and then to solve problems@footnote{You can write
9569 recursive functions to be frugal or wasteful of mental or computer
9570 resources; as it happens, methods that people find easy---that are
9571 frugal of `mental resources'---sometimes use considerable computer
9572 resources.  Emacs was designed to run on machines that we now consider
9573 limited and its default settings are conservative.  You may want to
9574 increase the values of @code{max-specpdl-size} and
9575 @code{max-lisp-eval-depth}.  In my @file{.emacs} file, I set them to
9576 15 and 30 times their default value.}.
9578 @menu
9579 * while::                       Causing a stretch of code to repeat.
9580 * dolist dotimes::
9581 * Recursion::                   Causing a function to call itself.
9582 * Looping exercise::
9583 @end menu
9585 @node while, dolist dotimes, Loops & Recursion, Loops & Recursion
9586 @comment  node-name,  next,  previous,  up
9587 @section @code{while}
9588 @cindex Loops
9589 @findex while
9591 The @code{while} special form tests whether the value returned by
9592 evaluating its first argument is true or false.  This is similar to what
9593 the Lisp interpreter does with an @code{if}; what the interpreter does
9594 next, however, is different.
9596 In a @code{while} expression, if the value returned by evaluating the
9597 first argument is false, the Lisp interpreter skips the rest of the
9598 expression (the @dfn{body} of the expression) and does not evaluate it.
9599 However, if the value is true, the Lisp interpreter evaluates the body
9600 of the expression and then again tests whether the first argument to
9601 @code{while} is true or false.  If the value returned by evaluating the
9602 first argument is again true, the Lisp interpreter again evaluates the
9603 body of the expression.
9605 @need 1200
9606 The template for a @code{while} expression looks like this:
9608 @smallexample
9609 @group
9610 (while @var{true-or-false-test}
9611   @var{body}@dots{})
9612 @end group
9613 @end smallexample
9615 @menu
9616 * Looping with while::          Repeat so long as test returns true.
9617 * Loop Example::                A @code{while} loop that uses a list.
9618 * print-elements-of-list::      Uses @code{while}, @code{car}, @code{cdr}.
9619 * Incrementing Loop::           A loop with an incrementing counter.
9620 * Decrementing Loop::           A loop with a decrementing counter.
9621 @end menu
9623 @node Looping with while, Loop Example, while, while
9624 @ifnottex
9625 @unnumberedsubsec Looping with @code{while}
9626 @end ifnottex
9628 So long as the true-or-false-test of the @code{while} expression
9629 returns a true value when it is evaluated, the body is repeatedly
9630 evaluated.  This process is called a loop since the Lisp interpreter
9631 repeats the same thing again and again, like an airplane doing a loop.
9632 When the result of evaluating the true-or-false-test is false, the
9633 Lisp interpreter does not evaluate the rest of the @code{while}
9634 expression and `exits the loop'.
9636 Clearly, if the value returned by evaluating the first argument to
9637 @code{while} is always true, the body following will be evaluated
9638 again and again @dots{} and again @dots{} forever.  Conversely, if the
9639 value returned is never true, the expressions in the body will never
9640 be evaluated.  The craft of writing a @code{while} loop consists of
9641 choosing a mechanism such that the true-or-false-test returns true
9642 just the number of times that you want the subsequent expressions to
9643 be evaluated, and then have the test return false.
9645 The value returned by evaluating a @code{while} is the value of the
9646 true-or-false-test.  An interesting consequence of this is that a
9647 @code{while} loop that evaluates without error will return @code{nil}
9648 or false regardless of whether it has looped 1 or 100 times or none at
9649 all.  A @code{while} expression that evaluates successfully never
9650 returns a true value!  What this means is that @code{while} is always
9651 evaluated for its side effects, which is to say, the consequences of
9652 evaluating the expressions within the body of the @code{while} loop.
9653 This makes sense.  It is not the mere act of looping that is desired,
9654 but the consequences of what happens when the expressions in the loop
9655 are repeatedly evaluated.
9657 @node Loop Example, print-elements-of-list, Looping with while, while
9658 @comment  node-name,  next,  previous,  up
9659 @subsection A @code{while} Loop and a List
9661 A common way to control a @code{while} loop is to test whether a list
9662 has any elements.  If it does, the loop is repeated; but if it does not,
9663 the repetition is ended.  Since this is an important technique, we will
9664 create a short example to illustrate it.
9666 A simple way to test whether a list has elements is to evaluate the
9667 list: if it has no elements, it is an empty list and will return the
9668 empty list, @code{()}, which is a synonym for @code{nil} or false.  On
9669 the other hand, a list with elements will return those elements when it
9670 is evaluated.  Since Emacs Lisp considers as true any value that is not
9671 @code{nil}, a list that returns elements will test true in a
9672 @code{while} loop.
9674 @need 1200
9675 For example, you can set the variable @code{empty-list} to @code{nil} by
9676 evaluating the following @code{setq} expression:
9678 @smallexample
9679 (setq empty-list ())
9680 @end smallexample
9682 @noindent
9683 After evaluating the @code{setq} expression, you can evaluate the
9684 variable @code{empty-list} in the usual way, by placing the cursor after
9685 the symbol and typing @kbd{C-x C-e}; @code{nil} will appear in your
9686 echo area:
9688 @smallexample
9689 empty-list
9690 @end smallexample
9692 On the other hand, if you set a variable to be a list with elements, the
9693 list will appear when you evaluate the variable, as you can see by
9694 evaluating the following two expressions:
9696 @smallexample
9697 @group
9698 (setq animals '(gazelle giraffe lion tiger))
9700 animals
9701 @end group
9702 @end smallexample
9704 Thus, to create a @code{while} loop that tests whether there are any
9705 items in the list @code{animals}, the first part of the loop will be
9706 written like this:
9708 @smallexample
9709 @group
9710 (while animals
9711        @dots{}
9712 @end group
9713 @end smallexample
9715 @noindent
9716 When the @code{while} tests its first argument, the variable
9717 @code{animals} is evaluated.  It returns a list.  So long as the list
9718 has elements, the @code{while} considers the results of the test to be
9719 true; but when the list is empty, it considers the results of the test
9720 to be false.
9722 To prevent the @code{while} loop from running forever, some mechanism
9723 needs to be provided to empty the list eventually.  An oft-used
9724 technique is to have one of the subsequent forms in the @code{while}
9725 expression set the value of the list to be the @sc{cdr} of the list.
9726 Each time the @code{cdr} function is evaluated, the list will be made
9727 shorter, until eventually only the empty list will be left.  At this
9728 point, the test of the @code{while} loop will return false, and the
9729 arguments to the @code{while} will no longer be evaluated.
9731 For example, the list of animals bound to the variable @code{animals}
9732 can be set to be the @sc{cdr} of the original list with the
9733 following expression:
9735 @smallexample
9736 (setq animals (cdr animals))
9737 @end smallexample
9739 @noindent
9740 If you have evaluated the previous expressions and then evaluate this
9741 expression, you will see @code{(giraffe lion tiger)} appear in the echo
9742 area.  If you evaluate the expression again, @code{(lion tiger)} will
9743 appear in the echo area.  If you evaluate it again and yet again,
9744 @code{(tiger)} appears and then the empty list, shown by @code{nil}.
9746 A template for a @code{while} loop that uses the @code{cdr} function
9747 repeatedly to cause the true-or-false-test eventually to test false
9748 looks like this:
9750 @smallexample
9751 @group
9752 (while @var{test-whether-list-is-empty}
9753   @var{body}@dots{}
9754   @var{set-list-to-cdr-of-list})
9755 @end group
9756 @end smallexample
9758 This test and use of @code{cdr} can be put together in a function that
9759 goes through a list and prints each element of the list on a line of its
9760 own.
9762 @node print-elements-of-list, Incrementing Loop, Loop Example, while
9763 @subsection An Example: @code{print-elements-of-list}
9764 @findex print-elements-of-list
9766 The @code{print-elements-of-list} function illustrates a @code{while}
9767 loop with a list.
9769 @cindex @file{*scratch*} buffer
9770 The function requires several lines for its output.  If you are
9771 reading this in Emacs 21 or a later version, you can evaluate the
9772 following expression inside of Info, as usual.
9774 If you are using an earlier version of Emacs, you need to copy the
9775 necessary expressions to your @file{*scratch*} buffer and evaluate
9776 them there.  This is because the echo area had only one line in the
9777 earlier versions.
9779 You can copy the expressions by marking the beginning of the region
9780 with @kbd{C-@key{SPC}} (@code{set-mark-command}), moving the cursor to
9781 the end of the region and then copying the region using @kbd{M-w}
9782 (@code{copy-region-as-kill}).  In the @file{*scratch*} buffer, you can
9783 yank the expressions back by typing @kbd{C-y} (@code{yank}).
9785 After you have copied the expressions to the @file{*scratch*} buffer,
9786 evaluate each expression in turn.  Be sure to evaluate the last
9787 expression, @code{(print-elements-of-list animals)}, by typing
9788 @kbd{C-u C-x C-e}, that is, by giving an argument to
9789 @code{eval-last-sexp}.  This will cause the result of the evaluation
9790 to be printed in the @file{*scratch*} buffer instead of being printed
9791 in the echo area.  (Otherwise you will see something like this in your
9792 echo area: @code{^Jgazelle^J^Jgiraffe^J^Jlion^J^Jtiger^Jnil}, in which
9793 each @samp{^J} stands for a `newline'.)
9795 @need 1500
9796 If you are using Emacs 21 or later, you can evaluate these expressions
9797 directly in the Info buffer, and the echo area will grow to show the
9798 results.
9800 @smallexample
9801 @group
9802 (setq animals '(gazelle giraffe lion tiger))
9804 (defun print-elements-of-list (list)
9805   "Print each element of LIST on a line of its own."
9806   (while list
9807     (print (car list))
9808     (setq list (cdr list))))
9810 (print-elements-of-list animals)
9811 @end group
9812 @end smallexample
9814 @need 1200
9815 @noindent
9816 When you evaluate the three expressions in sequence, you will see
9817 this:
9819 @smallexample
9820 @group
9821 gazelle
9823 giraffe
9825 lion
9827 tiger
9829 @end group
9830 @end smallexample
9832 Each element of the list is printed on a line of its own (that is what
9833 the function @code{print} does) and then the value returned by the
9834 function is printed.  Since the last expression in the function is the
9835 @code{while} loop, and since @code{while} loops always return
9836 @code{nil}, a @code{nil} is printed after the last element of the list.
9838 @node Incrementing Loop, Decrementing Loop, print-elements-of-list, while
9839 @comment  node-name,  next,  previous,  up
9840 @subsection A Loop with an Incrementing Counter
9842 A loop is not useful unless it stops when it ought.  Besides
9843 controlling a loop with a list, a common way of stopping a loop is to
9844 write the first argument as a test that returns false when the correct
9845 number of repetitions are complete.  This means that the loop must
9846 have a counter---an expression that counts how many times the loop
9847 repeats itself.
9849 The test can be an expression such as @code{(< count desired-number)}
9850 which returns @code{t} for true if the value of @code{count} is less
9851 than the @code{desired-number} of repetitions and @code{nil} for false if
9852 the value of @code{count} is equal to or is greater than the
9853 @code{desired-number}.  The expression that increments the count can be
9854 a simple @code{setq} such as @code{(setq count (1+ count))}, where
9855 @code{1+} is a built-in function in Emacs Lisp that adds 1 to its
9856 argument.  (The expression @w{@code{(1+ count)}} has the same result as
9857 @w{@code{(+ count 1)}}, but is easier for a human to read.)
9859 @need 1250
9860 The template for a @code{while} loop controlled by an incrementing
9861 counter looks like this:
9863 @smallexample
9864 @group
9865 @var{set-count-to-initial-value}
9866 (while (< count desired-number)         ; @r{true-or-false-test}
9867   @var{body}@dots{}
9868   (setq count (1+ count)))              ; @r{incrementer}
9869 @end group
9870 @end smallexample
9872 @noindent
9873 Note that you need to set the initial value of @code{count}; usually it
9874 is set to 1.
9876 @menu
9877 * Incrementing Example::        Counting pebbles in a triangle.
9878 * Inc Example parts::           The parts of the function definition.
9879 * Inc Example altogether::      Putting the function definition together.
9880 @end menu
9882 @node Incrementing Example, Inc Example parts, Incrementing Loop, Incrementing Loop
9883 @unnumberedsubsubsec  Example with incrementing counter
9885 Suppose you are playing on the beach and decide to make a triangle of
9886 pebbles, putting one pebble in the first row, two in the second row,
9887 three in the third row and so on, like this:
9889 @sp 1
9890 @c pebble diagram
9891 @ifnottex
9892 @smallexample
9893 @group
9894                *
9895               * *
9896              * * *
9897             * * * *
9898 @end group
9899 @end smallexample
9900 @end ifnottex
9901 @iftex
9902 @smallexample
9903 @group
9904                @bullet{}
9905               @bullet{} @bullet{}
9906              @bullet{} @bullet{} @bullet{}
9907             @bullet{} @bullet{} @bullet{} @bullet{}
9908 @end group
9909 @end smallexample
9910 @end iftex
9911 @sp 1
9913 @noindent
9914 (About 2500 years ago, Pythagoras and others developed the beginnings of
9915 number theory by considering questions such as this.)
9917 Suppose you want to know how many pebbles you will need to make a
9918 triangle with 7 rows?
9920 Clearly, what you need to do is add up the numbers from 1 to 7.  There
9921 are two ways to do this; start with the smallest number, one, and add up
9922 the list in sequence, 1, 2, 3, 4 and so on; or start with the largest
9923 number and add the list going down: 7, 6, 5, 4 and so on.  Because both
9924 mechanisms illustrate common ways of writing @code{while} loops, we will
9925 create two examples, one counting up and the other counting down.  In
9926 this first example, we will start with 1 and add 2, 3, 4 and so on.
9928 If you are just adding up a short list of numbers, the easiest way to do
9929 it is to add up all the numbers at once.  However, if you do not know
9930 ahead of time how many numbers your list will have, or if you want to be
9931 prepared for a very long list, then you need to design your addition so
9932 that what you do is repeat a simple process many times instead of doing
9933 a more complex process once.
9935 For example, instead of adding up all the pebbles all at once, what you
9936 can do is add the number of pebbles in the first row, 1, to the number
9937 in the second row, 2, and then add the total of those two rows to the
9938 third row, 3.  Then you can add the number in the fourth row, 4, to the
9939 total of the first three rows; and so on.
9941 The critical characteristic of the process is that each repetitive
9942 action is simple.  In this case, at each step we add only two numbers,
9943 the number of pebbles in the row and the total already found.  This
9944 process of adding two numbers is repeated again and again until the last
9945 row has been added to the total of all the preceding rows.  In a more
9946 complex loop the repetitive action might not be so simple, but it will
9947 be simpler than doing everything all at once.
9949 @node Inc Example parts, Inc Example altogether, Incrementing Example, Incrementing Loop
9950 @unnumberedsubsubsec The parts of the function definition
9952 The preceding analysis gives us the bones of our function definition:
9953 first, we will need a variable that we can call @code{total} that will
9954 be the total number of pebbles.  This will be the value returned by
9955 the function.
9957 Second, we know that the function will require an argument: this
9958 argument will be the total number of rows in the triangle.  It can be
9959 called @code{number-of-rows}.
9961 Finally, we need a variable to use as a counter.  We could call this
9962 variable @code{counter}, but a better name is @code{row-number}.
9963 That is because what the counter does is count rows, and a program
9964 should be written to be as understandable as possible.
9966 When the Lisp interpreter first starts evaluating the expressions in the
9967 function, the value of @code{total} should be set to zero, since we have
9968 not added anything to it.  Then the function should add the number of
9969 pebbles in the first row to the total, and then add the number of
9970 pebbles in the second to the total, and then add the number of
9971 pebbles in the third row to the total, and so on, until there are no
9972 more rows left to add.
9974 Both @code{total} and @code{row-number} are used only inside the
9975 function, so they can be declared as local variables with @code{let}
9976 and given initial values.  Clearly, the initial value for @code{total}
9977 should be 0.  The initial value of @code{row-number} should be 1,
9978 since we start with the first row.  This means that the @code{let}
9979 statement will look like this:
9981 @smallexample
9982 @group
9983   (let ((total 0)
9984         (row-number 1))
9985     @var{body}@dots{})
9986 @end group
9987 @end smallexample
9989 After the internal variables are declared and bound to their initial
9990 values, we can begin the @code{while} loop.  The expression that serves
9991 as the test should return a value of @code{t} for true so long as the
9992 @code{row-number} is less than or equal to the @code{number-of-rows}.
9993 (If the expression tests true only so long as the row number is less
9994 than the number of rows in the triangle, the last row will never be
9995 added to the total; hence the row number has to be either less than or
9996 equal to the number of rows.)
9998 @need 1500
9999 @findex <= @r{(less than or equal)}
10000 Lisp provides the @code{<=} function that returns true if the value of
10001 its first argument is less than or equal to the value of its second
10002 argument and false otherwise.  So the expression that the @code{while}
10003 will evaluate as its test should look like this:
10005 @smallexample
10006 (<= row-number number-of-rows)
10007 @end smallexample
10009 The total number of pebbles can be found by repeatedly adding the number
10010 of pebbles in a row to the total already found.  Since the number of
10011 pebbles in the row is equal to the row number, the total can be found by
10012 adding the row number to the total.  (Clearly, in a more complex
10013 situation, the number of pebbles in the row might be related to the row
10014 number in a more complicated way; if this were the case, the row number
10015 would be replaced by the appropriate expression.)
10017 @smallexample
10018 (setq total (+ total row-number))
10019 @end smallexample
10021 @noindent
10022 What this does is set the new value of @code{total} to be equal to the
10023 sum of adding the number of pebbles in the row to the previous total.
10025 After setting the value of @code{total}, the conditions need to be
10026 established for the next repetition of the loop, if there is one.  This
10027 is done by incrementing the value of the @code{row-number} variable,
10028 which serves as a counter.  After the @code{row-number} variable has
10029 been incremented, the true-or-false-test at the beginning of the
10030 @code{while} loop tests whether its value is still less than or equal to
10031 the value of the @code{number-of-rows} and if it is, adds the new value
10032 of the @code{row-number} variable to the @code{total} of the previous
10033 repetition of the loop.
10035 @need 1200
10036 The built-in Emacs Lisp function @code{1+} adds 1 to a number, so the
10037 @code{row-number} variable can be incremented with this expression:
10039 @smallexample
10040 (setq row-number (1+ row-number))
10041 @end smallexample
10043 @node Inc Example altogether,  , Inc Example parts, Incrementing Loop
10044 @unnumberedsubsubsec Putting the function definition together
10046 We have created the parts for the function definition; now we need to
10047 put them together.
10049 @need 800
10050 First, the contents of the @code{while} expression:
10052 @smallexample
10053 @group
10054 (while (<= row-number number-of-rows)   ; @r{true-or-false-test}
10055   (setq total (+ total row-number))
10056   (setq row-number (1+ row-number)))    ; @r{incrementer}
10057 @end group
10058 @end smallexample
10060 Along with the @code{let} expression varlist, this very nearly
10061 completes the body of the function definition.  However, it requires
10062 one final element, the need for which is somewhat subtle.
10064 The final touch is to place the variable @code{total} on a line by
10065 itself after the @code{while} expression.  Otherwise, the value returned
10066 by the whole function is the value of the last expression that is
10067 evaluated in the body of the @code{let}, and this is the value
10068 returned by the @code{while}, which is always @code{nil}.
10070 This may not be evident at first sight.  It almost looks as if the
10071 incrementing expression is the last expression of the whole function.
10072 But that expression is part of the body of the @code{while}; it is the
10073 last element of the list that starts with the symbol @code{while}.
10074 Moreover, the whole of the @code{while} loop is a list within the body
10075 of the @code{let}.
10077 @need 1250
10078 In outline, the function will look like this:
10080 @smallexample
10081 @group
10082 (defun @var{name-of-function} (@var{argument-list})
10083   "@var{documentation}@dots{}"
10084   (let (@var{varlist})
10085     (while (@var{true-or-false-test})
10086       @var{body-of-while}@dots{} )
10087     @dots{} )                     ; @r{Need final expression here.}
10088 @end group
10089 @end smallexample
10091 The result of evaluating the @code{let} is what is going to be returned
10092 by the @code{defun} since the @code{let} is not embedded within any
10093 containing list, except for the @code{defun} as a whole.  However, if
10094 the @code{while} is the last element of the @code{let} expression, the
10095 function will always return @code{nil}.  This is not what we want!
10096 Instead, what we want is the value of the variable @code{total}.  This
10097 is returned by simply placing the symbol as the last element of the list
10098 starting with @code{let}.  It gets evaluated after the preceding
10099 elements of the list are evaluated, which means it gets evaluated after
10100 it has been assigned the correct value for the total.
10102 It may be easier to see this by printing the list starting with
10103 @code{let} all on one line.  This format makes it evident that the
10104 @var{varlist} and @code{while} expressions are the second and third
10105 elements of the list starting with @code{let}, and the @code{total} is
10106 the last element:
10108 @smallexample
10109 @group
10110 (let (@var{varlist}) (while (@var{true-or-false-test}) @var{body-of-while}@dots{} ) total)
10111 @end group
10112 @end smallexample
10114 @need 1200
10115 Putting everything together, the @code{triangle} function definition
10116 looks like this:
10118 @smallexample
10119 @group
10120 (defun triangle (number-of-rows)    ; @r{Version with}
10121                                     ; @r{  incrementing counter.}
10122   "Add up the number of pebbles in a triangle.
10123 The first row has one pebble, the second row two pebbles,
10124 the third row three pebbles, and so on.
10125 The argument is NUMBER-OF-ROWS."
10126 @end group
10127 @group
10128   (let ((total 0)
10129         (row-number 1))
10130     (while (<= row-number number-of-rows)
10131       (setq total (+ total row-number))
10132       (setq row-number (1+ row-number)))
10133     total))
10134 @end group
10135 @end smallexample
10137 @need 1200
10138 After you have installed @code{triangle} by evaluating the function, you
10139 can try it out.  Here are two examples:
10141 @smallexample
10142 @group
10143 (triangle 4)
10145 (triangle 7)
10146 @end group
10147 @end smallexample
10149 @noindent
10150 The sum of the first four numbers is 10 and the sum of the first seven
10151 numbers is 28.
10153 @node Decrementing Loop,  , Incrementing Loop, while
10154 @comment  node-name,  next,  previous,  up
10155 @subsection Loop with a Decrementing Counter
10157 Another common way to write a @code{while} loop is to write the test
10158 so that it determines whether a counter is greater than zero.  So long
10159 as the counter is greater than zero, the loop is repeated.  But when
10160 the counter is equal to or less than zero, the loop is stopped.  For
10161 this to work, the counter has to start out greater than zero and then
10162 be made smaller and smaller by a form that is evaluated
10163 repeatedly.
10165 The test will be an expression such as @code{(> counter 0)} which
10166 returns @code{t} for true if the value of @code{counter} is greater
10167 than zero, and @code{nil} for false if the value of @code{counter} is
10168 equal to or less than zero.  The expression that makes the number
10169 smaller and smaller can be a simple @code{setq} such as @code{(setq
10170 counter (1- counter))}, where @code{1-} is a built-in function in
10171 Emacs Lisp that subtracts 1 from its argument.
10173 @need 1250
10174 The template for a decrementing @code{while} loop looks like this:
10176 @smallexample
10177 @group
10178 (while (> counter 0)                    ; @r{true-or-false-test}
10179   @var{body}@dots{}
10180   (setq counter (1- counter)))          ; @r{decrementer}
10181 @end group
10182 @end smallexample
10184 @menu
10185 * Decrementing Example::        More pebbles on the beach.
10186 * Dec Example parts::           The parts of the function definition.
10187 * Dec Example altogether::      Putting the function definition together.
10188 @end menu
10190 @node Decrementing Example, Dec Example parts, Decrementing Loop, Decrementing Loop
10191 @unnumberedsubsubsec Example with decrementing counter
10193 To illustrate a loop with a decrementing counter, we will rewrite the
10194 @code{triangle} function so the counter decreases to zero.
10196 This is the reverse of the earlier version of the function.  In this
10197 case, to find out how many pebbles are needed to make a triangle with
10198 3 rows, add the number of pebbles in the third row, 3, to the number
10199 in the preceding row, 2, and then add the total of those two rows to
10200 the row that precedes them, which is 1.
10202 Likewise, to find the number of pebbles in a triangle with 7 rows, add
10203 the number of pebbles in the seventh row, 7, to the number in the
10204 preceding row, which is 6, and then add the total of those two rows to
10205 the row that precedes them, which is 5, and so on.  As in the previous
10206 example, each addition only involves adding two numbers, the total of
10207 the rows already added up and the number of pebbles in the row that is
10208 being added to the total.  This process of adding two numbers is
10209 repeated again and again until there are no more pebbles to add.
10211 We know how many pebbles to start with: the number of pebbles in the
10212 last row is equal to the number of rows.  If the triangle has seven
10213 rows, the number of pebbles in the last row is 7.  Likewise, we know how
10214 many pebbles are in the preceding row: it is one less than the number in
10215 the row.
10217 @node Dec Example parts, Dec Example altogether, Decrementing Example, Decrementing Loop
10218 @unnumberedsubsubsec The parts of the function definition
10220 We start with three variables: the total number of rows in the
10221 triangle; the number of pebbles in a row; and the total number of
10222 pebbles, which is what we want to calculate.  These variables can be
10223 named @code{number-of-rows}, @code{number-of-pebbles-in-row}, and
10224 @code{total}, respectively.
10226 Both @code{total} and @code{number-of-pebbles-in-row} are used only
10227 inside the function and are declared with @code{let}.  The initial
10228 value of @code{total} should, of course, be zero.  However, the
10229 initial value of @code{number-of-pebbles-in-row} should be equal to
10230 the number of rows in the triangle, since the addition will start with
10231 the longest row.
10233 @need 1250
10234 This means that the beginning of the @code{let} expression will look
10235 like this:
10237 @smallexample
10238 @group
10239 (let ((total 0)
10240       (number-of-pebbles-in-row number-of-rows))
10241   @var{body}@dots{})
10242 @end group
10243 @end smallexample
10245 The total number of pebbles can be found by repeatedly adding the number
10246 of pebbles in a row to the total already found, that is, by repeatedly
10247 evaluating the following expression:
10249 @smallexample
10250 (setq total (+ total number-of-pebbles-in-row))
10251 @end smallexample
10253 @noindent
10254 After the @code{number-of-pebbles-in-row} is added to the @code{total},
10255 the @code{number-of-pebbles-in-row} should be decremented by one, since
10256 the next time the loop repeats, the preceding row will be
10257 added to the total.
10259 The number of pebbles in a preceding row is one less than the number of
10260 pebbles in a row, so the built-in Emacs Lisp function @code{1-} can be
10261 used to compute the number of pebbles in the preceding row.  This can be
10262 done with the following expression:
10264 @smallexample
10265 @group
10266 (setq number-of-pebbles-in-row
10267       (1- number-of-pebbles-in-row))
10268 @end group
10269 @end smallexample
10271 Finally, we know that the @code{while} loop should stop making repeated
10272 additions when there are no pebbles in a row.  So the test for
10273 the @code{while} loop is simply:
10275 @smallexample
10276 (while (> number-of-pebbles-in-row 0)
10277 @end smallexample
10279 @node Dec Example altogether,  , Dec Example parts, Decrementing Loop
10280 @unnumberedsubsubsec Putting the function definition together
10282 We can put these expressions together to create a function definition
10283 that works.  However, on examination, we find that one of the local
10284 variables is unneeded!
10286 @need 1250
10287 The function definition looks like this:
10289 @smallexample
10290 @group
10291 ;;; @r{First subtractive version.}
10292 (defun triangle (number-of-rows)
10293   "Add up the number of pebbles in a triangle."
10294   (let ((total 0)
10295         (number-of-pebbles-in-row number-of-rows))
10296     (while (> number-of-pebbles-in-row 0)
10297       (setq total (+ total number-of-pebbles-in-row))
10298       (setq number-of-pebbles-in-row
10299             (1- number-of-pebbles-in-row)))
10300     total))
10301 @end group
10302 @end smallexample
10304 As written, this function works.
10306 However, we do not need @code{number-of-pebbles-in-row}.
10308 @cindex Argument as local variable
10309 When the @code{triangle} function is evaluated, the symbol
10310 @code{number-of-rows} will be bound to a number, giving it an initial
10311 value.  That number can be changed in the body of the function as if
10312 it were a local variable, without any fear that such a change will
10313 effect the value of the variable outside of the function.  This is a
10314 very useful characteristic of Lisp; it means that the variable
10315 @code{number-of-rows} can be used anywhere in the function where
10316 @code{number-of-pebbles-in-row} is used.
10318 @need 800
10319 Here is a second version of the function written a bit more cleanly:
10321 @smallexample
10322 @group
10323 (defun triangle (number)                ; @r{Second version.}
10324   "Return sum of numbers 1 through NUMBER inclusive."
10325   (let ((total 0))
10326     (while (> number 0)
10327       (setq total (+ total number))
10328       (setq number (1- number)))
10329     total))
10330 @end group
10331 @end smallexample
10333 In brief, a properly written @code{while} loop will consist of three parts:
10335 @enumerate
10336 @item
10337 A test that will return false after the loop has repeated itself the
10338 correct number of times.
10340 @item
10341 An expression the evaluation of which will return the value desired
10342 after being repeatedly evaluated.
10344 @item
10345 An expression to change the value passed to the true-or-false-test so
10346 that the test returns false after the loop has repeated itself the right
10347 number of times.
10348 @end enumerate
10350 @node dolist dotimes, Recursion, while, Loops & Recursion
10351 @comment  node-name,  next,  previous,  up
10352 @section Save your time: @code{dolist} and @code{dotimes}
10354 In addition to @code{while}, both @code{dolist} and @code{dotimes}
10355 provide for looping.  Sometimes these are quicker to write than the
10356 equivalent @code{while} loop.  Both are Lisp macros.  (@xref{Macros, ,
10357 Macros, elisp, The GNU Emacs Lisp Reference Manual}. )
10359 @code{dolist} works like a @code{while} loop that `@sc{cdr}s down a
10360 list':  @code{dolist} automatically shortens the list each time it
10361 loops---takes the @sc{cdr} of the list---and binds the @sc{car} of
10362 each shorter version of the list to the first of its arguments.
10364 @code{dotimes} loops a specific number of times: you specify the number.
10366 @menu
10367 * dolist::
10368 * dotimes::
10369 @end menu
10371 @node dolist, dotimes, dolist dotimes, dolist dotimes
10372 @unnumberedsubsubsec The @code{dolist} Macro
10373 @findex dolist
10375 Suppose, for example, you want to reverse a list, so that
10376 ``first'' ``second'' ``third'' becomes ``third'' ``second'' ``first''.
10378 @need 1250
10379 In practice, you would use the @code{reverse} function, like this:
10381 @smallexample
10382 @group
10383 (setq animals '(gazelle giraffe lion tiger))
10385 (reverse animals)
10386 @end group
10387 @end smallexample
10389 @need 800
10390 @noindent
10391 Here is how you could reverse the list using a @code{while} loop:
10393 @smallexample
10394 @group
10395 (setq animals '(gazelle giraffe lion tiger))
10397 (defun reverse-list-with-while (list)
10398   "Using while, reverse the order of LIST."
10399   (let (value)  ; make sure list starts empty
10400     (while list
10401       (setq value (cons (car list) value))
10402       (setq list (cdr list)))
10403     value))
10405 (reverse-list-with-while animals)
10406 @end group
10407 @end smallexample
10409 @need 800
10410 @noindent
10411 And here is how you could use the @code{dolist} macro:
10413 @smallexample
10414 @group
10415 (setq animals '(gazelle giraffe lion tiger))
10417 (defun reverse-list-with-dolist (list)
10418   "Using dolist, reverse the order of LIST."
10419   (let (value)  ; make sure list starts empty
10420     (dolist (element list value)
10421       (setq value (cons element value)))))
10423 (reverse-list-with-dolist animals)
10424 @end group
10425 @end smallexample
10427 @need 1250
10428 @noindent
10429 In Info, you can place your cursor after the closing parenthesis of
10430 each expression and type @kbd{C-x C-e}; in each case, you should see
10432 @smallexample
10433 (tiger lion giraffe gazelle)
10434 @end smallexample
10436 @noindent
10437 in the echo area.
10439 For this example, the existing @code{reverse} function is obviously best.
10440 The @code{while} loop is just like our first example (@pxref{Loop
10441 Example, , A @code{while} Loop and a List}).  The @code{while} first
10442 checks whether the list has elements; if so, it constructs a new list
10443 by adding the first element of the list to the existing list (which in
10444 the first iteration of the loop is @code{nil}).  Since the second
10445 element is prepended in front of the first element, and the third
10446 element is prepended in front of the second element, the list is reversed.
10448 In the expression using a @code{while} loop,
10449 the @w{@code{(setq list (cdr list))}}
10450 expression shortens the list, so the @code{while} loop eventually
10451 stops.  In addition, it provides the @code{cons} expression with a new
10452 first element by creating a new and shorter list at each repetition of
10453 the loop.
10455 The @code{dolist} expression does very much the same as the
10456 @code{while} expression, except that the @code{dolist} macro does some
10457 of the work you have to do when writing a @code{while} expression.
10459 Like a @code{while} loop, a @code{dolist} loops.  What is different is
10460 that it automatically shortens the list each time it loops --- it
10461 `@sc{cdr}s down the list' on its own --- and it automatically binds
10462 the @sc{car} of each shorter version of the list to the first of its
10463 arguments.
10465 In the example, the @sc{car} of each shorter version of the list is
10466 referred to using the symbol @samp{element}, the list itself is called
10467 @samp{list}, and the value returned is called @samp{value}.  The
10468 remainder of the @code{dolist} expression is the body.
10470 The @code{dolist} expression binds the @sc{car} of each shorter
10471 version of the list to @code{element} and then evaluates the body of
10472 the expression; and repeats the loop.  The result is returned in
10473 @code{value}.
10475 @node dotimes,  , dolist, dolist dotimes
10476 @unnumberedsubsubsec The @code{dotimes} Macro
10477 @findex dotimes
10479 The @code{dotimes} macro is similar to @code{dolist}, except that it
10480 loops a specific number of times.
10482 The first argument to @code{dotimes} is assigned the numbers 0, 1, 2
10483 and so forth each time around the loop, and the value of the third
10484 argument is returned.  You need to provide the value of the second
10485 argument, which is how many times the macro loops.
10487 @need 1250
10488 For example, the following binds the numbers from 0 up to, but not
10489 including, the number 3 to the first argument, @var{number}, and then
10490 constructs a list of the three numbers.  (The first number is 0, the
10491 second number is 1, and the third number is 2; this makes a total of
10492 three numbers in all, starting with zero as the first number.)
10494 @smallexample
10495 @group
10496 (let (value)      ; otherwise a value is a void variable
10497   (dotimes (number 3 value)
10498     (setq value (cons number value))))
10500 @result{} (2 1 0)
10501 @end group
10502 @end smallexample
10504 @noindent
10505 @code{dotimes} returns @code{value}, so the way to use
10506 @code{dotimes} is to operate on some expression @var{number} number of
10507 times and then return the result, either as a list or an atom.
10509 @need 1250
10510 Here is an example of a @code{defun} that uses @code{dotimes} to add
10511 up the number of pebbles in a triangle.
10513 @smallexample
10514 @group
10515 (defun triangle-using-dotimes (number-of-rows)
10516   "Using dotimes, add up the number of pebbles in a triangle."
10517 (let ((total 0))  ; otherwise a total is a void variable
10518   (dotimes (number number-of-rows total)
10519     (setq total (+ total (1+ number))))))
10521 (triangle-using-dotimes 4)
10522 @end group
10523 @end smallexample
10525 @node Recursion, Looping exercise, dolist dotimes, Loops & Recursion
10526 @comment  node-name,  next,  previous,  up
10527 @section Recursion
10528 @cindex Recursion
10530 A recursive function contains code that tells the Lisp interpreter to
10531 call a program that runs exactly like itself, but with slightly
10532 different arguments.  The code runs exactly the same because it has
10533 the same name.  However, even though the program has the same name, it
10534 is not the same entity.  It is different.  In the jargon, it is a
10535 different `instance'.
10537 Eventually, if the program is written correctly, the `slightly
10538 different arguments' will become sufficiently different from the first
10539 arguments that the final instance will stop.
10541 @menu
10542 * Building Robots::             Same model, different serial number ...
10543 * Recursive Definition Parts::  Walk until you stop ...
10544 * Recursion with list::         Using a list as the test whether to recurse.
10545 * Recursive triangle function::
10546 * Recursion with cond::
10547 * Recursive Patterns::          Often used templates.
10548 * No Deferment::                Don't store up work ...
10549 * No deferment solution::
10550 @end menu
10552 @node Building Robots, Recursive Definition Parts, Recursion, Recursion
10553 @comment  node-name,  next,  previous,  up
10554 @subsection Building Robots: Extending the Metaphor
10555 @cindex Building robots
10556 @cindex Robots, building
10558 It is sometimes helpful to think of a running program as a robot that
10559 does a job.  In doing its job, a recursive function calls on a second
10560 robot to help it.  The second robot is identical to the first in every
10561 way, except that the second robot helps the first and has been
10562 passed different arguments than the first.
10564 In a recursive function, the second robot may call a third; and the
10565 third may call a fourth, and so on.  Each of these is a different
10566 entity; but all are clones.
10568 Since each robot has slightly different instructions---the arguments
10569 will differ from one robot to the next---the last robot should know
10570 when to stop.
10572 Let's expand on the metaphor in which a computer program is a robot.
10574 A function definition provides the blueprints for a robot.  When you
10575 install a function definition, that is, when you evaluate a
10576 @code{defun} special form, you install the necessary equipment to
10577 build robots.  It is as if you were in a factory, setting up an
10578 assembly line.  Robots with the same name are built according to the
10579 same blueprints.  So they have, as it were, the same `model number',
10580 but a different `serial number'.
10582 We often say that a recursive function `calls itself'.  What we mean
10583 is that the instructions in a recursive function cause the Lisp
10584 interpreter to run a different function that has the same name and
10585 does the same job as the first, but with different arguments.
10587 It is important that the arguments differ from one instance to the
10588 next; otherwise, the process will never stop.
10590 @node Recursive Definition Parts, Recursion with list, Building Robots, Recursion
10591 @comment  node-name,  next,  previous,  up
10592 @subsection The Parts of a Recursive Definition
10593 @cindex Parts of a Recursive Definition
10594 @cindex Recursive Definition Parts
10596 A recursive function typically contains a conditional expression which
10597 has three parts:
10599 @enumerate
10600 @item
10601 A true-or-false-test that determines whether the function is called
10602 again, here called the @dfn{do-again-test}.
10604 @item
10605 The name of the function.  When this name is called, a new instance of
10606 the function---a new robot, as it were---is created and told what to do.
10608 @item
10609 An expression that returns a different value each time the function is
10610 called, here called the @dfn{next-step-expression}.  Consequently, the
10611 argument (or arguments) passed to the new instance of the function
10612 will be different from that passed to the previous instance.  This
10613 causes the conditional expression, the @dfn{do-again-test}, to test
10614 false after the correct number of repetitions.
10615 @end enumerate
10617 Recursive functions can be much simpler than any other kind of
10618 function.  Indeed, when people first start to use them, they often look
10619 so mysteriously simple as to be incomprehensible.  Like riding a
10620 bicycle, reading a recursive function definition takes a certain knack
10621 which is hard at first but then seems simple.
10623 @need 1200
10624 There are several different common recursive patterns.  A very simple
10625 pattern looks like this:
10627 @smallexample
10628 @group
10629 (defun @var{name-of-recursive-function} (@var{argument-list})
10630   "@var{documentation}@dots{}"
10631   (if @var{do-again-test}
10632     @var{body}@dots{}
10633     (@var{name-of-recursive-function}
10634          @var{next-step-expression})))
10635 @end group
10636 @end smallexample
10638 Each time a recursive function is evaluated, a new instance of it is
10639 created and told what to do.  The arguments tell the instance what to do.
10641 An argument is bound to the value of the next-step-expression.  Each
10642 instance runs with a different value of the next-step-expression.
10644 The value in the next-step-expression is used in the do-again-test.
10646 The value returned by the next-step-expression is passed to the new
10647 instance of the function, which evaluates it (or some
10648 transmogrification of it) to determine whether to continue or stop.
10649 The next-step-expression is designed so that the do-again-test returns
10650 false when the function should no longer be repeated.
10652 The do-again-test is sometimes called the @dfn{stop condition},
10653 since it stops the repetitions when it tests false.
10655 @node Recursion with list, Recursive triangle function, Recursive Definition Parts, Recursion
10656 @comment  node-name,  next,  previous,  up
10657 @subsection Recursion with a List
10659 The example of a @code{while} loop that printed the elements of a list
10660 of numbers can be written recursively.  Here is the code, including
10661 an expression to set the value of the variable @code{animals} to a list.
10663 If you are using Emacs 20 or before, this example must be copied to
10664 the @file{*scratch*} buffer and each expression must be evaluated
10665 there.  Use @kbd{C-u C-x C-e} to evaluate the
10666 @code{(print-elements-recursively animals)} expression so that the
10667 results are printed in the buffer; otherwise the Lisp interpreter will
10668 try to squeeze the results into the one line of the echo area.
10670 Also, place your cursor immediately after the last closing parenthesis
10671 of the @code{print-elements-recursively} function, before the comment.
10672 Otherwise, the Lisp interpreter will try to evaluate the comment.
10674 If you are using Emacs 21 or later, you can evaluate this expression
10675 directly in Info.
10677 @findex print-elements-recursively
10678 @smallexample
10679 @group
10680 (setq animals '(gazelle giraffe lion tiger))
10682 (defun print-elements-recursively (list)
10683   "Print each element of LIST on a line of its own.
10684 Uses recursion."
10685   (if list                              ; @r{do-again-test}
10686       (progn
10687         (print (car list))              ; @r{body}
10688         (print-elements-recursively     ; @r{recursive call}
10689          (cdr list)))))                 ; @r{next-step-expression}
10691 (print-elements-recursively animals)
10692 @end group
10693 @end smallexample
10695 The @code{print-elements-recursively} function first tests whether
10696 there is any content in the list; if there is, the function prints the
10697 first element of the list, the @sc{car} of the list.  Then the
10698 function `invokes itself', but gives itself as its argument, not the
10699 whole list, but the second and subsequent elements of the list, the
10700 @sc{cdr} of the list.
10702 Put another way, if the list is not empty, the function invokes
10703 another instance of code that is similar to the initial code, but is a
10704 different thread of execution, with different arguments than the first
10705 instance.
10707 Put in yet another way, if the list is not empty, the first robot
10708 assemblies a second robot and tells it what to do; the second robot is
10709 a different individual from the first, but is the same model.
10711 When the second evaluation occurs, the @code{if} expression is
10712 evaluated and if true, prints the first element of the list it
10713 receives as its argument (which is the second element of the original
10714 list).  Then the function `calls itself' with the @sc{cdr} of the list
10715 it is invoked with, which (the second time around) is the @sc{cdr} of
10716 the @sc{cdr} of the original list.
10718 Note that although we say that the function `calls itself', what we
10719 mean is that the Lisp interpreter assembles and instructs a new
10720 instance of the program.  The new instance is a clone of the first,
10721 but is a separate individual.
10723 Each time the function `invokes itself', it invokes itself on a
10724 shorter version of the original list.  It creates a new instance that
10725 works on a shorter list.
10727 Eventually, the function invokes itself on an empty list.  It creates
10728 a new instance whose argument is @code{nil}.  The conditional expression
10729 tests the value of @code{list}.  Since the value of @code{list} is
10730 @code{nil}, the @code{if} expression tests false so the then-part is
10731 not evaluated.  The function as a whole then returns @code{nil}.
10733 @need 1200
10734 When you evaluate @code{(print-elements-recursively animals)} in the
10735 @file{*scratch*} buffer, you see this result:
10737 @smallexample
10738 @group
10739 gazelle
10741 giraffe
10743 lion
10745 tiger
10747 @end group
10748 @end smallexample
10750 @node Recursive triangle function, Recursion with cond, Recursion with list, Recursion
10751 @comment  node-name,  next,  previous,  up
10752 @subsection Recursion in Place of a Counter
10753 @findex triangle-recursively
10755 @need 1200
10756 The @code{triangle} function described in a previous section can also
10757 be written recursively.  It looks like this:
10759 @smallexample
10760 @group
10761 (defun triangle-recursively (number)
10762   "Return the sum of the numbers 1 through NUMBER inclusive.
10763 Uses recursion."
10764   (if (= number 1)                    ; @r{do-again-test}
10765       1                               ; @r{then-part}
10766     (+ number                         ; @r{else-part}
10767        (triangle-recursively          ; @r{recursive call}
10768         (1- number)))))               ; @r{next-step-expression}
10770 (triangle-recursively 7)
10771 @end group
10772 @end smallexample
10774 @noindent
10775 You can install this function by evaluating it and then try it by
10776 evaluating @code{(triangle-recursively 7)}.  (Remember to put your
10777 cursor immediately after the last parenthesis of the function
10778 definition, before the comment.)  The function evaluates to 28.
10780 To understand how this function works, let's consider what happens in the
10781 various cases when the function is passed 1, 2, 3, or 4 as the value of
10782 its argument.
10784 @menu
10785 * Recursive Example arg of 1 or 2::
10786 * Recursive Example arg of 3 or 4::
10787 @end menu
10789 @node Recursive Example arg of 1 or 2, Recursive Example arg of 3 or 4, Recursive triangle function, Recursive triangle function
10790 @ifnottex
10791 @unnumberedsubsubsec An argument of 1 or 2
10792 @end ifnottex
10794 First, what happens if the value of the argument is 1?
10796 The function has an @code{if} expression after the documentation
10797 string.  It tests whether the value of @code{number} is equal to 1; if
10798 so, Emacs evaluates the then-part of the @code{if} expression, which
10799 returns the number 1 as the value of the function.  (A triangle with
10800 one row has one pebble in it.)
10802 Suppose, however, that the value of the argument is 2.  In this case,
10803 Emacs evaluates the else-part of the @code{if} expression.
10805 @need 1200
10806 The else-part consists of an addition, the recursive call to
10807 @code{triangle-recursively} and a decrementing action; and it looks like
10808 this:
10810 @smallexample
10811 (+ number (triangle-recursively (1- number)))
10812 @end smallexample
10814 When Emacs evaluates this expression, the innermost expression is
10815 evaluated first; then the other parts in sequence.  Here are the steps
10816 in detail:
10818 @table @i
10819 @item Step 1 @w{  } Evaluate the innermost expression.
10821 The innermost expression is @code{(1- number)} so Emacs decrements the
10822 value of @code{number} from 2 to 1.
10824 @item Step 2 @w{  } Evaluate the @code{triangle-recursively} function.
10826 The Lisp interpreter creates an individual instance of
10827 @code{triangle-recursively}.  It does not matter that this function is
10828 contained within itself.  Emacs passes the result Step 1 as the
10829 argument used by this instance of the @code{triangle-recursively}
10830 function
10832 In this case, Emacs evaluates @code{triangle-recursively} with an
10833 argument of 1.  This means that this evaluation of
10834 @code{triangle-recursively} returns 1.
10836 @item Step 3 @w{  } Evaluate the value of @code{number}.
10838 The variable @code{number} is the second element of the list that
10839 starts with @code{+}; its value is 2.
10841 @item Step 4 @w{  } Evaluate the @code{+} expression.
10843 The @code{+} expression receives two arguments, the first
10844 from the evaluation of @code{number} (Step 3) and the second from the
10845 evaluation of @code{triangle-recursively} (Step 2).
10847 The result of the addition is the sum of 2 plus 1, and the number 3 is
10848 returned, which is correct.  A triangle with two rows has three
10849 pebbles in it.
10850 @end table
10852 @node Recursive Example arg of 3 or 4,  , Recursive Example arg of 1 or 2, Recursive triangle function
10853 @unnumberedsubsubsec An argument of 3 or 4
10855 Suppose that @code{triangle-recursively} is called with an argument of
10858 @table @i
10859 @item Step 1 @w{  } Evaluate the do-again-test.
10861 The @code{if} expression is evaluated first.  This is the do-again
10862 test and returns false, so the else-part of the @code{if} expression
10863 is evaluated.  (Note that in this example, the do-again-test causes
10864 the function to call itself when it tests false, not when it tests
10865 true.)
10867 @item Step 2 @w{  } Evaluate the innermost expression of the else-part.
10869 The innermost expression of the else-part is evaluated, which decrements
10870 3 to 2.  This is the next-step-expression.
10872 @item Step 3 @w{  } Evaluate the @code{triangle-recursively} function.
10874 The number 2 is passed to the @code{triangle-recursively} function.
10876 We know what happens when Emacs evaluates @code{triangle-recursively} with
10877 an argument of 2.  After going through the sequence of actions described
10878 earlier, it returns a value of 3.  So that is what will happen here.
10880 @item Step 4 @w{  } Evaluate the addition.
10882 3 will be passed as an argument to the addition and will be added to the
10883 number with which the function was called, which is 3.
10884 @end table
10886 @noindent
10887 The value returned by the function as a whole will be 6.
10889 Now that we know what will happen when @code{triangle-recursively} is
10890 called with an argument of 3, it is evident what will happen if it is
10891 called with an argument of 4:
10893 @quotation
10894 @need 800
10895 In the recursive call, the evaluation of
10897 @smallexample
10898 (triangle-recursively (1- 4))
10899 @end smallexample
10901 @need 800
10902 @noindent
10903 will return the value of evaluating
10905 @smallexample
10906 (triangle-recursively 3)
10907 @end smallexample
10909 @noindent
10910 which is 6 and this value will be added to 4 by the addition in the
10911 third line.
10912 @end quotation
10914 @noindent
10915 The value returned by the function as a whole will be 10.
10917 Each time @code{triangle-recursively} is evaluated, it evaluates a
10918 version of itself---a different instance of itself---with a smaller
10919 argument, until the argument is small enough so that it does not
10920 evaluate itself.
10922 Note that this particular design for a recursive function
10923 requires that operations be deferred.
10925 Before @code{(triangle-recursively 7)} can calculate its answer, it
10926 must call @code{(triangle-recursively 6)}; and before
10927 @code{(triangle-recursively 6)} can calculate its answer, it must call
10928 @code{(triangle-recursively 5)}; and so on.  That is to say, the
10929 calculation that @code{(triangle-recursively 7)} makes must be
10930 deferred until @code{(triangle-recursively 6)} makes its calculation;
10931 and @code{(triangle-recursively 6)} must defer until
10932 @code{(triangle-recursively 5)} completes; and so on.
10934 If each of these instances of @code{triangle-recursively} are thought
10935 of as different robots, the first robot must wait for the second to
10936 complete its job, which must wait until the third completes, and so
10939 There is a way around this kind of waiting, which we will discuss in
10940 @ref{No Deferment, , Recursion without Deferments}.
10942 @node Recursion with cond, Recursive Patterns, Recursive triangle function, Recursion
10943 @comment  node-name,  next,  previous,  up
10944 @subsection Recursion Example Using @code{cond}
10945 @findex cond
10947 The version of @code{triangle-recursively} described earlier is written
10948 with the @code{if} special form.  It can also be written using another
10949 special form called @code{cond}.  The name of the special form
10950 @code{cond} is an abbreviation of the word @samp{conditional}.
10952 Although the @code{cond} special form is not used as often in the
10953 Emacs Lisp sources as @code{if}, it is used often enough to justify
10954 explaining it.
10956 @need 800
10957 The template for a @code{cond} expression looks like this:
10959 @smallexample
10960 @group
10961 (cond
10962  @var{body}@dots{})
10963 @end group
10964 @end smallexample
10966 @noindent
10967 where the @var{body} is a series of lists.
10969 @need 800
10970 Written out more fully, the template looks like this:
10972 @smallexample
10973 @group
10974 (cond
10975  (@var{first-true-or-false-test} @var{first-consequent})
10976  (@var{second-true-or-false-test} @var{second-consequent})
10977  (@var{third-true-or-false-test} @var{third-consequent})
10978   @dots{})
10979 @end group
10980 @end smallexample
10982 When the Lisp interpreter evaluates the @code{cond} expression, it
10983 evaluates the first element (the @sc{car} or true-or-false-test) of
10984 the first expression in a series of expressions within the body of the
10985 @code{cond}.
10987 If the true-or-false-test returns @code{nil} the rest of that
10988 expression, the consequent, is skipped and  the true-or-false-test of the
10989 next expression is evaluated.  When an expression is found whose
10990 true-or-false-test returns a value that is not @code{nil}, the
10991 consequent of that expression is evaluated.  The consequent can be one
10992 or more expressions.  If the consequent consists of more than one
10993 expression, the expressions are evaluated in sequence and the value of
10994 the last one is returned.  If the expression does not have a consequent,
10995 the value of the true-or-false-test is returned.
10997 If none of the true-or-false-tests test true, the @code{cond} expression
10998 returns @code{nil}.
11000 @need 1250
11001 Written using @code{cond}, the @code{triangle} function looks like this:
11003 @smallexample
11004 @group
11005 (defun triangle-using-cond (number)
11006   (cond ((<= number 0) 0)
11007         ((= number 1) 1)
11008         ((> number 1)
11009          (+ number (triangle-using-cond (1- number))))))
11010 @end group
11011 @end smallexample
11013 @noindent
11014 In this example, the @code{cond} returns 0 if the number is less than or
11015 equal to 0, it returns 1 if the number is 1 and it evaluates @code{(+
11016 number (triangle-using-cond (1- number)))} if the number is greater than
11019 @node Recursive Patterns, No Deferment, Recursion with cond, Recursion
11020 @comment  node-name,  next,  previous,  up
11021 @subsection Recursive Patterns
11022 @cindex Recursive Patterns
11024 Here are three common recursive patterns.  Each involves a list.
11025 Recursion does not need to involve lists, but Lisp is designed for lists
11026 and this provides a sense of its primal capabilities.
11028 @menu
11029 * Every::
11030 * Accumulate::
11031 * Keep::
11032 @end menu
11034 @node Every, Accumulate, Recursive Patterns, Recursive Patterns
11035 @comment  node-name,  next,  previous,  up
11036 @unnumberedsubsubsec Recursive Pattern: @emph{every}
11037 @cindex Every, type of recursive pattern
11038 @cindex Recursive pattern: every
11040 In the @code{every} recursive pattern, an action is performed on every
11041 element of a list.
11043 @need 1500
11044 The basic pattern is:
11046 @itemize @bullet
11047 @item
11048 If a list be empty, return @code{nil}.
11049 @item
11050 Else, act on the beginning of the list (the @sc{car} of the list)
11051     @itemize @minus
11052     @item
11053     through a recursive call by the function on the rest (the
11054     @sc{cdr}) of the list,
11055     @item
11056     and, optionally, combine the acted-on element, using @code{cons},
11057     with the results of acting on the rest.
11058     @end itemize
11059 @end itemize
11061 @need 1500
11062 Here is example:
11064 @smallexample
11065 @group
11066 (defun square-each (numbers-list)
11067   "Square each of a NUMBERS LIST, recursively."
11068   (if (not numbers-list)                ; do-again-test
11069       nil
11070     (cons
11071      (* (car numbers-list) (car numbers-list))
11072      (square-each (cdr numbers-list))))) ; next-step-expression
11073 @end group
11075 @group
11076 (square-each '(1 2 3))
11077     @result{} (1 4 9)
11078 @end group
11079 @end smallexample
11081 @need 1200
11082 @noindent
11083 If @code{numbers-list} is empty, do nothing.  But if it has content,
11084 construct a list combining the square of the first number in the list
11085 with the result of the recursive call.
11087 (The example follows the pattern exactly: @code{nil} is returned if
11088 the numbers' list is empty.  In practice, you would write the
11089 conditional so it carries out the action when the numbers' list is not
11090 empty.)
11092 The @code{print-elements-recursively} function (@pxref{Recursion with
11093 list, , Recursion with a List}) is another example of an @code{every}
11094 pattern, except in this case, rather than bring the results together
11095 using @code{cons}, we print each element of output.
11097 @need 1250
11098 The @code{print-elements-recursively} function looks like this:
11100 @smallexample
11101 @group
11102 (setq animals '(gazelle giraffe lion tiger))
11103 @end group
11105 @group
11106 (defun print-elements-recursively (list)
11107   "Print each element of LIST on a line of its own.
11108 Uses recursion."
11109   (if list                              ; @r{do-again-test}
11110       (progn
11111         (print (car list))              ; @r{body}
11112         (print-elements-recursively     ; @r{recursive call}
11113          (cdr list)))))                 ; @r{next-step-expression}
11115 (print-elements-recursively animals)
11116 @end group
11117 @end smallexample
11119 @need 1500
11120 The pattern for @code{print-elements-recursively} is:
11122 @itemize @bullet
11123 @item
11124 If the list be empty, do nothing.
11125 @item
11126 But if the list has at least one element,
11127     @itemize @minus
11128     @item
11129     act on the beginning of the list (the @sc{car} of the list),
11130     @item
11131     and make a recursive call on the rest (the @sc{cdr}) of the list.
11132     @end itemize
11133 @end itemize
11135 @node Accumulate, Keep, Every, Recursive Patterns
11136 @comment  node-name,  next,  previous,  up
11137 @unnumberedsubsubsec Recursive Pattern: @emph{accumulate}
11138 @cindex Accumulate, type of recursive pattern
11139 @cindex Recursive pattern: accumulate
11141 Another recursive pattern is called the @code{accumulate} pattern.  In
11142 the @code{accumulate} recursive pattern, an action is performed on
11143 every element of a list and the result of that action is accumulated
11144 with the results of performing the action on the other elements.
11146 This is very like the `every' pattern using @code{cons}, except that
11147 @code{cons} is not used, but some other combiner.
11149 @need 1500
11150 The pattern is:
11152 @itemize @bullet
11153 @item
11154 If a list be empty, return zero or some other constant.
11155 @item
11156 Else, act on the beginning of the list (the @sc{car} of the list),
11157     @itemize @minus
11158     @item
11159     and combine that acted-on element, using @code{+} or
11160     some other combining function, with
11161     @item
11162     a recursive call by the function on the rest (the @sc{cdr}) of the list.
11163     @end itemize
11164 @end itemize
11166 @need 1500
11167 Here is an example:
11169 @smallexample
11170 @group
11171 (defun add-elements (numbers-list)
11172   "Add the elements of NUMBERS-LIST together."
11173   (if (not numbers-list)
11174       0
11175     (+ (car numbers-list) (add-elements (cdr numbers-list)))))
11176 @end group
11178 @group
11179 (add-elements '(1 2 3 4))
11180     @result{} 10
11181 @end group
11182 @end smallexample
11184 @xref{Files List, , Making a List of Files}, for an example of the
11185 accumulate pattern.
11187 @node Keep,  , Accumulate, Recursive Patterns
11188 @comment  node-name,  next,  previous,  up
11189 @unnumberedsubsubsec Recursive Pattern: @emph{keep}
11190 @cindex Keep, type of recursive pattern
11191 @cindex Recursive pattern: keep
11193 A third recursive pattern is called the @code{keep} pattern.
11194 In the @code{keep} recursive pattern, each element of a list is tested;
11195 the element is acted on and the results are kept only if the element
11196 meets a criterion.
11198 Again, this is very like the `every' pattern, except the element is
11199 skipped unless it meets a criterion.
11201 @need 1500
11202 The pattern has three parts:
11204 @itemize @bullet
11205 @item
11206 If a list be empty, return @code{nil}.
11207 @item
11208 Else, if the beginning of the list (the @sc{car} of the list) passes
11209         a test
11210     @itemize @minus
11211     @item
11212     act on that element and combine it, using @code{cons} with
11213     @item
11214     a recursive call by the function on the rest (the @sc{cdr}) of the list.
11215     @end itemize
11216 @item
11217 Otherwise, if the beginning of the list (the @sc{car} of the list) fails
11218 the test
11219     @itemize @minus
11220     @item
11221     skip on that element,
11222     @item
11223     and, recursively call the function on the rest (the @sc{cdr}) of the list.
11224     @end itemize
11225 @end itemize
11227 @need 1500
11228 Here is an example that uses @code{cond}:
11230 @smallexample
11231 @group
11232 (defun keep-three-letter-words (word-list)
11233   "Keep three letter words in WORD-LIST."
11234   (cond
11235    ;; First do-again-test: stop-condition
11236    ((not word-list) nil)
11238    ;; Second do-again-test: when to act
11239    ((eq 3 (length (symbol-name (car word-list))))
11240     ;; combine acted-on element with recursive call on shorter list
11241     (cons (car word-list) (keep-three-letter-words (cdr word-list))))
11243    ;; Third do-again-test: when to skip element;
11244    ;;   recursively call shorter list with next-step expression
11245    (t  (keep-three-letter-words (cdr word-list)))))
11246 @end group
11248 @group
11249 (keep-three-letter-words '(one two three four five six))
11250     @result{} (one two six)
11251 @end group
11252 @end smallexample
11254 It goes without saying that you need not use @code{nil} as the test for
11255 when to stop; and you can, of course, combine these patterns.
11257 @node No Deferment, No deferment solution, Recursive Patterns, Recursion
11258 @subsection Recursion without Deferments
11259 @cindex Deferment in recursion
11260 @cindex Recursion without Deferments
11262 Let's consider again what happens with the @code{triangle-recursively}
11263 function.  We will find that the intermediate calculations are
11264 deferred until all can be done.
11266 @need 800
11267 Here is the function definition:
11269 @smallexample
11270 @group
11271 (defun triangle-recursively (number)
11272   "Return the sum of the numbers 1 through NUMBER inclusive.
11273 Uses recursion."
11274   (if (= number 1)                    ; @r{do-again-test}
11275       1                               ; @r{then-part}
11276     (+ number                         ; @r{else-part}
11277        (triangle-recursively          ; @r{recursive call}
11278         (1- number)))))               ; @r{next-step-expression}
11279 @end group
11280 @end smallexample
11282 What happens when we call this function with a argument of 7?
11284 The first instance of the @code{triangle-recursively} function adds
11285 the number 7 to the value returned by a second instance of
11286 @code{triangle-recursively}, an instance that has been passed an
11287 argument of 6.  That is to say, the first calculation is:
11289 @smallexample
11290 (+ 7 (triangle-recursively 6))
11291 @end smallexample
11293 @noindent
11294 The first instance of @code{triangle-recursively}---you may want to
11295 think of it as a little robot---cannot complete its job.  It must hand
11296 off the calculation for @code{(triangle-recursively 6)} to a second
11297 instance of the program, to a second robot.  This second individual is
11298 completely different from the first one; it is, in the jargon, a
11299 `different instantiation'.  Or, put another way, it is a different
11300 robot.  It is the same model as the first; it calculates triangle
11301 numbers recursively; but it has a different serial number.
11303 And what does @code{(triangle-recursively 6)} return?  It returns the
11304 number 6 added to the value returned by evaluating
11305 @code{triangle-recursively} with an argument of 5.  Using the robot
11306 metaphor, it asks yet another robot to help it.
11308 @need 800
11309 Now the total is:
11311 @smallexample
11312 (+ 7 6 (triangle-recursively 5))
11313 @end smallexample
11315 @need 800
11316 And what happens next?
11318 @smallexample
11319 (+ 7 6 5 (triangle-recursively 4))
11320 @end smallexample
11322 Each time @code{triangle-recursively} is called, except for the last
11323 time, it creates another instance of the program---another robot---and
11324 asks it to make a calculation.
11326 @need 800
11327 Eventually, the full addition is set up and performed:
11329 @smallexample
11330 (+ 7 6 5 4 3 2 1)
11331 @end smallexample
11333 This design for the function defers the calculation of the first step
11334 until the second can be done, and defers that until the third can be
11335 done, and so on.  Each deferment means the computer must remember what
11336 is being waited on.  This is not a problem when there are only a few
11337 steps, as in this example.  But it can be a problem when there are
11338 more steps.
11340 @node No deferment solution,  , No Deferment, Recursion
11341 @subsection No Deferment Solution
11342 @cindex No deferment solution
11343 @cindex Defermentless solution
11344 @cindex Solution without deferment
11346 The solution to the problem of deferred operations is to write in a
11347 manner that does not defer operations@footnote{The phrase @dfn{tail
11348 recursive} is used to describe such a process, one that uses
11349 `constant space'.}.  This requires
11350 writing to a different pattern, often one that involves writing two
11351 function definitions, an `initialization' function and a `helper'
11352 function.
11354 The `initialization' function sets up the job; the `helper' function
11355 does the work.
11357 @need 1200
11358 Here are the two function definitions for adding up numbers.  They are
11359 so simple, I find them hard to understand.
11361 @smallexample
11362 @group
11363 (defun triangle-initialization (number)
11364   "Return the sum of the numbers 1 through NUMBER inclusive.
11365 This is the `initialization' component of a two function
11366 duo that uses recursion."
11367   (triangle-recursive-helper 0 0 number))
11368 @end group
11369 @end smallexample
11371 @smallexample
11372 @group
11373 (defun triangle-recursive-helper (sum counter number)
11374   "Return SUM, using COUNTER, through NUMBER inclusive.
11375 This is the `helper' component of a two function duo
11376 that uses recursion."
11377   (if (> counter number)
11378       sum
11379     (triangle-recursive-helper (+ sum counter)  ; @r{sum}
11380                                (1+ counter)     ; @r{counter}
11381                                number)))        ; @r{number}
11382 @end group
11383 @end smallexample
11385 @need 1250
11386 Install both function definitions by evaluating them, then call
11387 @code{triangle-initialization} with 2 rows:
11389 @smallexample
11390 @group
11391 (triangle-initialization 2)
11392     @result{} 3
11393 @end group
11394 @end smallexample
11396 The `initialization' function calls the first instance of the `helper'
11397 function with three arguments: zero, zero, and a number which is the
11398 number of rows in the triangle.
11400 The first two arguments passed to the `helper' function are
11401 initialization values.  These values are changed when
11402 @code{triangle-recursive-helper} invokes new instances.@footnote{The
11403 jargon is mildly confusing:  @code{triangle-recursive-helper} uses a
11404 process that is iterative in a procedure that is recursive.  The
11405 process is called iterative because the computer need only record the
11406 three values, @code{sum}, @code{counter}, and @code{number}; the
11407 procedure is recursive because the function `calls itself'.  On the
11408 other hand, both the process and the procedure used by
11409 @code{triangle-recursively} are called recursive.  The word
11410 `recursive' has different meanings in the two contexts.}
11412 Let's see what happens when we have a triangle that has one row.  (This
11413 triangle will have one pebble in it!)
11415 @need 1200
11416 @code{triangle-initialization} will call its helper with
11417 the arguments @w{@code{0 0 1}}.  That function will run the conditional
11418 test whether @code{(> counter number)}:
11420 @smallexample
11421 (> 0 1)
11422 @end smallexample
11424 @need 1200
11425 @noindent
11426 and find that the result is false, so it will invoke
11427 the then-part of the @code{if} clause:
11429 @smallexample
11430 @group
11431     (triangle-recursive-helper
11432      (+ sum counter)  ; @r{sum plus counter} @result{} @r{sum}
11433      (1+ counter)     ; @r{increment counter} @result{} @r{counter}
11434      number)          ; @r{number stays the same}
11435 @end group
11436 @end smallexample
11438 @need 800
11439 @noindent
11440 which will first compute:
11442 @smallexample
11443 @group
11444 (triangle-recursive-helper (+ 0 0)  ; @r{sum}
11445                            (1+ 0)   ; @r{counter}
11446                            1)       ; @r{number}
11447 @exdent which is:
11449 (triangle-recursive-helper 0 1 1)
11450 @end group
11451 @end smallexample
11453 Again, @code{(> counter number)} will be false, so again, the Lisp
11454 interpreter will evaluate @code{triangle-recursive-helper}, creating a
11455 new instance with new arguments.
11457 @need 800
11458 This new instance will be;
11460 @smallexample
11461 @group
11462     (triangle-recursive-helper
11463      (+ sum counter)  ; @r{sum plus counter} @result{} @r{sum}
11464      (1+ counter)     ; @r{increment counter} @result{} @r{counter}
11465      number)          ; @r{number stays the same}
11467 @exdent which is:
11469 (triangle-recursive-helper 1 2 1)
11470 @end group
11471 @end smallexample
11473 In this case, the @code{(> counter number)} test will be true!  So the
11474 instance will return the value of the sum, which will be 1, as
11475 expected.
11477 Now, let's pass @code{triangle-initialization} an argument
11478 of 2, to find out how many pebbles there are in a triangle with two rows.
11480 That function calls @code{(triangle-recursive-helper 0 0 2)}.
11482 @need 800
11483 In stages, the instances called will be:
11485 @smallexample
11486 @group
11487                           @r{sum counter number}
11488 (triangle-recursive-helper 0    1       2)
11490 (triangle-recursive-helper 1    2       2)
11492 (triangle-recursive-helper 3    3       2)
11493 @end group
11494 @end smallexample
11496 When the last instance is called, the @code{(> counter number)} test
11497 will be true, so the instance will return the value of @code{sum},
11498 which will be 3.
11500 This kind of pattern helps when you are writing functions that can use
11501 many resources in a computer.
11503 @need 1500
11504 @node Looping exercise,  , Recursion, Loops & Recursion
11505 @section Looping Exercise
11507 @itemize @bullet
11508 @item
11509 Write a function similar to @code{triangle} in which each row has a
11510 value which is the square of the row number.  Use a @code{while} loop.
11512 @item
11513 Write a function similar to @code{triangle} that multiplies instead of
11514 adds the values.
11516 @item
11517 Rewrite these two functions recursively.  Rewrite these functions
11518 using @code{cond}.
11520 @c comma in printed title causes problem in Info cross reference
11521 @item
11522 Write a function for Texinfo mode that creates an index entry at the
11523 beginning of a paragraph for every @samp{@@dfn} within the paragraph.
11524 (In a Texinfo file, @samp{@@dfn} marks a definition.  This book is
11525 written in Texinfo.)
11527 Many of the functions you will need are described in two of the
11528 previous chapters, @ref{Cutting & Storing Text, , Cutting and Storing
11529 Text}, and @ref{Yanking, , Yanking Text Back}.  If you use
11530 @code{forward-paragraph} to put the index entry at the beginning of
11531 the paragraph, you will have to use @w{@kbd{C-h f}}
11532 (@code{describe-function}) to find out how to make the command go
11533 backwards.
11535 For more information, see
11536 @ifinfo
11537 @ref{Indicating, , Indicating Definitions, texinfo}.
11538 @end ifinfo
11539 @ifhtml
11540 @ref{Indicating, , Indicating, texinfo, Texinfo Manual}, which goes to
11541 a Texinfo manual in the current directory.  Or, if you are on the
11542 Internet, see
11543 @uref{http://www.gnu.org/manual/texinfo-4.6/html_node/Indicating.html}
11544 @end ifhtml
11545 @iftex
11546 ``Indicating Definitions, Commands, etc.'' in @cite{Texinfo, The GNU
11547 Documentation Format}.
11548 @end iftex
11549 @end itemize
11551 @node Regexp Search, Counting Words, Loops & Recursion, Top
11552 @comment  node-name,  next,  previous,  up
11553 @chapter Regular Expression Searches
11554 @cindex Searches, illustrating
11555 @cindex Regular expression searches
11556 @cindex Patterns, searching for
11557 @cindex Motion by sentence and paragraph
11558 @cindex Sentences, movement by
11559 @cindex Paragraphs, movement by
11561 Regular expression searches are used extensively in GNU Emacs.  The
11562 two functions, @code{forward-sentence} and @code{forward-paragraph},
11563 illustrate these searches well.  They use regular expressions to find
11564 where to move point.  The phrase `regular expression' is often written
11565 as `regexp'.
11567 Regular expression searches are described in @ref{Regexp Search, ,
11568 Regular Expression Search, emacs, The GNU Emacs Manual}, as well as in
11569 @ref{Regular Expressions, , , elisp, The GNU Emacs Lisp Reference
11570 Manual}.  In writing this chapter, I am presuming that you have at
11571 least a mild acquaintance with them.  The major point to remember is
11572 that regular expressions permit you to search for patterns as well as
11573 for literal strings of characters.  For example, the code in
11574 @code{forward-sentence} searches for the pattern of possible
11575 characters that could mark the end of a sentence, and moves point to
11576 that spot.
11578 Before looking at the code for the @code{forward-sentence} function, it
11579 is worth considering what the pattern that marks the end of a sentence
11580 must be.  The pattern is discussed in the next section; following that
11581 is a description of the regular expression search function,
11582 @code{re-search-forward}.  The @code{forward-sentence} function
11583 is described in the section following.  Finally, the
11584 @code{forward-paragraph} function is described in the last section of
11585 this chapter.  @code{forward-paragraph} is a complex function that
11586 introduces several new features.
11588 @menu
11589 * sentence-end::                The regular expression for @code{sentence-end}.
11590 * re-search-forward::           Very similar to @code{search-forward}.
11591 * forward-sentence::            A straightforward example of regexp search.
11592 * forward-paragraph::           A somewhat complex example.
11593 * etags::                       How to create your own @file{TAGS} table.
11594 * Regexp Review::
11595 * re-search Exercises::
11596 @end menu
11598 @node sentence-end, re-search-forward, Regexp Search, Regexp Search
11599 @comment  node-name,  next,  previous,  up
11600 @section The Regular Expression for @code{sentence-end}
11601 @findex sentence-end
11603 The symbol @code{sentence-end} is bound to the pattern that marks the
11604 end of a sentence.  What should this regular expression be?
11606 Clearly, a sentence may be ended by a period, a question mark, or an
11607 exclamation mark.  Indeed, only clauses that end with one of those three
11608 characters should be considered the end of a sentence.  This means that
11609 the pattern should include the character set:
11611 @smallexample
11612 [.?!]
11613 @end smallexample
11615 However, we do not want @code{forward-sentence} merely to jump to a
11616 period, a question mark, or an exclamation mark, because such a character
11617 might be used in the middle of a sentence.  A period, for example, is
11618 used after abbreviations.  So other information is needed.
11620 According to convention, you type two spaces after every sentence, but
11621 only one space after a period, a question mark, or an exclamation mark in
11622 the body of a sentence.  So a period, a question mark, or an exclamation
11623 mark followed by two spaces is a good indicator of an end of sentence.
11624 However, in a file, the two spaces may instead be a tab or the end of a
11625 line.  This means that the regular expression should include these three
11626 items as alternatives.
11628 @need 800
11629 This group of alternatives will look like this:
11631 @smallexample
11632 @group
11633 \\($\\| \\|  \\)
11634        ^   ^^
11635       TAB  SPC
11636 @end group
11637 @end smallexample
11639 @noindent
11640 Here, @samp{$} indicates the end of the line, and I have pointed out
11641 where the tab and two spaces are inserted in the expression.  Both are
11642 inserted by putting the actual characters into the expression.
11644 Two backslashes, @samp{\\}, are required before the parentheses and
11645 vertical bars: the first backslash quotes the following backslash in
11646 Emacs; and the second indicates that the following character, the
11647 parenthesis or the vertical bar, is special.
11649 @need 1000
11650 Also, a sentence may be followed by one or more carriage returns, like
11651 this:
11653 @smallexample
11654 @group
11657 @end group
11658 @end smallexample
11660 @noindent
11661 Like tabs and spaces, a carriage return is inserted into a regular
11662 expression by inserting it literally.  The asterisk indicates that the
11663 @key{RET} is repeated zero or more times.
11665 But a sentence end does not consist only of a period, a question mark or
11666 an exclamation mark followed by appropriate space: a closing quotation
11667 mark or a closing brace of some kind may precede the space.  Indeed more
11668 than one such mark or brace may precede the space.  These require a
11669 expression that looks like this:
11671 @smallexample
11672 []\"')@}]*
11673 @end smallexample
11675 In this expression, the first @samp{]} is the first character in the
11676 expression; the second character is @samp{"}, which is preceded by a
11677 @samp{\} to tell Emacs the @samp{"} is @emph{not} special.  The last
11678 three characters are @samp{'}, @samp{)}, and @samp{@}}.
11680 All this suggests what the regular expression pattern for matching the
11681 end of a sentence should be; and, indeed, if we evaluate
11682 @code{sentence-end} we find that it returns the following value:
11684 @smallexample
11685 @group
11686 sentence-end
11687      @result{} "[.?!][]\"')@}]*\\($\\|     \\|  \\)[
11689 @end group
11690 @end smallexample
11692 @ignore
11694 @noindent
11695 (Note that here the @key{TAB}, two spaces, and  @key{RET} are shown
11696 literally in the pattern.)
11698 This regular expression can be decyphered as follows:
11700 @table @code
11701 @item [.?!]
11702 The first part of the pattern is the three characters, a period, a question
11703 mark and an exclamation mark, within square brackets.  The pattern must
11704 begin with one or other of these characters.
11706 @item []\"')@}]*
11707 The second part of the pattern is the group of closing braces and
11708 quotation marks, which can appear zero or more times.  These may follow
11709 the period, question mark or exclamation mark.  In a regular expression,
11710 the backslash, @samp{\}, followed by the double quotation mark,
11711 @samp{"}, indicates the class of string-quote characters.  Usually, the
11712 double quotation mark is the only character in this class.  The
11713 asterisk, @samp{*}, indicates that the items in the previous group (the
11714 group surrounded by square brackets, @samp{[]}) may be repeated zero or
11715 more times.
11717 @item \\($\\|   \\|  \\)
11718 The third part of the pattern is one or other of: either the end of a
11719 line, or two blank spaces, or a tab.  The double back-slashes are used
11720 to prevent Emacs from reading the parentheses and vertical bars as part
11721 of the search pattern; the parentheses are used to mark the group and
11722 the vertical bars are used to indicated that the patterns to either side
11723 of them are alternatives.  The dollar sign is used to indicate the end
11724 of a line and both the two spaces and the tab are each inserted as is to
11725 indicate what they are.
11727 @item [@key{RET}]*
11728 Finally, the last part of the pattern indicates that the end of the line
11729 or the whitespace following the period, question mark or exclamation
11730 mark may, but need not, be followed by one or more carriage returns.  In
11731 the pattern, the carriage return is inserted as an actual carriage
11732 return between square brackets but here it is shown as @key{RET}.
11733 @end table
11735 @end ignore
11737 @node re-search-forward, forward-sentence, sentence-end, Regexp Search
11738 @comment  node-name,  next,  previous,  up
11739 @section The @code{re-search-forward} Function
11740 @findex re-search-forward
11742 The @code{re-search-forward} function is very like the
11743 @code{search-forward} function.  (@xref{search-forward, , The
11744 @code{search-forward} Function}.)
11746 @code{re-search-forward} searches for a regular expression.  If the
11747 search is successful, it leaves point immediately after the last
11748 character in the target.  If the search is backwards, it leaves point
11749 just before the first character in the target.  You may tell
11750 @code{re-search-forward} to return @code{t} for true.  (Moving point
11751 is therefore a `side effect'.)
11753 Like @code{search-forward}, the @code{re-search-forward} function takes
11754 four arguments:
11756 @enumerate
11757 @item
11758 The first argument is the regular expression that the function searches
11759 for.  The regular expression will be a string between quotations marks.
11761 @item
11762 The optional second argument limits how far the function will search; it is a
11763 bound, which is specified as a position in the buffer.
11765 @item
11766 The optional third argument specifies how the function responds to
11767 failure: @code{nil} as the third argument causes the function to
11768 signal an error (and print a message) when the search fails; any other
11769 value causes it to return @code{nil} if the search fails and @code{t}
11770 if the search succeeds.
11772 @item
11773 The optional fourth argument is the repeat count.  A negative repeat
11774 count causes @code{re-search-forward} to search backwards.
11775 @end enumerate
11777 @need 800
11778 The template for @code{re-search-forward} looks like this:
11780 @smallexample
11781 @group
11782 (re-search-forward "@var{regular-expression}"
11783                 @var{limit-of-search}
11784                 @var{what-to-do-if-search-fails}
11785                 @var{repeat-count})
11786 @end group
11787 @end smallexample
11789 The second, third, and fourth arguments are optional.  However, if you
11790 want to pass a value to either or both of the last two arguments, you
11791 must also pass a value to all the preceding arguments.  Otherwise, the
11792 Lisp interpreter will mistake which argument you are passing the value
11795 @need 1200
11796 In the @code{forward-sentence} function, the regular expression will be
11797 the value of the variable @code{sentence-end}, namely:
11799 @smallexample
11800 @group
11801 "[.?!][]\"')@}]*\\($\\|  \\|  \\)[
11803 @end group
11804 @end smallexample
11806 @noindent
11807 The limit of the search will be the end of the paragraph (since a
11808 sentence cannot go beyond a paragraph).  If the search fails, the
11809 function will return @code{nil}; and the repeat count will be provided
11810 by the argument to the @code{forward-sentence} function.
11812 @node forward-sentence, forward-paragraph, re-search-forward, Regexp Search
11813 @comment  node-name,  next,  previous,  up
11814 @section @code{forward-sentence}
11815 @findex forward-sentence
11817 The command to move the cursor forward a sentence is a straightforward
11818 illustration of how to use regular expression searches in Emacs Lisp.
11819 Indeed, the function looks longer and more complicated than it is; this
11820 is because the function is designed to go backwards as well as forwards;
11821 and, optionally, over more than one sentence.  The function is usually
11822 bound to the key command @kbd{M-e}.
11824 @menu
11825 * Complete forward-sentence::
11826 * fwd-sentence while loops::    Two @code{while} loops.
11827 * fwd-sentence re-search::      A regular expression search.
11828 @end menu
11830 @node Complete forward-sentence, fwd-sentence while loops, forward-sentence, forward-sentence
11831 @ifnottex
11832 @unnumberedsubsec Complete @code{forward-sentence} function definition
11833 @end ifnottex
11835 @need 1250
11836 Here is the code for @code{forward-sentence}:
11838 @smallexample
11839 @group
11840 (defun forward-sentence (&optional arg)
11841   "Move forward to next sentence-end.  With argument, repeat.
11842 With negative argument, move backward repeatedly to sentence-beginning.
11843 Sentence ends are identified by the value of sentence-end
11844 treated as a regular expression.  Also, every paragraph boundary
11845 terminates sentences as well."
11846 @end group
11847 @group
11848   (interactive "p")
11849   (or arg (setq arg 1))
11850   (while (< arg 0)
11851     (let ((par-beg
11852            (save-excursion (start-of-paragraph-text) (point))))
11853       (if (re-search-backward
11854            (concat sentence-end "[^ \t\n]") par-beg t)
11855           (goto-char (1- (match-end 0)))
11856         (goto-char par-beg)))
11857     (setq arg (1+ arg)))
11858   (while (> arg 0)
11859     (let ((par-end
11860            (save-excursion (end-of-paragraph-text) (point))))
11861       (if (re-search-forward sentence-end par-end t)
11862           (skip-chars-backward " \t\n")
11863         (goto-char par-end)))
11864     (setq arg (1- arg))))
11865 @end group
11866 @end smallexample
11868 The function looks long at first sight and it is best to look at its
11869 skeleton first, and then its muscle.  The way to see the skeleton is to
11870 look at the expressions that start in the left-most columns:
11872 @smallexample
11873 @group
11874 (defun forward-sentence (&optional arg)
11875   "@var{documentation}@dots{}"
11876   (interactive "p")
11877   (or arg (setq arg 1))
11878   (while (< arg 0)
11879     @var{body-of-while-loop}
11880   (while (> arg 0)
11881     @var{body-of-while-loop}
11882 @end group
11883 @end smallexample
11885 This looks much simpler!  The function definition consists of
11886 documentation, an @code{interactive} expression, an @code{or}
11887 expression, and @code{while} loops.
11889 Let's look at each of these parts in turn.
11891 We note that the documentation is thorough and understandable.
11893 The function has an @code{interactive "p"} declaration.  This means
11894 that the processed prefix argument, if any, is passed to the
11895 function as its argument.  (This will be a number.)  If the function
11896 is not passed an argument (it is optional) then the argument
11897 @code{arg} will be bound to 1.  When @code{forward-sentence} is called
11898 non-interactively without an argument, @code{arg} is bound to
11899 @code{nil}.
11901 The @code{or} expression handles the prefix argument.  What it does is
11902 either leave the value of @code{arg} as it is, but only if @code{arg}
11903 is bound to a value; or it sets the value of @code{arg} to 1, in the
11904 case when @code{arg} is bound to @code{nil}.
11906 @node fwd-sentence while loops, fwd-sentence re-search, Complete forward-sentence, forward-sentence
11907 @unnumberedsubsec The @code{while} loops
11909 Two @code{while} loops follow the @code{or} expression.  The first
11910 @code{while} has a true-or-false-test that tests true if the prefix
11911 argument for @code{forward-sentence} is a negative number.  This is for
11912 going backwards.  The body of this loop is similar to the body of the
11913 second @code{while} clause, but it is not exactly the same.  We will
11914 skip this @code{while} loop and concentrate on the second @code{while}
11915 loop.
11917 @need 1500
11918 The second @code{while} loop is for moving point forward.  Its skeleton
11919 looks like this:
11921 @smallexample
11922 @group
11923 (while (> arg 0)            ; @r{true-or-false-test}
11924   (let @var{varlist}
11925     (if (@var{true-or-false-test})
11926         @var{then-part}
11927       @var{else-part}
11928   (setq arg (1- arg))))     ; @code{while} @r{loop decrementer}
11929 @end group
11930 @end smallexample
11932 The @code{while} loop is of the decrementing kind.
11933 (@xref{Decrementing Loop, , A Loop with a Decrementing Counter}.)  It
11934 has a true-or-false-test that tests true so long as the counter (in
11935 this case, the variable @code{arg}) is greater than zero; and it has a
11936 decrementer that subtracts 1 from the value of the counter every time
11937 the loop repeats.
11939 If no prefix argument is given to @code{forward-sentence}, which is
11940 the most common way the command is used, this @code{while} loop will
11941 run once, since the value of @code{arg} will be 1.
11943 The body of the @code{while} loop consists of a @code{let} expression,
11944 which creates and binds a local variable, and has, as its body, an
11945 @code{if} expression.
11947 @need 1250
11948 The body of the @code{while} loop looks like this:
11950 @smallexample
11951 @group
11952 (let ((par-end
11953        (save-excursion (end-of-paragraph-text) (point))))
11954   (if (re-search-forward sentence-end par-end t)
11955       (skip-chars-backward " \t\n")
11956     (goto-char par-end)))
11957 @end group
11958 @end smallexample
11960 The @code{let} expression creates and binds the local variable
11961 @code{par-end}.  As we shall see, this local variable is designed to
11962 provide a bound or limit to the regular expression search.  If the
11963 search fails to find a proper sentence ending in the paragraph, it will
11964 stop on reaching the end of the paragraph.
11966 But first, let us examine how @code{par-end} is bound to the value of
11967 the end of the paragraph.  What happens is that the @code{let} sets the
11968 value of @code{par-end} to the value returned when the Lisp interpreter
11969 evaluates the expression
11971 @smallexample
11972 @group
11973 (save-excursion (end-of-paragraph-text) (point))
11974 @end group
11975 @end smallexample
11977 @noindent
11978 In this expression, @code{(end-of-paragraph-text)} moves point to the
11979 end of the paragraph, @code{(point)} returns the value of point, and then
11980 @code{save-excursion} restores point to its original position.  Thus,
11981 the @code{let} binds @code{par-end} to the value returned by the
11982 @code{save-excursion} expression, which is the position of the end of
11983 the paragraph.  (The @code{(end-of-paragraph-text)} function uses
11984 @code{forward-paragraph}, which we will discuss shortly.)
11986 @need 1200
11987 Emacs next evaluates the body of the @code{let}, which is an @code{if}
11988 expression that looks like this:
11990 @smallexample
11991 @group
11992 (if (re-search-forward sentence-end par-end t) ; @r{if-part}
11993     (skip-chars-backward " \t\n")              ; @r{then-part}
11994   (goto-char par-end)))                        ; @r{else-part}
11995 @end group
11996 @end smallexample
11998 The @code{if} tests whether its first argument is true and if so,
11999 evaluates its then-part; otherwise, the Emacs Lisp interpreter
12000 evaluates the else-part.  The true-or-false-test of the @code{if}
12001 expression is the regular expression search.
12003 It may seem odd to have what looks like the `real work' of
12004 the @code{forward-sentence} function buried here, but this is a common
12005 way this kind of operation is carried out in Lisp.
12007 @node fwd-sentence re-search,  , fwd-sentence while loops, forward-sentence
12008 @unnumberedsubsec The regular expression search
12010 The @code{re-search-forward} function searches for the end of the
12011 sentence, that is, for the pattern defined by the @code{sentence-end}
12012 regular expression.  If the pattern is found---if the end of the sentence is
12013 found---then the @code{re-search-forward} function does two things:
12015 @enumerate
12016 @item
12017 The @code{re-search-forward} function carries out a side effect, which
12018 is to move point to the end of the occurrence found.
12020 @item
12021 The @code{re-search-forward} function returns a value of true.  This is
12022 the value received by the @code{if}, and means that the search was
12023 successful.
12024 @end enumerate
12026 @noindent
12027 The side effect, the movement of point, is completed before the
12028 @code{if} function is handed the value returned by the successful
12029 conclusion of the search.
12031 When the @code{if} function receives the value of true from a successful
12032 call to @code{re-search-forward}, the @code{if} evaluates the then-part,
12033 which is the expression @code{(skip-chars-backward " \t\n")}.  This
12034 expression moves backwards over any blank spaces, tabs or carriage
12035 returns until a printed character is found and then leaves point after
12036 the character.  Since point has already been moved to the end of the
12037 pattern that marks the end of the sentence, this action leaves point
12038 right after the closing printed character of the sentence, which is
12039 usually a period.
12041 On the other hand, if the @code{re-search-forward} function fails to
12042 find a pattern marking the end of the sentence, the function returns
12043 false.  The false then causes the @code{if} to evaluate its third
12044 argument, which is @code{(goto-char par-end)}:  it moves point to the
12045 end of the paragraph.
12047 Regular expression searches are exceptionally useful and the pattern
12048 illustrated by @code{re-search-forward}, in which the search is the
12049 test of an @code{if} expression, is handy.  You will see or write code
12050 incorporating this pattern often.
12052 @node forward-paragraph, etags, forward-sentence, Regexp Search
12053 @comment  node-name,  next,  previous,  up
12054 @section @code{forward-paragraph}: a Goldmine of Functions
12055 @findex forward-paragraph
12057 The @code{forward-paragraph} function moves point forward to the end
12058 of the paragraph.  It is usually bound to @kbd{M-@}} and makes use of a
12059 number of functions that are important in themselves, including
12060 @code{let*}, @code{match-beginning}, and @code{looking-at}.
12062 The function definition for @code{forward-paragraph} is considerably
12063 longer than the function definition for @code{forward-sentence}
12064 because it works with a paragraph, each line of which may begin with a
12065 fill prefix.
12067 A fill prefix consists of a string of characters that are repeated at
12068 the beginning of each line.  For example, in Lisp code, it is a
12069 convention to start each line of a paragraph-long comment with
12070 @samp{;;; }.  In Text mode, four blank spaces make up another common
12071 fill prefix, creating an indented paragraph.  (@xref{Fill Prefix, , ,
12072 emacs, The GNU Emacs Manual}, for more information about fill
12073 prefixes.)
12075 The existence of a fill prefix means that in addition to being able to
12076 find the end of a paragraph whose lines begin on the left-most
12077 column, the @code{forward-paragraph} function must be able to find the
12078 end of a paragraph when all or many of the lines in the buffer begin
12079 with the fill prefix.
12081 Moreover, it is sometimes practical to ignore a fill prefix that
12082 exists, especially when blank lines separate paragraphs.
12083 This is an added complication.
12085 @menu
12086 * forward-paragraph in brief::  Key parts of the function definition.
12087 * fwd-para let::                The @code{let*} expression.
12088 * fwd-para while::              The forward motion @code{while} loop.
12089 * fwd-para between paragraphs::  Movement between paragraphs.
12090 * fwd-para within paragraph::   Movement within paragraphs.
12091 * fwd-para no fill prefix::     When there is no fill prefix.
12092 * fwd-para with fill prefix::   When there is a fill prefix.
12093 * fwd-para summary::            Summary of @code{forward-paragraph} code.
12094 @end menu
12096 @node forward-paragraph in brief, fwd-para let, forward-paragraph, forward-paragraph
12097 @ifnottex
12098 @unnumberedsubsec Shortened @code{forward-paragraph} function definition
12099 @end ifnottex
12101 Rather than print all of the @code{forward-paragraph} function, we
12102 will only print parts of it.  Read without preparation, the function
12103 can be daunting!
12105 @need 800
12106 In outline, the function looks like this:
12108 @smallexample
12109 @group
12110 (defun forward-paragraph (&optional arg)
12111   "@var{documentation}@dots{}"
12112   (interactive "p")
12113   (or arg (setq arg 1))
12114   (let*
12115       @var{varlist}
12116     (while (< arg 0)        ; @r{backward-moving-code}
12117       @dots{}
12118       (setq arg (1+ arg)))
12119     (while (> arg 0)        ; @r{forward-moving-code}
12120       @dots{}
12121       (setq arg (1- arg)))))
12122 @end group
12123 @end smallexample
12125 The first parts of the function are routine: the function's argument
12126 list consists of one optional argument.  Documentation follows.
12128 The lower case @samp{p} in the @code{interactive} declaration means
12129 that the processed prefix argument, if any, is passed to the function.
12130 This will be a number, and is the repeat count of how many paragraphs
12131 point will move.  The @code{or} expression in the next line handles
12132 the common case when no argument is passed to the function, which occurs
12133 if the function is called from other code rather than interactively.
12134 This case was described earlier.  (@xref{forward-sentence, The
12135 @code{forward-sentence} function}.)  Now we reach the end of the
12136 familiar part of this function.
12138 @node fwd-para let, fwd-para while, forward-paragraph in brief, forward-paragraph
12139 @unnumberedsubsec The @code{let*} expression
12141 The next line of the @code{forward-paragraph} function begins a
12142 @code{let*} expression.  This is a different kind of expression than
12143 we have seen so far.  The symbol is @code{let*} not @code{let}.
12145 The @code{let*} special form is like @code{let} except that Emacs sets
12146 each variable in sequence, one after another, and variables in the
12147 latter part of the varlist can make use of the values to which Emacs
12148 set variables in the earlier part of the varlist.
12150 In the @code{let*} expression in this function, Emacs binds two
12151 variables: @code{fill-prefix-regexp} and @code{paragraph-separate}.
12152 The value to which @code{paragraph-separate} is bound depends on the
12153 value of @code{fill-prefix-regexp}.
12155 @need 1200
12156 Let's look at each in turn.  The symbol @code{fill-prefix-regexp} is
12157 set to the value returned by evaluating the following list:
12159 @smallexample
12160 @group
12161 (and fill-prefix
12162      (not (equal fill-prefix ""))
12163      (not paragraph-ignore-fill-prefix)
12164      (regexp-quote fill-prefix))
12165 @end group
12166 @end smallexample
12168 @noindent
12169 This is an expression whose first element is the @code{and} special form.
12171 As we learned earlier (@pxref{kill-new function, , The @code{kill-new}
12172 function}), the @code{and} special form evaluates each of its
12173 arguments until one of the arguments returns a value of @code{nil}, in
12174 which case the @code{and} expression returns @code{nil}; however, if
12175 none of the arguments returns a value of @code{nil}, the value
12176 resulting from evaluating the last argument is returned.  (Since such
12177 a value is not @code{nil}, it is considered true in Lisp.)  In other
12178 words, an @code{and} expression returns a true value only if all its
12179 arguments are true.
12180 @findex and
12182 In this case, the variable @code{fill-prefix-regexp} is bound to a
12183 non-@code{nil} value only if the following four expressions produce a
12184 true (i.e., a non-@code{nil}) value when they are evaluated; otherwise,
12185 @code{fill-prefix-regexp} is bound to @code{nil}.
12187 @table @code
12188 @item fill-prefix
12189 When this variable is evaluated, the value of the fill prefix, if any,
12190 is returned.  If there is no fill prefix, this variable returns
12191 @code{nil}.
12193 @item (not (equal fill-prefix "")
12194 This expression checks whether an existing fill prefix is an empty
12195 string, that is, a string with no characters in it.  An empty string is
12196 not a useful fill prefix.
12198 @item (not paragraph-ignore-fill-prefix)
12199 This expression returns @code{nil} if the variable
12200 @code{paragraph-ignore-fill-prefix} has been turned on by being set to a
12201 true value such as @code{t}.
12203 @item (regexp-quote fill-prefix)
12204 This is the last argument to the @code{and} special form.  If all the
12205 arguments to the @code{and} are true, the value resulting from
12206 evaluating this expression will be returned by the @code{and} expression
12207 and bound to the variable @code{fill-prefix-regexp},
12208 @end table
12210 @findex regexp-quote
12211 @noindent
12212 The result of evaluating this @code{and} expression successfully is that
12213 @code{fill-prefix-regexp} will be bound to the value of
12214 @code{fill-prefix} as modified by the @code{regexp-quote} function.
12215 What @code{regexp-quote} does is read a string and return a regular
12216 expression that will exactly match the string and match nothing else.
12217 This means that @code{fill-prefix-regexp} will be set to a value that
12218 will exactly match the fill prefix if the fill prefix exists.
12219 Otherwise, the variable will be set to @code{nil}.
12221 The second local variable in the @code{let*} expression is
12222 @code{paragraph-separate}.  It is bound to the value returned by
12223 evaluating the expression:
12225 @smallexample
12226 @group
12227 (if fill-prefix-regexp
12228     (concat paragraph-separate
12229             "\\|^" fill-prefix-regexp "[ \t]*$")
12230   paragraph-separate)))
12231 @end group
12232 @end smallexample
12234 This expression shows why @code{let*} rather than @code{let} was used.
12235 The true-or-false-test for the @code{if} depends on whether the variable
12236 @code{fill-prefix-regexp} evaluates to @code{nil} or some other value.
12238 If @code{fill-prefix-regexp} does not have a value, Emacs evaluates
12239 the else-part of the @code{if} expression and binds
12240 @code{paragraph-separate} to its local value.
12241 (@code{paragraph-separate} is a regular expression that matches what
12242 separates paragraphs.)
12244 But if @code{fill-prefix-regexp} does have a value, Emacs evaluates
12245 the then-part of the @code{if} expression and binds
12246 @code{paragraph-separate} to a regular expression that includes the
12247 @code{fill-prefix-regexp} as part of the pattern.
12249 Specifically, @code{paragraph-separate} is set to the original value
12250 of the paragraph separate regular expression concatenated with an
12251 alternative expression that consists of the @code{fill-prefix-regexp}
12252 followed by a blank line.  The @samp{^} indicates that the
12253 @code{fill-prefix-regexp} must begin a line, and the optional
12254 whitespace to the end of the line is defined by @w{@code{"[ \t]*$"}}.)
12255 The @samp{\\|} defines this portion of the regexp as an alternative to
12256 @code{paragraph-separate}.
12258 Now we get into the body of the @code{let*}.  The first part of the body
12259 of the @code{let*} deals with the case when the function is given a
12260 negative argument and is therefore moving backwards.  We will skip this
12261 section.
12263 @node fwd-para while, fwd-para between paragraphs, fwd-para let, forward-paragraph
12264 @unnumberedsubsec The forward motion @code{while} loop
12266 The second part of the body of the @code{let*} deals with forward
12267 motion.  It is a @code{while} loop that repeats itself so long as the
12268 value of @code{arg} is greater than zero.  In the most common use of
12269 the function, the value of the argument is 1, so the body of the
12270 @code{while} loop is evaluated exactly once, and the cursor moves
12271 forward one paragraph.
12273 This part handles three situations: when point is between paragraphs,
12274 when point is within a paragraph and there is a fill prefix, and
12275 when point is within a paragraph and there is no fill prefix.
12277 @need 800
12278 The @code{while} loop looks like this:
12280 @smallexample
12281 @group
12282 (while (> arg 0)
12283   (beginning-of-line)
12285   ;; @r{between paragraphs}
12286   (while (prog1 (and (not (eobp))
12287                      (looking-at paragraph-separate))
12288            (forward-line 1)))
12289 @end group
12291 @group
12292   ;; @r{within paragraphs, with a fill prefix}
12293   (if fill-prefix-regexp
12294       ;; @r{There is a fill prefix; it overrides paragraph-start.}
12295       (while (and (not (eobp))
12296                   (not (looking-at paragraph-separate))
12297                   (looking-at fill-prefix-regexp))
12298         (forward-line 1))
12299 @end group
12301 @group
12302     ;; @r{within paragraphs, no fill prefix}
12303     (if (re-search-forward paragraph-start nil t)
12304         (goto-char (match-beginning 0))
12305       (goto-char (point-max))))
12307   (setq arg (1- arg)))
12308 @end group
12309 @end smallexample
12311 We can see immediately that this is a decrementing counter @code{while}
12312 loop, using the expression @code{(setq arg (1- arg))} as the decrementer.
12314 @need 800
12315 The body of the loop consists of three expressions:
12317 @smallexample
12318 @group
12319 ;; @r{between paragraphs}
12320 (beginning-of-line)
12321 (while
12322     @var{body-of-while})
12323 @end group
12325 @group
12326 ;; @r{within paragraphs, with fill prefix}
12327 (if @var{true-or-false-test}
12328     @var{then-part}
12329 @end group
12331 @group
12332 ;; @r{within paragraphs, no fill prefix}
12333   @var{else-part}
12334 @end group
12335 @end smallexample
12337 @noindent
12338 When the Emacs Lisp interpreter evaluates the body of the
12339 @code{while} loop, the first thing it does is evaluate the
12340 @code{(beginning-of-line)} expression and move point to the beginning
12341 of the line.  Then there is an inner @code{while} loop.  This
12342 @code{while} loop is designed to move the cursor out of the blank
12343 space between paragraphs, if it should happen to be there.  Finally,
12344 there is an @code{if} expression that actually moves point to the end
12345 of the paragraph.
12347 @node fwd-para between paragraphs, fwd-para within paragraph, fwd-para while, forward-paragraph
12348 @unnumberedsubsec Between paragraphs
12350 First, let us look at the inner @code{while} loop.  This loop handles
12351 the case when point is between paragraphs; it uses three functions
12352 that are new to us: @code{prog1}, @code{eobp} and @code{looking-at}.
12353 @findex prog1
12354 @findex eobp
12355 @findex looking-at
12357 @itemize @bullet
12358 @item
12359 @code{prog1} is similar to the @code{progn} special form,
12360 except that @code{prog1} evaluates its arguments in sequence and then
12361 returns the value of its first argument as the value of the whole
12362 expression.  (@code{progn} returns the value of its last argument as the
12363 value of the expression.) The second and subsequent arguments to
12364 @code{prog1} are evaluated only for their side effects.
12366 @item
12367 @code{eobp} is an abbreviation of @samp{End Of Buffer P} and is a
12368 function that returns true if point is at the end of the buffer.
12370 @item
12371 @code{looking-at} is a function that returns true if the text following
12372 point matches the regular expression passed @code{looking-at} as its
12373 argument.
12374 @end itemize
12376 @need 800
12377 The @code{while} loop we are studying looks like this:
12379 @smallexample
12380 @group
12381 (while (prog1 (and (not (eobp))
12382                    (looking-at paragraph-separate))
12383               (forward-line 1)))
12384 @end group
12385 @end smallexample
12387 @need 1200
12388 @noindent
12389 This is a @code{while} loop with no body!  The true-or-false-test of the
12390 loop is the expression:
12392 @smallexample
12393 @group
12394 (prog1 (and (not (eobp))
12395             (looking-at paragraph-separate))
12396        (forward-line 1))
12397 @end group
12398 @end smallexample
12400 @noindent
12401 The first argument to the @code{prog1} is the @code{and} expression.  It
12402 has within in it a test of whether point is at the end of the buffer and
12403 also a test of whether the pattern following point matches the regular
12404 expression for separating paragraphs.
12406 If the cursor is not at the end of the buffer and if the characters
12407 following the cursor mark the separation between two paragraphs, then
12408 the @code{and} expression is true.  After evaluating the @code{and}
12409 expression, the Lisp interpreter evaluates the second argument to
12410 @code{prog1}, which is @code{forward-line}.  This moves point forward
12411 one line.  The value returned by the @code{prog1} however, is the
12412 value of its first argument, so the @code{while} loop continues so
12413 long as point is not at the end of the buffer and is between
12414 paragraphs.  When, finally, point is moved to a paragraph, the
12415 @code{and} expression tests false.  Note however, that the
12416 @code{forward-line} command is carried out anyhow.  This means that
12417 when point is moved from between paragraphs to a paragraph, it is left
12418 at the beginning of the second line of the paragraph.
12420 @node fwd-para within paragraph, fwd-para no fill prefix, fwd-para between paragraphs, forward-paragraph
12421 @unnumberedsubsec Within paragraphs
12423 The next expression in the outer @code{while} loop is an @code{if}
12424 expression.  The Lisp interpreter evaluates the then-part of the
12425 @code{if} when the @code{fill-prefix-regexp} variable has a value other
12426 than @code{nil}, and it evaluates the else-part when the value of
12427 @code{if fill-prefix-regexp} is @code{nil}, that is, when there is no
12428 fill prefix.
12430 @node fwd-para no fill prefix, fwd-para with fill prefix, fwd-para within paragraph, forward-paragraph
12431 @unnumberedsubsec No fill prefix
12433 It is simplest to look at the code for the case when there is no fill
12434 prefix first.  This code consists of yet another inner @code{if}
12435 expression, and reads as follows:
12437 @smallexample
12438 @group
12439 (if (re-search-forward paragraph-start nil t)
12440     (goto-char (match-beginning 0))
12441   (goto-char (point-max)))
12442 @end group
12443 @end smallexample
12445 @noindent
12446 This expression actually does the work that most people think of as
12447 the primary purpose of the @code{forward-paragraph} command: it causes
12448 a regular expression search to occur that searches forward to the
12449 start of the next paragraph and if it is found, moves point there; but
12450 if the start of another paragraph if not found, it moves point to the
12451 end of the accessible region of the buffer.
12453 The only unfamiliar part of this is the use of @code{match-beginning}.
12454 This is another function that is new to us.  The
12455 @code{match-beginning} function returns a number specifying the
12456 location of the start of the text that was matched by the last regular
12457 expression search.
12459 The @code{match-beginning} function is used here because of a
12460 characteristic of a forward search: a successful forward search,
12461 regardless of whether it is a plain search or a regular expression
12462 search, will move point to the end of the text that is found.  In this
12463 case, a successful search will move point to the end of the pattern for
12464 @code{paragraph-start}, which will be the beginning of the next
12465 paragraph rather than the end of the current one.
12467 However, we want to put point at the end of the current paragraph, not at
12468 the beginning of the next one.  The two positions may be different,
12469 because there may be several blank lines between paragraphs.
12471 @findex match-beginning
12472 When given an argument of 0, @code{match-beginning} returns the position
12473 that is the start of the text that the most recent regular
12474 expression search matched.  In this case, the most recent regular
12475 expression search is the one looking for @code{paragraph-start}, so
12476 @code{match-beginning} returns the beginning position of the pattern,
12477 rather than the end of the pattern.  The beginning position is the end
12478 of the paragraph.
12480 (Incidentally, when passed a positive number as an argument, the
12481 @code{match-beginning} function will place point at that parenthesized
12482 expression in the last regular expression.  It is a useful function.)
12484 @node fwd-para with fill prefix, fwd-para summary, fwd-para no fill prefix, forward-paragraph
12485 @unnumberedsubsec With a fill prefix
12487 The inner @code{if} expression just discussed is the else-part of an enclosing
12488 @code{if} expression which tests whether there is a fill prefix.  If
12489 there is a fill prefix, the then-part of this @code{if} is evaluated.
12490 It looks like this:
12492 @smallexample
12493 @group
12494 (while (and (not (eobp))
12495             (not (looking-at paragraph-separate))
12496             (looking-at fill-prefix-regexp))
12497   (forward-line 1))
12498 @end group
12499 @end smallexample
12501 @noindent
12502 What this expression does is move point forward line by line so long
12503 as three conditions are true:
12505 @enumerate
12506 @item
12507 Point is not at the end of the buffer.
12509 @item
12510 The text following point does not separate paragraphs.
12512 @item
12513 The pattern following point is the fill prefix regular expression.
12514 @end enumerate
12516 The last condition may be puzzling, until you remember that point was
12517 moved to the beginning of the line early in the @code{forward-paragraph}
12518 function.  This means that if the text has a fill prefix, the
12519 @code{looking-at} function will see it.
12521 @node fwd-para summary,  , fwd-para with fill prefix, forward-paragraph
12522 @unnumberedsubsec Summary
12524 In summary, when moving forward, the @code{forward-paragraph} function
12525 does the following:
12527 @itemize @bullet
12528 @item
12529 Move point to the beginning of the line.
12531 @item
12532 Skip over lines between paragraphs.
12534 @item
12535 Check whether there is a fill prefix, and if there is:
12537 @itemize ---
12539 @item
12540 Go forward line by line so long as the line is not a paragraph
12541 separating line.
12542 @end itemize
12544 @item
12545 But if there is no fill prefix,
12547 @itemize ---
12549 @item
12550 Search for the next paragraph start pattern.
12552 @item
12553 Go to the beginning of the paragraph start pattern, which will be the
12554 end of the previous paragraph.
12556 @item
12557 Or else go to the end of the accessible portion of the buffer.
12558 @end itemize
12559 @end itemize
12561 @need 1200
12562 For review, here is the code we have just been discussing, formatted
12563 for clarity:
12565 @smallexample
12566 @group
12567 (interactive "p")
12568 (or arg (setq arg 1))
12569 (let* (
12570        (fill-prefix-regexp
12571         (and fill-prefix (not (equal fill-prefix ""))
12572              (not paragraph-ignore-fill-prefix)
12573              (regexp-quote fill-prefix)))
12574 @end group
12576 @group
12577        (paragraph-separate
12578         (if fill-prefix-regexp
12579             (concat paragraph-separate
12580                     "\\|^"
12581                     fill-prefix-regexp
12582                     "[ \t]*$")
12583           paragraph-separate)))
12585   @var{omitted-backward-moving-code} @dots{}
12586 @end group
12588 @group
12589   (while (> arg 0)                ; @r{forward-moving-code}
12590     (beginning-of-line)
12592     (while (prog1 (and (not (eobp))
12593                        (looking-at paragraph-separate))
12594              (forward-line 1)))
12595 @end group
12597 @group
12598     (if fill-prefix-regexp
12599         (while (and (not (eobp))  ; @r{then-part}
12600                     (not (looking-at paragraph-separate))
12601                     (looking-at fill-prefix-regexp))
12602           (forward-line 1))
12603 @end group
12604 @group
12605                                   ; @r{else-part: the inner-if}
12606       (if (re-search-forward paragraph-start nil t)
12607           (goto-char (match-beginning 0))
12608         (goto-char (point-max))))
12610     (setq arg (1- arg)))))        ; @r{decrementer}
12611 @end group
12612 @end smallexample
12614 The full definition for the @code{forward-paragraph} function not only
12615 includes this code for going forwards, but also code for going backwards.
12617 If you are reading this inside of GNU Emacs and you want to see the
12618 whole function, you can type @kbd{C-h f} (@code{describe-function})
12619 and the name of the function.  This gives you the function
12620 documentation and the name of the library containing the function's
12621 source.  Place point over the name of the library and press the RET
12622 key; you will be taken directly to the source.  (Be sure to install
12623 your sources!  Without them, you are like a person who tries to drive
12624 a car with his eyes shut!)
12626 @c !!! again, 21.0.100 tags table location in this paragraph
12627 Or -- a good habit to get into -- you can type @kbd{M-.}
12628 (@code{find-tag}) and the name of the function when prompted for it.
12629 This will take you directly to the source.  If the @code{find-tag}
12630 function first asks you for the name of a @file{TAGS} table, give it
12631 the name of the @file{TAGS} file such as
12632 @file{/usr/local/share/emacs/21.0.100/lisp/TAGS}.  (The exact path to your
12633 @file{TAGS} file depends on how your copy of Emacs was installed.)
12635 You can also create your own @file{TAGS} file for directories that
12636 lack one.
12637 @ifnottex
12638 @xref{etags, , Create Your Own @file{TAGS} File}.
12639 @end ifnottex
12641 @node etags, Regexp Review, forward-paragraph, Regexp Search
12642 @section Create Your Own @file{TAGS} File
12643 @findex etags
12644 @cindex @file{TAGS} file, create own
12646 The @kbd{M-.} (@code{find-tag}) command takes you directly to the
12647 source for a function, variable, node, or other source.  The function
12648 depends on tags tables to tell it where to go.
12650 You often need to build and install tags tables yourself.  They are
12651 not built automatically.  A tags table is called a @file{TAGS} file;
12652 the name is in upper case letters.
12654 You can create a @file{TAGS} file by calling the @code{etags} program
12655 that comes as a part of the Emacs distribution.  Usually, @code{etags}
12656 is compiled and installed when Emacs is built.  (@code{etags} is not
12657 an Emacs Lisp function or a part of Emacs; it is a C program.)
12659 @need 1250
12660 To create a @file{TAGS} file, first switch to the directory in which
12661 you want to create the file.  In Emacs you can do this with the
12662 @kbd{M-x cd} command, or by visiting a file in the directory, or by
12663 listing the directory with @kbd{C-x d} (@code{dired}).  Then run the
12664 compile command, with @w{@code{etags *.el}} as the command to execute
12666 @smallexample
12667 M-x compile RET etags *.el RET
12668 @end smallexample
12670 @noindent
12671 to create a @file{TAGS} file.
12673 For example, if you have a large number of files in your
12674 @file{~/emacs} directory, as I do---I have 137 @file{.el} files in it,
12675 of which I load 12---you can create a @file{TAGS} file for the Emacs
12676 Lisp files in that directory.
12678 @need 1250
12679 The @code{etags} program takes all the
12680 usual shell `wildcards'.  For example, if you have two directories for
12681 which you want a single @file{TAGS file}, type
12682 @w{@code{etags *.el ../elisp/*.el}},
12683 where @file{../elisp/} is the second directory:
12685 @smallexample
12686 M-x compile RET etags *.el ../elisp/*.el RET
12687 @end smallexample
12689 @need 1250
12690 Type
12692 @smallexample
12693 M-x compile RET etags --help RET
12694 @end smallexample
12696 @noindent
12697 to see a list of the options accepted by @code{etags} as well as a
12698 list of supported languages.
12700 The @code{etags} program handles more than 20 languages, including
12701 Emacs Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, Java, LaTeX,
12702 Pascal, Perl, Python, Texinfo, makefiles, and most assemblers.  The
12703 program has no switches for specifying the language; it recognizes the
12704 language in an input file according to its file name and contents.
12706 @file{etags} is very helpful when you are writing code yourself and
12707 want to refer back to functions you have already written.  Just run
12708 @code{etags} again at intervals as you write new functions, so they
12709 become part of the @file{TAGS} file.
12711 If you think an appropriate @file{TAGS} file already exists for what
12712 you want, but do not know where it is, you can use the @code{locate}
12713 program to attempt to find it.
12715 Type @w{@kbd{M-x locate RET TAGS RET}} and Emacs will list for you the
12716 full path names of all your @file{TAGS} files.  On my system, this
12717 command lists 34 @file{TAGS} files.  On the other hand, a `plain
12718 vanilla' system I recently installed did not contain any @file{TAGS}
12719 files.
12721 If the tags table you want has been created, you can use the @code{M-x
12722 visit-tags-table} command to specify it.  Otherwise, you will need to
12723 create the tag table yourself and then use @code{M-x
12724 visit-tags-table}.
12726 @subsubheading Building Tags in the Emacs sources
12727 @cindex Building Tags in the Emacs sources
12728 @cindex Tags in the Emacs sources
12729 @findex make tags
12731 The GNU Emacs sources come with a @file{Makefile} that contains a
12732 sophisticated @code{etags} command that creates, collects, and merges
12733 tags tables from all over the Emacs sources and puts the information
12734 into one @file{TAGS} file in the @file{src/} directory below the top
12735 level of your Emacs source directory.
12737 @need 1250
12738 To build this @file{TAGS} file, go to the top level of your Emacs
12739 source directory and run the compile command @code{make tags}:
12741 @smallexample
12742 M-x compile RET make tags RET
12743 @end smallexample
12745 @noindent
12746 (The @code{make tags} command works well with the GNU Emacs sources,
12747 as well as with some other source packages.)
12749 For more information, see @ref{Tags, , Tag Tables, emacs, The GNU Emacs
12750 Manual}.
12752 @node Regexp Review, re-search Exercises, etags, Regexp Search
12753 @comment  node-name,  next,  previous,  up
12754 @section Review
12756 Here is a brief summary of some recently introduced functions.
12758 @table @code
12759 @item while
12760 Repeatedly evaluate the body of the expression so long as the first
12761 element of the body tests true.  Then return @code{nil}.  (The
12762 expression is evaluated only for its side effects.)
12764 @need 1250
12765 For example:
12767 @smallexample
12768 @group
12769 (let ((foo 2))
12770   (while (> foo 0)
12771     (insert (format "foo is %d.\n" foo))
12772     (setq foo (1- foo))))
12774      @result{}      foo is 2.
12775              foo is 1.
12776              nil
12777 @end group
12778 @end smallexample
12779 @noindent
12780 (The @code{insert} function inserts its arguments at point; the
12781 @code{format} function returns a string formatted from its arguments
12782 the way @code{message} formats its arguments; @code{\n} produces a new
12783 line.)
12785 @item re-search-forward
12786 Search for a pattern, and if the pattern is found, move point to rest
12787 just after it.
12789 @noindent
12790 Takes four arguments, like @code{search-forward}:
12792 @enumerate
12793 @item
12794 A regular expression that specifies the pattern to search for.
12796 @item
12797 Optionally, the limit of the search.
12799 @item
12800 Optionally, what to do if the search fails, return @code{nil} or an
12801 error message.
12803 @item
12804 Optionally, how many times to repeat the search; if negative, the
12805 search goes backwards.
12806 @end enumerate
12808 @item let*
12809 Bind some variables locally to particular values,
12810 and then evaluate the remaining arguments, returning the value of the
12811 last one.  While binding the local variables, use the local values of
12812 variables bound earlier, if any.
12814 @need 1250
12815 For example:
12817 @smallexample
12818 @group
12819 (let* ((foo 7)
12820       (bar (* 3 foo)))
12821   (message "`bar' is %d." bar))
12822      @result{} `bar' is 21.
12823 @end group
12824 @end smallexample
12826 @item match-beginning
12827 Return the position of the start of the text found by the last regular
12828 expression search.
12830 @item looking-at
12831 Return @code{t} for true if the text after point matches the argument,
12832 which should be a regular expression.
12834 @item eobp
12835 Return @code{t} for true if point is at the end of the accessible part
12836 of a buffer.  The end of the accessible part is the end of the buffer
12837 if the buffer is not narrowed; it is the end of the narrowed part if
12838 the buffer is narrowed.
12840 @item prog1
12841 Evaluate each argument in sequence and then return the value of the
12842 @emph{first}.
12844 @need 1250
12845 For example:
12847 @smallexample
12848 @group
12849 (prog1 1 2 3 4)
12850      @result{} 1
12851 @end group
12852 @end smallexample
12853 @end table
12855 @need 1500
12856 @node re-search Exercises,  , Regexp Review, Regexp Search
12857 @section Exercises with @code{re-search-forward}
12859 @itemize @bullet
12860 @item
12861 Write a function to search for a regular expression that matches two
12862 or more blank lines in sequence.
12864 @item
12865 Write a function to search for duplicated words, such as `the the'.
12866 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
12867 Manual}, for information on how to write a regexp (a regular
12868 expression) to match a string that is composed of two identical
12869 halves.  You can devise several regexps; some are better than others.
12870 The function I use is described in an appendix, along with several
12871 regexps.  @xref{the-the, , @code{the-the} Duplicated Words Function}.
12872 @end itemize
12874 @node Counting Words, Words in a defun, Regexp Search, Top
12875 @chapter Counting: Repetition and Regexps
12876 @cindex Repetition for word counting
12877 @cindex Regular expressions for word counting
12879 Repetition and regular expression searches are powerful tools that you
12880 often use when you write code in Emacs Lisp.  This chapter illustrates
12881 the use of regular expression searches through the construction of
12882 word count commands using @code{while} loops and recursion.
12884 @menu
12885 * Why Count Words::
12886 * count-words-region::          Use a regexp, but find a problem.
12887 * recursive-count-words::       Start with case of no words in region.
12888 * Counting Exercise::
12889 @end menu
12891 @node Why Count Words, count-words-region, Counting Words, Counting Words
12892 @ifnottex
12893 @unnumberedsec Counting words
12894 @end ifnottex
12896 The standard Emacs distribution contains a function for counting the
12897 number of lines within a region.  However, there is no corresponding
12898 function for counting words.
12900 Certain types of writing ask you to count words.  Thus, if you write
12901 an essay, you may be limited to 800 words; if you write a novel, you
12902 may discipline yourself to write 1000 words a day.  It seems odd to me
12903 that Emacs lacks a word count command.  Perhaps people use Emacs
12904 mostly for code or types of documentation that do not require word
12905 counts; or perhaps they restrict themselves to the operating system
12906 word count command, @code{wc}.  Alternatively, people may follow
12907 the publishers' convention and compute a word count by dividing the
12908 number of characters in a document by five.  In any event, here are
12909 commands to count words.
12911 @node count-words-region, recursive-count-words, Why Count Words, Counting Words
12912 @comment  node-name,  next,  previous,  up
12913 @section The @code{count-words-region} Function
12914 @findex count-words-region
12916 A word count command could count words in a line, paragraph, region,
12917 or buffer.  What should the command cover?  You could design the
12918 command to count the number of words in a complete buffer.  However,
12919 the Emacs tradition encourages flexibility---you may want to count
12920 words in just a section, rather than all of a buffer.  So it makes
12921 more sense to design the command to count the number of words in a
12922 region.  Once you have a @code{count-words-region} command, you can,
12923 if you wish, count words in a whole buffer by marking it with @kbd{C-x
12924 h} (@code{mark-whole-buffer}).
12926 Clearly, counting words is a repetitive act: starting from the
12927 beginning of the region, you count the first word, then the second
12928 word, then the third word, and so on, until you reach the end of the
12929 region.  This means that word counting is ideally suited to recursion
12930 or to a @code{while} loop.
12932 @menu
12933 * Design count-words-region::   The definition using a @code{while} loop.
12934 * Whitespace Bug::              The Whitespace Bug in @code{count-words-region}.
12935 @end menu
12937 @node Design count-words-region, Whitespace Bug, count-words-region, count-words-region
12938 @ifnottex
12939 @unnumberedsubsec Designing @code{count-words-region}
12940 @end ifnottex
12942 First, we will implement the word count command with a @code{while}
12943 loop, then with recursion.  The command will, of course, be
12944 interactive.
12946 @need 800
12947 The template for an interactive function definition is, as always:
12949 @smallexample
12950 @group
12951 (defun @var{name-of-function} (@var{argument-list})
12952   "@var{documentation}@dots{}"
12953   (@var{interactive-expression}@dots{})
12954   @var{body}@dots{})
12955 @end group
12956 @end smallexample
12958 What we need to do is fill in the slots.
12960 The name of the function should be self-explanatory and similar to the
12961 existing @code{count-lines-region} name.  This makes the name easier
12962 to remember.  @code{count-words-region} is a good choice.
12964 The function counts words within a region.  This means that the
12965 argument list must contain symbols that are bound to the two
12966 positions, the beginning and end of the region.  These two positions
12967 can be called @samp{beginning} and @samp{end} respectively.  The first
12968 line of the documentation should be a single sentence, since that is
12969 all that is printed as documentation by a command such as
12970 @code{apropos}.  The interactive expression will be of the form
12971 @samp{(interactive "r")}, since that will cause Emacs to pass the
12972 beginning and end of the region to the function's argument list.  All
12973 this is routine.
12975 The body of the function needs to be written to do three tasks:
12976 first, to set up conditions under which the @code{while} loop can
12977 count words, second, to run the @code{while} loop, and third, to send
12978 a message to the user.
12980 When a user calls @code{count-words-region}, point may be at the
12981 beginning or the end of the region.  However, the counting process
12982 must start at the beginning of the region.  This means we will want
12983 to put point there if it is not already there.  Executing
12984 @code{(goto-char beginning)} ensures this.  Of course, we will want to
12985 return point to its expected position when the function finishes its
12986 work.  For this reason, the body must be enclosed in a
12987 @code{save-excursion} expression.
12989 The central part of the body of the function consists of a
12990 @code{while} loop in which one expression jumps point forward word by
12991 word, and another expression counts those jumps.  The true-or-false-test
12992 of the @code{while} loop should test true so long as point should jump
12993 forward, and false when point is at the end of the region.
12995 We could use @code{(forward-word 1)} as the expression for moving point
12996 forward word by word, but it is easier to see what Emacs identifies as a
12997 `word' if we use a regular expression search.
12999 A regular expression search that finds the pattern for which it is
13000 searching leaves point after the last character matched.  This means
13001 that a succession of successful word searches will move point forward
13002 word by word.
13004 As a practical matter, we want the regular expression search to jump
13005 over whitespace and punctuation between words as well as over the
13006 words themselves.  A regexp that refuses to jump over interword
13007 whitespace would never jump more than one word!  This means that
13008 the regexp should include the whitespace and punctuation that follows
13009 a word, if any, as well as the word itself.  (A word may end a buffer
13010 and not have any following whitespace or punctuation, so that part of
13011 the regexp must be optional.)
13013 Thus, what we want for the regexp is a pattern defining one or more
13014 word constituent characters followed, optionally, by one or more
13015 characters that are not word constituents.  The regular expression for
13016 this is:
13018 @smallexample
13019 \w+\W*
13020 @end smallexample
13022 @noindent
13023 The buffer's syntax table determines which characters are and are not
13024 word constituents.  (@xref{Syntax, , What Constitutes a Word or
13025 Symbol?}, for more about syntax.  Also, see @ref{Syntax, Syntax, The
13026 Syntax Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, ,
13027 Syntax Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
13029 @need 800
13030 The search expression looks like this:
13032 @smallexample
13033 (re-search-forward "\\w+\\W*")
13034 @end smallexample
13036 @noindent
13037 (Note that paired backslashes precede the @samp{w} and @samp{W}.  A
13038 single backslash has special meaning to the Emacs Lisp interpreter.  It
13039 indicates that the following character is interpreted differently than
13040 usual.  For example, the two characters, @samp{\n}, stand for
13041 @samp{newline}, rather than for a backslash followed by @samp{n}.  Two
13042 backslashes in a row stand for an ordinary, `unspecial' backslash.)
13044 We need a counter to count how many words there are; this variable
13045 must first be set to 0 and then incremented each time Emacs goes
13046 around the @code{while} loop.  The incrementing expression is simply:
13048 @smallexample
13049 (setq count (1+ count))
13050 @end smallexample
13052 Finally, we want to tell the user how many words there are in the
13053 region.  The @code{message} function is intended for presenting this
13054 kind of information to the user.  The message has to be phrased so
13055 that it reads properly regardless of how many words there are in the
13056 region: we don't want to say that ``there are 1 words in the region''.
13057 The conflict between singular and plural is ungrammatical.  We can
13058 solve this problem by using a conditional expression that evaluates
13059 different messages depending on the number of words in the region.
13060 There are three possibilities: no words in the region, one word in the
13061 region, and more than one word.  This means that the @code{cond}
13062 special form is appropriate.
13064 @need 1500
13065 All this leads to the following function definition:
13067 @smallexample
13068 @group
13069 ;;; @r{First version; has bugs!}
13070 (defun count-words-region (beginning end)
13071   "Print number of words in the region.
13072 Words are defined as at least one word-constituent
13073 character followed by at least one character that
13074 is not a word-constituent.  The buffer's syntax
13075 table determines which characters these are."
13076   (interactive "r")
13077   (message "Counting words in region ... ")
13078 @end group
13080 @group
13081 ;;; @r{1. Set up appropriate conditions.}
13082   (save-excursion
13083     (goto-char beginning)
13084     (let ((count 0))
13085 @end group
13087 @group
13088 ;;; @r{2. Run the} while @r{loop.}
13089       (while (< (point) end)
13090         (re-search-forward "\\w+\\W*")
13091         (setq count (1+ count)))
13092 @end group
13094 @group
13095 ;;; @r{3. Send a message to the user.}
13096       (cond ((zerop count)
13097              (message
13098               "The region does NOT have any words."))
13099             ((= 1 count)
13100              (message
13101               "The region has 1 word."))
13102             (t
13103              (message
13104               "The region has %d words." count))))))
13105 @end group
13106 @end smallexample
13108 @noindent
13109 As written, the function works, but not in all circumstances.
13111 @node Whitespace Bug,  , Design count-words-region, count-words-region
13112 @comment  node-name,  next,  previous,  up
13113 @subsection The Whitespace Bug in @code{count-words-region}
13115 The @code{count-words-region} command described in the preceding
13116 section has two bugs, or rather, one bug with two manifestations.
13117 First, if you mark a region containing only whitespace in the middle
13118 of some text, the @code{count-words-region} command tells you that the
13119 region contains one word!  Second, if you mark a region containing
13120 only whitespace at the end of the buffer or the accessible portion of
13121 a narrowed buffer, the command displays an error message that looks
13122 like this:
13124 @smallexample
13125 Search failed: "\\w+\\W*"
13126 @end smallexample
13128 If you are reading this in Info in GNU Emacs, you can test for these
13129 bugs yourself.
13131 First, evaluate the function in the usual manner to install it.
13132 @ifinfo
13133 Here is a copy of the definition.  Place your cursor after the closing
13134 parenthesis and type @kbd{C-x C-e} to install it.
13136 @smallexample
13137 @group
13138 ;; @r{First version; has bugs!}
13139 (defun count-words-region (beginning end)
13140   "Print number of words in the region.
13141 Words are defined as at least one word-constituent character followed
13142 by at least one character that is not a word-constituent.  The buffer's
13143 syntax table determines which characters these are."
13144 @end group
13145 @group
13146   (interactive "r")
13147   (message "Counting words in region ... ")
13148 @end group
13150 @group
13151 ;;; @r{1. Set up appropriate conditions.}
13152   (save-excursion
13153     (goto-char beginning)
13154     (let ((count 0))
13155 @end group
13157 @group
13158 ;;; @r{2. Run the} while @r{loop.}
13159       (while (< (point) end)
13160         (re-search-forward "\\w+\\W*")
13161         (setq count (1+ count)))
13162 @end group
13164 @group
13165 ;;; @r{3. Send a message to the user.}
13166       (cond ((zerop count)
13167              (message "The region does NOT have any words."))
13168             ((= 1 count) (message "The region has 1 word."))
13169             (t (message "The region has %d words." count))))))
13170 @end group
13171 @end smallexample
13172 @end ifinfo
13174 @need 1000
13175 If you wish, you can also install this keybinding by evaluating it:
13177 @smallexample
13178 (global-set-key "\C-c=" 'count-words-region)
13179 @end smallexample
13181 To conduct the first test, set mark and point to the beginning and end
13182 of the following line and then type @kbd{C-c =} (or @kbd{M-x
13183 count-words-region} if you have not bound @kbd{C-c =}):
13185 @smallexample
13186     one   two  three
13187 @end smallexample
13189 @noindent
13190 Emacs will tell you, correctly, that the region has three words.
13192 Repeat the test, but place mark at the beginning of the line and place
13193 point just @emph{before} the word @samp{one}.  Again type the command
13194 @kbd{C-c =} (or @kbd{M-x count-words-region}).  Emacs should tell you
13195 that the region has no words, since it is composed only of the
13196 whitespace at the beginning of the line.  But instead Emacs tells you
13197 that the region has one word!
13199 For the third test, copy the sample line to the end of the
13200 @file{*scratch*} buffer and then type several spaces at the end of the
13201 line.  Place mark right after the word @samp{three} and point at the
13202 end of line.  (The end of the line will be the end of the buffer.)
13203 Type @kbd{C-c =} (or @kbd{M-x count-words-region}) as you did before.
13204 Again, Emacs should tell you that the region has no words, since it is
13205 composed only of the whitespace at the end of the line.  Instead,
13206 Emacs displays an error message saying @samp{Search failed}.
13208 The two bugs stem from the same problem.
13210 Consider the first manifestation of the bug, in which the command
13211 tells you that the whitespace at the beginning of the line contains
13212 one word.  What happens is this: The @code{M-x count-words-region}
13213 command moves point to the beginning of the region.  The @code{while}
13214 tests whether the value of point is smaller than the value of
13215 @code{end}, which it is.  Consequently, the regular expression search
13216 looks for and finds the first word.  It leaves point after the word.
13217 @code{count} is set to one.  The @code{while} loop repeats; but this
13218 time the value of point is larger than the value of @code{end}, the
13219 loop is exited; and the function displays a message saying the number
13220 of words in the region is one.  In brief, the regular expression
13221 search looks for and finds the word even though it is outside
13222 the marked region.
13224 In the second manifestation of the bug, the region is whitespace at
13225 the end of the buffer.  Emacs says @samp{Search failed}.  What happens
13226 is that the true-or-false-test in the @code{while} loop tests true, so
13227 the search expression is executed.  But since there are no more words
13228 in the buffer, the search fails.
13230 In both manifestations of the bug, the search extends or attempts to
13231 extend outside of the region.
13233 The solution is to limit the search to the region---this is a fairly
13234 simple action, but as you may have come to expect, it is not quite as
13235 simple as you might think.
13237 As we have seen, the @code{re-search-forward} function takes a search
13238 pattern as its first argument.  But in addition to this first,
13239 mandatory argument, it accepts three optional arguments.  The optional
13240 second argument bounds the search.  The optional third argument, if
13241 @code{t}, causes the function to return @code{nil} rather than signal
13242 an error if the search fails.  The optional fourth argument is a
13243 repeat count.  (In Emacs, you can see a function's documentation by
13244 typing @kbd{C-h f}, the name of the function, and then @key{RET}.)
13246 In the @code{count-words-region} definition, the value of the end of
13247 the region is held by the variable @code{end} which is passed as an
13248 argument to the function.  Thus, we can add @code{end} as an argument
13249 to the regular expression search expression:
13251 @smallexample
13252 (re-search-forward "\\w+\\W*" end)
13253 @end smallexample
13255 However, if you make only this change to the @code{count-words-region}
13256 definition and then test the new version of the definition on a
13257 stretch of whitespace, you will receive an error message saying
13258 @samp{Search failed}.
13260 What happens is this: the search is limited to the region, and fails
13261 as you expect because there are no word-constituent characters in the
13262 region.  Since it fails, we receive an error message.  But we do not
13263 want to receive an error message in this case; we want to receive the
13264 message that "The region does NOT have any words."
13266 The solution to this problem is to provide @code{re-search-forward}
13267 with a third argument of @code{t}, which causes the function to return
13268 @code{nil} rather than signal an error if the search fails.
13270 However, if you make this change and try it, you will see the message
13271 ``Counting words in region ... '' and @dots{} you will keep on seeing
13272 that message @dots{}, until you type @kbd{C-g} (@code{keyboard-quit}).
13274 Here is what happens: the search is limited to the region, as before,
13275 and it fails because there are no word-constituent characters in the
13276 region, as expected.  Consequently, the @code{re-search-forward}
13277 expression returns @code{nil}.  It does nothing else.  In particular,
13278 it does not move point, which it does as a side effect if it finds the
13279 search target.  After the @code{re-search-forward} expression returns
13280 @code{nil}, the next expression in the @code{while} loop is evaluated.
13281 This expression increments the count.  Then the loop repeats.  The
13282 true-or-false-test tests true because the value of point is still less
13283 than the value of end, since the @code{re-search-forward} expression
13284 did not move point. @dots{} and the cycle repeats @dots{}
13286 The @code{count-words-region} definition requires yet another
13287 modification, to cause the true-or-false-test of the @code{while} loop
13288 to test false if the search fails.  Put another way, there are two
13289 conditions that must be satisfied in the true-or-false-test before the
13290 word count variable is incremented: point must still be within the
13291 region and the search expression must have found a word to count.
13293 Since both the first condition and the second condition must be true
13294 together, the two expressions, the region test and the search
13295 expression, can be joined with an @code{and} special form and embedded in
13296 the @code{while} loop as the true-or-false-test, like this:
13298 @smallexample
13299 (and (< (point) end) (re-search-forward "\\w+\\W*" end t))
13300 @end smallexample
13302 @c colon in printed section title causes problem in Info cross reference
13303 @c also trouble with an overfull hbox
13304 @iftex
13305 @noindent
13306 (For information about @code{and}, see
13307 @ref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
13308 Functions}.)
13309 @end iftex
13310 @ifinfo
13311 @noindent
13312 (@xref{forward-paragraph}, for information about @code{and}.)
13313 @end ifinfo
13315 The @code{re-search-forward} expression returns @code{t} if the search
13316 succeeds and as a side effect moves point.  Consequently, as words are
13317 found, point is moved through the region.  When the search
13318 expression fails to find another word, or when point reaches the end
13319 of the region, the true-or-false-test tests false, the @code{while}
13320 loop exists, and the @code{count-words-region} function displays one
13321 or other of its messages.
13323 After incorporating these final changes, the @code{count-words-region}
13324 works without bugs (or at least, without bugs that I have found!).
13325 Here is what it looks like:
13327 @smallexample
13328 @group
13329 ;;; @r{Final version:} @code{while}
13330 (defun count-words-region (beginning end)
13331   "Print number of words in the region."
13332   (interactive "r")
13333   (message "Counting words in region ... ")
13334 @end group
13336 @group
13337 ;;; @r{1. Set up appropriate conditions.}
13338   (save-excursion
13339     (let ((count 0))
13340       (goto-char beginning)
13341 @end group
13343 @group
13344 ;;; @r{2. Run the} while @r{loop.}
13345       (while (and (< (point) end)
13346                   (re-search-forward "\\w+\\W*" end t))
13347         (setq count (1+ count)))
13348 @end group
13350 @group
13351 ;;; @r{3. Send a message to the user.}
13352       (cond ((zerop count)
13353              (message
13354               "The region does NOT have any words."))
13355             ((= 1 count)
13356              (message
13357               "The region has 1 word."))
13358             (t
13359              (message
13360               "The region has %d words." count))))))
13361 @end group
13362 @end smallexample
13364 @node recursive-count-words, Counting Exercise, count-words-region, Counting Words
13365 @comment  node-name,  next,  previous,  up
13366 @section Count Words Recursively
13367 @cindex Count words recursively
13368 @cindex Recursively counting words
13369 @cindex Words, counted recursively
13371 You can write the function for counting words recursively as well as
13372 with a @code{while} loop.  Let's see how this is done.
13374 First, we need to recognize that the @code{count-words-region}
13375 function has three jobs: it sets up the appropriate conditions for
13376 counting to occur; it counts the words in the region; and it sends a
13377 message to the user telling how many words there are.
13379 If we write a single recursive function to do everything, we will
13380 receive a message for every recursive call.  If the region contains 13
13381 words, we will receive thirteen messages, one right after the other.
13382 We don't want this!  Instead, we must write two functions to do the
13383 job, one of which (the recursive function) will be used inside of the
13384 other.  One function will set up the conditions and display the
13385 message; the other will return the word count.
13387 Let us start with the function that causes the message to be displayed.
13388 We can continue to call this @code{count-words-region}.
13390 This is the function that the user will call.  It will be interactive.
13391 Indeed, it will be similar to our previous versions of this
13392 function, except that it will call @code{recursive-count-words} to
13393 determine how many words are in the region.
13395 @need 1250
13396 We can readily construct a template for this function, based on our
13397 previous versions:
13399 @smallexample
13400 @group
13401 ;; @r{Recursive version; uses regular expression search}
13402 (defun count-words-region (beginning end)
13403   "@var{documentation}@dots{}"
13404   (@var{interactive-expression}@dots{})
13405 @end group
13406 @group
13408 ;;; @r{1. Set up appropriate conditions.}
13409   (@var{explanatory message})
13410   (@var{set-up functions}@dots{}
13411 @end group
13412 @group
13414 ;;; @r{2. Count the words.}
13415     @var{recursive call}
13416 @end group
13417 @group
13419 ;;; @r{3. Send a message to the user.}
13420     @var{message providing word count}))
13421 @end group
13422 @end smallexample
13424 The definition looks straightforward, except that somehow the count
13425 returned by the recursive call must be passed to the message
13426 displaying the word count.  A little thought suggests that this can be
13427 done by making use of a @code{let} expression: we can bind a variable
13428 in the varlist of a @code{let} expression to the number of words in
13429 the region, as returned by the recursive call; and then the
13430 @code{cond} expression, using binding, can display the value to the
13431 user.
13433 Often, one thinks of the binding within a @code{let} expression as
13434 somehow secondary to the `primary' work of a function.  But in this
13435 case, what you might consider the `primary' job of the function,
13436 counting words, is done within the @code{let} expression.
13438 @need 1250
13439 Using @code{let}, the function definition looks like this:
13441 @smallexample
13442 @group
13443 (defun count-words-region (beginning end)
13444   "Print number of words in the region."
13445   (interactive "r")
13446 @end group
13448 @group
13449 ;;; @r{1. Set up appropriate conditions.}
13450   (message "Counting words in region ... ")
13451   (save-excursion
13452     (goto-char beginning)
13453 @end group
13455 @group
13456 ;;; @r{2. Count the words.}
13457     (let ((count (recursive-count-words end)))
13458 @end group
13460 @group
13461 ;;; @r{3. Send a message to the user.}
13462       (cond ((zerop count)
13463              (message
13464               "The region does NOT have any words."))
13465             ((= 1 count)
13466              (message
13467               "The region has 1 word."))
13468             (t
13469              (message
13470               "The region has %d words." count))))))
13471 @end group
13472 @end smallexample
13474 Next, we need to write the recursive counting function.
13476 A recursive function has at least three parts: the `do-again-test', the
13477 `next-step-expression', and the recursive call.
13479 The do-again-test determines whether the function will or will not be
13480 called again.  Since we are counting words in a region and can use a
13481 function that moves point forward for every word, the do-again-test
13482 can check whether point is still within the region.  The do-again-test
13483 should find the value of point and determine whether point is before,
13484 at, or after the value of the end of the region.  We can use the
13485 @code{point} function to locate point.  Clearly, we must pass the
13486 value of the end of the region to the recursive counting function as an
13487 argument.
13489 In addition, the do-again-test should also test whether the search finds a
13490 word.  If it does not, the function should not call itself again.
13492 The next-step-expression changes a value so that when the recursive
13493 function is supposed to stop calling itself, it stops.  More
13494 precisely, the next-step-expression changes a value so that at the
13495 right time, the do-again-test stops the recursive function from
13496 calling itself again.  In this case, the next-step-expression can be
13497 the expression that moves point forward, word by word.
13499 The third part of a recursive function is the recursive call.
13501 Somewhere, also, we also need a part that does the `work' of the
13502 function, a part that does the counting.  A vital part!
13504 @need 1250
13505 But already, we have an outline of the recursive counting function:
13507 @smallexample
13508 @group
13509 (defun recursive-count-words (region-end)
13510   "@var{documentation}@dots{}"
13511    @var{do-again-test}
13512    @var{next-step-expression}
13513    @var{recursive call})
13514 @end group
13515 @end smallexample
13517 Now we need to fill in the slots.  Let's start with the simplest cases
13518 first:  if point is at or beyond the end of the region, there cannot
13519 be any words in the region, so the function should return zero.
13520 Likewise, if the search fails, there are no words to count, so the
13521 function should return zero.
13523 On the other hand, if point is within the region and the search
13524 succeeds, the function should call itself again.
13526 @need 800
13527 Thus, the do-again-test should look like this:
13529 @smallexample
13530 @group
13531 (and (< (point) region-end)
13532      (re-search-forward "\\w+\\W*" region-end t))
13533 @end group
13534 @end smallexample
13536 Note that the search expression is part of the do-again-test---the
13537 function returns @code{t} if its search succeeds and @code{nil} if it
13538 fails.  (@xref{Whitespace Bug, , The Whitespace Bug in
13539 @code{count-words-region}}, for an explanation of how
13540 @code{re-search-forward} works.)
13542 The do-again-test is the true-or-false test of an @code{if} clause.
13543 Clearly, if the do-again-test succeeds, the then-part of the @code{if}
13544 clause should call the function again; but if it fails, the else-part
13545 should return zero since either point is outside the region or the
13546 search failed because there were no words to find.
13548 But before considering the recursive call, we need to consider the
13549 next-step-expression.  What is it?  Interestingly, it is the search
13550 part of the do-again-test.
13552 In addition to returning @code{t} or @code{nil} for the
13553 do-again-test, @code{re-search-forward} moves point forward as a side
13554 effect of a successful search.  This is the action that changes the
13555 value of point so that the recursive function stops calling itself
13556 when point completes its movement through the region.  Consequently,
13557 the @code{re-search-forward} expression is the next-step-expression.
13559 @need 1200
13560 In outline, then, the body of the @code{recursive-count-words}
13561 function looks like this:
13563 @smallexample
13564 @group
13565 (if @var{do-again-test-and-next-step-combined}
13566     ;; @r{then}
13567     @var{recursive-call-returning-count}
13568   ;; @r{else}
13569   @var{return-zero})
13570 @end group
13571 @end smallexample
13573 How to incorporate the mechanism that counts?
13575 If you are not used to writing recursive functions, a question like
13576 this can be troublesome.  But it can and should be approached
13577 systematically.
13579 We know that the counting mechanism should be associated in some way
13580 with the recursive call.  Indeed, since the next-step-expression moves
13581 point forward by one word, and since a recursive call is made for
13582 each word, the counting mechanism must be an expression that adds one
13583 to the value returned by a call to @code{recursive-count-words}.
13585 Consider several cases:
13587 @itemize @bullet
13588 @item
13589 If there are two words in the region, the function should return
13590 a value resulting from adding one to the value returned when it counts
13591 the first word, plus the number returned when it counts the remaining
13592 words in the region, which in this case is one.
13594 @item
13595 If there is one word in the region, the function should return
13596 a value resulting from adding one to the value returned when it counts
13597 that word, plus the number returned when it counts the remaining
13598 words in the region, which in this case is zero.
13600 @item
13601 If there are no words in the region, the function should return zero.
13602 @end itemize
13604 From the sketch we can see that the else-part of the @code{if} returns
13605 zero for the case of no words.  This means that the then-part of the
13606 @code{if} must return a value resulting from adding one to the value
13607 returned from a count of the remaining words.
13609 @need 1200
13610 The expression will look like this, where @code{1+} is a function that
13611 adds one to its argument.
13613 @smallexample
13614 (1+ (recursive-count-words region-end))
13615 @end smallexample
13617 @need 1200
13618 The whole @code{recursive-count-words} function will then look like
13619 this:
13621 @smallexample
13622 @group
13623 (defun recursive-count-words (region-end)
13624   "@var{documentation}@dots{}"
13626 ;;; @r{1. do-again-test}
13627   (if (and (< (point) region-end)
13628            (re-search-forward "\\w+\\W*" region-end t))
13629 @end group
13631 @group
13632 ;;; @r{2. then-part: the recursive call}
13633       (1+ (recursive-count-words region-end))
13635 ;;; @r{3. else-part}
13636     0))
13637 @end group
13638 @end smallexample
13640 @need 1250
13641 Let's examine how this works:
13643 If there are no words in the region, the else part of the @code{if}
13644 expression is evaluated and consequently the function returns zero.
13646 If there is one word in the region, the value of point is less than
13647 the value of @code{region-end} and the search succeeds.  In this case,
13648 the true-or-false-test of the @code{if} expression tests true, and the
13649 then-part of the @code{if} expression is evaluated.  The counting
13650 expression is evaluated.  This expression returns a value (which will
13651 be the value returned by the whole function) that is the sum of one
13652 added to the value returned by a recursive call.
13654 Meanwhile, the next-step-expression has caused point to jump over the
13655 first (and in this case only) word in the region.  This means that
13656 when @code{(recursive-count-words region-end)} is evaluated a second
13657 time, as a result of the recursive call, the value of point will be
13658 equal to or greater than the value of region end.  So this time,
13659 @code{recursive-count-words} will return zero.  The zero will be added
13660 to one, and the original evaluation of @code{recursive-count-words}
13661 will return one plus zero, which is one, which is the correct amount.
13663 Clearly, if there are two words in the region, the first call to
13664 @code{recursive-count-words} returns one added to the value returned
13665 by calling @code{recursive-count-words} on a region containing the
13666 remaining word---that is, it adds one to one, producing two, which is
13667 the correct amount.
13669 Similarly, if there are three words in the region, the first call to
13670 @code{recursive-count-words} returns one added to the value returned
13671 by calling @code{recursive-count-words} on a region containing the
13672 remaining two words---and so on and so on.
13674 @need 1250
13675 @noindent
13676 With full documentation the two functions look like this:
13678 @need 1250
13679 @noindent
13680 The recursive function:
13682 @findex recursive-count-words
13683 @smallexample
13684 @group
13685 (defun recursive-count-words (region-end)
13686   "Number of words between point and REGION-END."
13687 @end group
13689 @group
13690 ;;; @r{1. do-again-test}
13691   (if (and (< (point) region-end)
13692            (re-search-forward "\\w+\\W*" region-end t))
13693 @end group
13695 @group
13696 ;;; @r{2. then-part: the recursive call}
13697       (1+ (recursive-count-words region-end))
13699 ;;; @r{3. else-part}
13700     0))
13701 @end group
13702 @end smallexample
13704 @need 800
13705 @noindent
13706 The wrapper:
13708 @smallexample
13709 @group
13710 ;;; @r{Recursive version}
13711 (defun count-words-region (beginning end)
13712   "Print number of words in the region.
13713 @end group
13715 @group
13716 Words are defined as at least one word-constituent
13717 character followed by at least one character that is
13718 not a word-constituent.  The buffer's syntax table
13719 determines which characters these are."
13720 @end group
13721 @group
13722   (interactive "r")
13723   (message "Counting words in region ... ")
13724   (save-excursion
13725     (goto-char beginning)
13726     (let ((count (recursive-count-words end)))
13727 @end group
13728 @group
13729       (cond ((zerop count)
13730              (message
13731               "The region does NOT have any words."))
13732 @end group
13733 @group
13734             ((= 1 count)
13735              (message "The region has 1 word."))
13736             (t
13737              (message
13738               "The region has %d words." count))))))
13739 @end group
13740 @end smallexample
13742 @node Counting Exercise,  , recursive-count-words, Counting Words
13743 @section Exercise: Counting Punctuation
13745 Using a @code{while} loop, write a function to count the number of
13746 punctuation marks in a region---period, comma, semicolon, colon,
13747 exclamation mark, and question mark.  Do the same using recursion.
13749 @node Words in a defun, Readying a Graph, Counting Words, Top
13750 @chapter Counting Words in a @code{defun}
13751 @cindex Counting words in a @code{defun}
13752 @cindex Word counting in a @code{defun}
13754 Our next project is to count the number of words in a function
13755 definition.  Clearly, this can be done using some variant of
13756 @code{count-word-region}.  @xref{Counting Words, , Counting Words:
13757 Repetition and Regexps}.  If we are just going to count the words in
13758 one definition, it is easy enough to mark the definition with the
13759 @kbd{C-M-h} (@code{mark-defun}) command, and then call
13760 @code{count-word-region}.
13762 However, I am more ambitious: I want to count the words and symbols in
13763 every definition in the Emacs sources and then print a graph that
13764 shows how many functions there are of each length: how many contain 40
13765 to 49 words or symbols, how many contain 50 to 59 words or symbols,
13766 and so on.  I have often been curious how long a typical function is,
13767 and this will tell.
13769 @menu
13770 * Divide and Conquer::
13771 * Words and Symbols::           What to count?
13772 * Syntax::                      What constitutes a word or symbol?
13773 * count-words-in-defun::        Very like @code{count-words}.
13774 * Several defuns::              Counting several defuns in a file.
13775 * Find a File::                 Do you want to look at a file?
13776 * lengths-list-file::           A list of the lengths of many definitions.
13777 * Several files::               Counting in definitions in different files.
13778 * Several files recursively::   Recursively counting in different files.
13779 * Prepare the data::            Prepare the data for display in a graph.
13780 @end menu
13782 @node Divide and Conquer, Words and Symbols, Words in a defun, Words in a defun
13783 @ifnottex
13784 @unnumberedsec Divide and Conquer
13785 @end ifnottex
13787 Described in one phrase, the histogram project is daunting; but
13788 divided into numerous small steps, each of which we can take one at a
13789 time, the project becomes less fearsome.  Let us consider what the
13790 steps must be:
13792 @itemize @bullet
13793 @item
13794 First, write a function to count the words in one definition.  This
13795 includes the problem of handling symbols as well as words.
13797 @item
13798 Second, write a function to list the numbers of words in each function
13799 in a file.  This function can use the @code{count-words-in-defun}
13800 function.
13802 @item
13803 Third, write a function to list the numbers of words in each function
13804 in each of several files.  This entails automatically finding the
13805 various files, switching to them, and counting the words in the
13806 definitions within them.
13808 @item
13809 Fourth, write a function to convert the list of numbers that we
13810 created in step three to a form that will be suitable for printing as
13811 a graph.
13813 @item
13814 Fifth, write a function to print the results as a graph.
13815 @end itemize
13817 This is quite a project!  But if we take each step slowly, it will not
13818 be difficult.
13820 @node Words and Symbols, Syntax, Divide and Conquer, Words in a defun
13821 @section What to Count?
13822 @cindex Words and symbols in defun
13824 When we first start thinking about how to count the words in a
13825 function definition, the first question is (or ought to be) what are
13826 we going to count?  When we speak of `words' with respect to a Lisp
13827 function definition, we are actually speaking, in large part, of
13828 `symbols'.  For example, the following @code{multiply-by-seven}
13829 function contains the five symbols @code{defun},
13830 @code{multiply-by-seven}, @code{number}, @code{*}, and @code{7}.  In
13831 addition, in the documentation string, it contains the four words
13832 @samp{Multiply}, @samp{NUMBER}, @samp{by}, and @samp{seven}.  The
13833 symbol @samp{number} is repeated, so the definition contains a total
13834 of ten words and symbols.
13836 @smallexample
13837 @group
13838 (defun multiply-by-seven (number)
13839   "Multiply NUMBER by seven."
13840   (* 7 number))
13841 @end group
13842 @end smallexample
13844 @noindent
13845 However, if we mark the @code{multiply-by-seven} definition with
13846 @kbd{C-M-h} (@code{mark-defun}), and then call
13847 @code{count-words-region} on it, we will find that
13848 @code{count-words-region} claims the definition has eleven words, not
13849 ten!  Something is wrong!
13851 The problem is twofold: @code{count-words-region} does not count the
13852 @samp{*} as a word, and it counts the single symbol,
13853 @code{multiply-by-seven}, as containing three words.  The hyphens are
13854 treated as if they were interword spaces rather than intraword
13855 connectors: @samp{multiply-by-seven} is counted as if it were written
13856 @samp{multiply by seven}.
13858 The cause of this confusion is the regular expression search within
13859 the @code{count-words-region} definition that moves point forward word
13860 by word.  In the canonical version of @code{count-words-region}, the
13861 regexp is:
13863 @smallexample
13864 "\\w+\\W*"
13865 @end smallexample
13867 @noindent
13868 This regular expression is a pattern defining one or more word
13869 constituent characters possibly followed by one or more characters
13870 that are not word constituents.  What is meant by `word constituent
13871 characters' brings us to the issue of syntax, which is worth a section
13872 of its own.
13874 @node Syntax, count-words-in-defun, Words and Symbols, Words in a defun
13875 @section What Constitutes a Word or Symbol?
13876 @cindex Syntax categories and tables
13878 Emacs treats different characters as belonging to different
13879 @dfn{syntax categories}.  For example, the regular expression,
13880 @samp{\\w+}, is a pattern specifying one or more @emph{word
13881 constituent} characters.  Word constituent characters are members of
13882 one syntax category.  Other syntax categories include the class of
13883 punctuation characters, such as the period and the comma, and the
13884 class of whitespace characters, such as the blank space and the tab
13885 character.  (For more information, see @ref{Syntax, Syntax, The Syntax
13886 Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, , Syntax
13887 Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
13889 Syntax tables specify which characters belong to which categories.
13890 Usually, a hyphen is not specified as a `word constituent character'.
13891 Instead, it is specified as being in the `class of characters that are
13892 part of symbol names but not words.'  This means that the
13893 @code{count-words-region} function treats it in the same way it treats
13894 an interword white space, which is why @code{count-words-region}
13895 counts @samp{multiply-by-seven} as three words.
13897 There are two ways to cause Emacs to count @samp{multiply-by-seven} as
13898 one symbol: modify the syntax table or modify the regular expression.
13900 We could redefine a hyphen as a word constituent character by
13901 modifying the syntax table that Emacs keeps for each mode.  This
13902 action would serve our purpose, except that a hyphen is merely the
13903 most common character within symbols that is not typically a word
13904 constituent character; there are others, too.
13906 Alternatively, we can redefine the regular expression used in the
13907 @code{count-words} definition so as to include symbols.  This
13908 procedure has the merit of clarity, but the task is a little tricky.
13910 @need 1200
13911 The first part is simple enough: the pattern must match ``at least one
13912 character that is a word or symbol constituent''.  Thus:
13914 @smallexample
13915 "\\(\\w\\|\\s_\\)+"
13916 @end smallexample
13918 @noindent
13919 The @samp{\\(} is the first part of the grouping construct that
13920 includes the @samp{\\w} and the @samp{\\s_} as alternatives, separated
13921 by the @samp{\\|}.  The @samp{\\w} matches any word-constituent
13922 character and the @samp{\\s_} matches any character that is part of a
13923 symbol name but not a word-constituent character.  The @samp{+}
13924 following the group indicates that the word or symbol constituent
13925 characters must be matched at least once.
13927 However, the second part of the regexp is more difficult to design.
13928 What we want is to follow the first part with ``optionally one or more
13929 characters that are not constituents of a word or symbol''.  At first,
13930 I thought I could define this with the following:
13932 @smallexample
13933 "\\(\\W\\|\\S_\\)*"
13934 @end smallexample
13936 @noindent
13937 The upper case @samp{W} and @samp{S} match characters that are
13938 @emph{not} word or symbol constituents.  Unfortunately, this
13939 expression matches any character that is either not a word constituent
13940 or not a symbol constituent.  This matches any character!
13942 I then noticed that every word or symbol in my test region was
13943 followed by white space (blank space, tab, or newline).  So I tried
13944 placing a pattern to match one or more blank spaces after the pattern
13945 for one or more word or symbol constituents.  This failed, too.  Words
13946 and symbols are often separated by whitespace, but in actual code
13947 parentheses may follow symbols and punctuation may follow words.  So
13948 finally, I designed a pattern in which the word or symbol constituents
13949 are followed optionally by characters that are not white space and
13950 then followed optionally by white space.
13952 @need 800
13953 Here is the full regular expression:
13955 @smallexample
13956 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
13957 @end smallexample
13959 @node count-words-in-defun, Several defuns, Syntax, Words in a defun
13960 @section The @code{count-words-in-defun} Function
13961 @cindex Counting words in a @code{defun}
13963 We have seen that there are several ways to write a
13964 @code{count-word-region} function.  To write a
13965 @code{count-words-in-defun}, we need merely adapt one of these
13966 versions.
13968 The version that uses a @code{while} loop is easy to understand, so I
13969 am going to adapt that.  Because @code{count-words-in-defun} will be
13970 part of a more complex program, it need not be interactive and it need
13971 not display a message but just return the count.  These considerations
13972 simplify the definition a little.
13974 On the other hand, @code{count-words-in-defun} will be used within a
13975 buffer that contains function definitions.  Consequently, it is
13976 reasonable to ask that the function determine whether it is called
13977 when point is within a function definition, and if it is, to return
13978 the count for that definition.  This adds complexity to the
13979 definition, but saves us from needing to pass arguments to the
13980 function.
13982 @need 1250
13983 These considerations lead us to prepare the following template:
13985 @smallexample
13986 @group
13987 (defun count-words-in-defun ()
13988   "@var{documentation}@dots{}"
13989   (@var{set up}@dots{}
13990      (@var{while loop}@dots{})
13991    @var{return count})
13992 @end group
13993 @end smallexample
13995 @noindent
13996 As usual, our job is to fill in the slots.
13998 First, the set up.
14000 We are presuming that this function will be called within a buffer
14001 containing function definitions.  Point will either be within a
14002 function definition or not.  For @code{count-words-in-defun} to work,
14003 point must move to the beginning of the definition, a counter must
14004 start at zero, and the counting loop must stop when point reaches the
14005 end of the definition.
14007 The @code{beginning-of-defun} function searches backwards for an
14008 opening delimiter such as a @samp{(} at the beginning of a line, and
14009 moves point to that position, or else to the limit of the search.  In
14010 practice, this means that @code{beginning-of-defun} moves point to the
14011 beginning of an enclosing or preceding function definition, or else to
14012 the beginning of the buffer.  We can use @code{beginning-of-defun} to
14013 place point where we wish to start.
14015 The @code{while} loop requires a counter to keep track of the words or
14016 symbols being counted.  A @code{let} expression can be used to create
14017 a local variable for this purpose, and bind it to an initial value of zero.
14019 The @code{end-of-defun} function works like @code{beginning-of-defun}
14020 except that it moves point to the end of the definition.
14021 @code{end-of-defun} can be used as part of an expression that
14022 determines the position of the end of the definition.
14024 The set up for @code{count-words-in-defun} takes shape rapidly: first
14025 we move point to the beginning of the definition, then we create a
14026 local variable to hold the count, and finally, we record the position
14027 of the end of the definition so the @code{while} loop will know when to stop
14028 looping.
14030 @need 1250
14031 The code looks like this:
14033 @smallexample
14034 @group
14035 (beginning-of-defun)
14036 (let ((count 0)
14037       (end (save-excursion (end-of-defun) (point))))
14038 @end group
14039 @end smallexample
14041 @noindent
14042 The code is simple.  The only slight complication is likely to concern
14043 @code{end}: it is bound to the position of the end of the definition
14044 by a @code{save-excursion} expression that returns the value of point
14045 after @code{end-of-defun} temporarily moves it to the end of the
14046 definition.
14048 The second part of the @code{count-words-in-defun}, after the set up,
14049 is the @code{while} loop.
14051 The loop must contain an expression that jumps point forward word by
14052 word and symbol by symbol, and another expression that counts the
14053 jumps.  The true-or-false-test for the @code{while} loop should test
14054 true so long as point should jump forward, and false when point is at
14055 the end of the definition.  We have already redefined the regular
14056 expression for this (@pxref{Syntax}), so the loop is straightforward:
14058 @smallexample
14059 @group
14060 (while (and (< (point) end)
14061             (re-search-forward
14062              "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t)
14063   (setq count (1+ count)))
14064 @end group
14065 @end smallexample
14067 The third part of the function definition returns the count of words
14068 and symbols.  This part is the last expression within the body of the
14069 @code{let} expression, and can be, very simply, the local variable
14070 @code{count}, which when evaluated returns the count.
14072 @need 1250
14073 Put together, the @code{count-words-in-defun} definition looks like this:
14075 @findex count-words-in-defun
14076 @smallexample
14077 @group
14078 (defun count-words-in-defun ()
14079   "Return the number of words and symbols in a defun."
14080   (beginning-of-defun)
14081   (let ((count 0)
14082         (end (save-excursion (end-of-defun) (point))))
14083 @end group
14084 @group
14085     (while
14086         (and (< (point) end)
14087              (re-search-forward
14088               "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14089               end t))
14090       (setq count (1+ count)))
14091     count))
14092 @end group
14093 @end smallexample
14095 How to test this?  The function is not interactive, but it is easy to
14096 put a wrapper around the function to make it interactive; we can use
14097 almost the same code as for the recursive version of
14098 @code{count-words-region}:
14100 @smallexample
14101 @group
14102 ;;; @r{Interactive version.}
14103 (defun count-words-defun ()
14104   "Number of words and symbols in a function definition."
14105   (interactive)
14106   (message
14107    "Counting words and symbols in function definition ... ")
14108 @end group
14109 @group
14110   (let ((count (count-words-in-defun)))
14111     (cond
14112      ((zerop count)
14113       (message
14114        "The definition does NOT have any words or symbols."))
14115 @end group
14116 @group
14117      ((= 1 count)
14118       (message
14119        "The definition has 1 word or symbol."))
14120      (t
14121       (message
14122        "The definition has %d words or symbols." count)))))
14123 @end group
14124 @end smallexample
14126 @need 800
14127 @noindent
14128 Let's re-use @kbd{C-c =} as a convenient keybinding:
14130 @smallexample
14131 (global-set-key "\C-c=" 'count-words-defun)
14132 @end smallexample
14134 Now we can try out @code{count-words-defun}: install both
14135 @code{count-words-in-defun} and @code{count-words-defun}, and set the
14136 keybinding, and then place the cursor within the following definition:
14138 @smallexample
14139 @group
14140 (defun multiply-by-seven (number)
14141   "Multiply NUMBER by seven."
14142   (* 7 number))
14143      @result{} 10
14144 @end group
14145 @end smallexample
14147 @noindent
14148 Success!  The definition has 10 words and symbols.
14150 The next problem is to count the numbers of words and symbols in
14151 several definitions within a single file.
14153 @node Several defuns, Find a File, count-words-in-defun, Words in a defun
14154 @section Count Several @code{defuns} Within a File
14156 A file such as @file{simple.el} may have 80 or more function
14157 definitions within it.  Our long term goal is to collect statistics on
14158 many files, but as a first step, our immediate goal is to collect
14159 statistics on one file.
14161 The information will be a series of numbers, each number being the
14162 length of a function definition.  We can store the numbers in a list.
14164 We know that we will want to incorporate the information regarding one
14165 file with information about many other files; this means that the
14166 function for counting definition lengths within one file need only
14167 return the list of lengths.  It need not and should not display any
14168 messages.
14170 The word count commands contain one expression to jump point forward
14171 word by word and another expression to count the jumps.  The function
14172 to return the lengths of definitions can be designed to work the same
14173 way, with one expression to jump point forward definition by
14174 definition and another expression to construct the lengths' list.
14176 This statement of the problem makes it elementary to write the
14177 function definition.  Clearly, we will start the count at the
14178 beginning of the file, so the first command will be @code{(goto-char
14179 (point-min))}.  Next, we start the @code{while} loop; and the
14180 true-or-false test of the loop can be a regular expression search for
14181 the next function definition---so long as the search succeeds, point
14182 is moved forward and then the body of the loop is evaluated.  The body
14183 needs an expression that constructs the lengths' list.  @code{cons},
14184 the list construction command, can be used to create the list.  That
14185 is almost all there is to it.
14187 @need 800
14188 Here is what this fragment of code looks like:
14190 @smallexample
14191 @group
14192 (goto-char (point-min))
14193 (while (re-search-forward "^(defun" nil t)
14194   (setq lengths-list
14195         (cons (count-words-in-defun) lengths-list)))
14196 @end group
14197 @end smallexample
14199 What we have left out is the mechanism for finding the file that
14200 contains the function definitions.
14202 In previous examples, we either used this, the Info file, or we
14203 switched back and forth to some other buffer, such as the
14204 @file{*scratch*} buffer.
14206 Finding a file is a new process that we have not yet discussed.
14208 @node Find a File, lengths-list-file, Several defuns, Words in a defun
14209 @comment  node-name,  next,  previous,  up
14210 @section Find a File
14211 @cindex Find a File
14213 To find a file in Emacs, you use the @kbd{C-x C-f} (@code{find-file})
14214 command.  This command is almost, but not quite right for the lengths
14215 problem.
14217 @need 1200
14218 Let's look at the source for @code{find-file} (you can use the
14219 @code{find-tag} command or @kbd{C-h f} (@code{describe-function}) to
14220 find the source of a function):
14222 @smallexample
14223 @group
14224 (defun find-file (filename)
14225   "Edit file FILENAME.
14226 Switch to a buffer visiting file FILENAME,
14227 creating one if none already exists."
14228   (interactive "FFind file: ")
14229   (switch-to-buffer (find-file-noselect filename)))
14230 @end group
14231 @end smallexample
14233 The definition possesses short but complete documentation and an
14234 interactive specification that prompts you for a file name when you
14235 use the command interactively.  The body of the definition contains
14236 two functions, @code{find-file-noselect} and @code{switch-to-buffer}.
14238 According to its documentation as shown by @kbd{C-h f} (the
14239 @code{describe-function} command), the @code{find-file-noselect}
14240 function reads the named file into a buffer and returns the buffer.
14241 However, the buffer is not selected.  Emacs does not switch its
14242 attention (or yours if you are using @code{find-file-noselect}) to the
14243 named buffer.  That is what @code{switch-to-buffer} does: it switches
14244 the buffer to which Emacs attention is directed; and it switches the
14245 buffer displayed in the window to the new buffer.  We have discussed
14246 buffer switching elsewhere.  (@xref{Switching Buffers}.)
14248 In this histogram project, we do not need to display each file on the
14249 screen as the program determines the length of each definition within
14250 it.  Instead of employing @code{switch-to-buffer}, we can work with
14251 @code{set-buffer}, which redirects the attention of the computer
14252 program to a different buffer but does not redisplay it on the screen.
14253 So instead of calling on @code{find-file} to do the job, we must write
14254 our own expression.
14256 The task is easy: use  @code{find-file-noselect} and @code{set-buffer}.
14258 @node lengths-list-file, Several files, Find a File, Words in a defun
14259 @section @code{lengths-list-file} in Detail
14261 The core of the @code{lengths-list-file} function is a @code{while}
14262 loop containing a function to move point forward `defun by defun' and
14263 a function to count the number of words and symbols in each defun.
14264 This core must be surrounded by functions that do various other tasks,
14265 including finding the file, and ensuring that point starts out at the
14266 beginning of the file.  The function definition looks like this:
14267 @findex lengths-list-file
14269 @smallexample
14270 @group
14271 (defun lengths-list-file (filename)
14272   "Return list of definitions' lengths within FILE.
14273 The returned list is a list of numbers.
14274 Each number is the number of words or
14275 symbols in one function definition."
14276 @end group
14277 @group
14278   (message "Working on `%s' ... " filename)
14279   (save-excursion
14280     (let ((buffer (find-file-noselect filename))
14281           (lengths-list))
14282       (set-buffer buffer)
14283       (setq buffer-read-only t)
14284       (widen)
14285       (goto-char (point-min))
14286       (while (re-search-forward "^(defun" nil t)
14287         (setq lengths-list
14288               (cons (count-words-in-defun) lengths-list)))
14289       (kill-buffer buffer)
14290       lengths-list)))
14291 @end group
14292 @end smallexample
14294 @noindent
14295 The function is passed one argument, the name of the file on which it
14296 will work.  It has four lines of documentation, but no interactive
14297 specification.  Since people worry that a computer is broken if they
14298 don't see anything going on, the first line of the body is a
14299 message.
14301 The next line contains a @code{save-excursion} that returns Emacs'
14302 attention to the current buffer when the function completes.  This is
14303 useful in case you embed this function in another function that
14304 presumes point is restored to the original buffer.
14306 In the varlist of the @code{let} expression, Emacs finds the file and
14307 binds the local variable @code{buffer} to the buffer containing the
14308 file.  At the same time, Emacs creates @code{lengths-list} as a local
14309 variable.
14311 Next, Emacs switches its attention to the buffer.
14313 In the following line, Emacs makes the buffer read-only.  Ideally,
14314 this line is not necessary.  None of the functions for counting words
14315 and symbols in a function definition should change the buffer.
14316 Besides, the buffer is not going to be saved, even if it were changed.
14317 This line is entirely the consequence of great, perhaps excessive,
14318 caution.  The reason for the caution is that this function and those
14319 it calls work on the sources for Emacs and it is very inconvenient if
14320 they are inadvertently modified.  It goes without saying that I did
14321 not realize a need for this line until an experiment went awry and
14322 started to modify my Emacs source files @dots{}
14324 Next comes a call to widen the buffer if it is narrowed.  This
14325 function is usually not needed---Emacs creates a fresh buffer if none
14326 already exists; but if a buffer visiting the file already exists Emacs
14327 returns that one.  In this case, the buffer may be narrowed and must
14328 be widened.  If we wanted to be fully `user-friendly', we would
14329 arrange to save the restriction and the location of point, but we
14330 won't.
14332 The @code{(goto-char (point-min))} expression moves point to the
14333 beginning of the buffer.
14335 Then comes a @code{while} loop in which the `work' of the function is
14336 carried out.  In the loop, Emacs determines the length of each
14337 definition and constructs a lengths' list containing the information.
14339 Emacs kills the buffer after working through it.  This is to save
14340 space inside of Emacs.  My version of Emacs 19 contained over 300
14341 source files of interest; Emacs 21 contains over 800 source files.
14342 Another function will apply @code{lengths-list-file} to each of the
14343 files.
14345 Finally, the last expression within the @code{let} expression is the
14346 @code{lengths-list} variable; its value is returned as the value of
14347 the whole function.
14349 You can try this function by installing it in the usual fashion.  Then
14350 place your cursor after the following expression and type @kbd{C-x
14351 C-e} (@code{eval-last-sexp}).
14353 @c !!! 21.0.100 lisp sources location here
14354 @smallexample
14355 (lengths-list-file
14356  "/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el")
14357 @end smallexample
14359 @c was: (lengths-list-file "../lisp/debug.el")
14360 @c !!!  as of 21, Info file is in
14361 @c /usr/share/info/emacs-lisp-intro.info.gz
14362 @c but debug.el is in  /usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14364 @noindent
14365 (You may need to change the pathname of the file; the one here worked
14366 with GNU Emacs version 21.0.100.  To change the expression, copy it to
14367 the @file{*scratch*} buffer and edit it.
14369 @need 1200
14370 @noindent
14371 (Also, to see the full length of the list, rather than a truncated
14372 version, you may have to evaluate the following:
14374 @smallexample
14375 (custom-set-variables '(eval-expression-print-length nil))
14376 @end smallexample
14378 @noindent
14379 (@xref{defcustom, , Specifying Variables using @code{defcustom}}.)
14380 Then evaluate the @code{lengths-list-file} expression.)
14382 @need 1200
14383 The lengths' list for @file{debug.el} takes less than a second to
14384 produce and looks like this:
14386 @smallexample
14387 (77 95 85 87 131 89 50 25 44 44 68 35 64 45 17 34 167 457)
14388 @end smallexample
14390 @need 1500
14391 (Using my old machine, the version 19 lengths' list for @file{debug.el}
14392 took seven seconds to produce and looked like this:
14394 @smallexample
14395 (75 41 80 62 20 45 44 68 45 12 34 235)
14396 @end smallexample
14398 (The newer version of  @file{debug.el} contains more defuns than the
14399 earlier one; and my new machine is much faster than the old one.)
14401 Note that the length of the last definition in the file is first in
14402 the list.
14404 @node Several files, Several files recursively, lengths-list-file, Words in a defun
14405 @section Count Words in @code{defuns} in Different Files
14407 In the previous section, we created a function that returns a list of
14408 the lengths of each definition in a file.  Now, we want to define a
14409 function to return a master list of the lengths of the definitions in
14410 a list of files.
14412 Working on each of a list of files is a repetitious act, so we can use
14413 either a @code{while} loop or recursion.
14415 @menu
14416 * lengths-list-many-files::     Return a list of the lengths of defuns.
14417 * append::                      Attach one list to another.
14418 @end menu
14420 @node lengths-list-many-files, append, Several files, Several files
14421 @ifnottex
14422 @unnumberedsubsec Determine the lengths of @code{defuns}
14423 @end ifnottex
14425 The design using a @code{while} loop is routine.  The argument passed
14426 the function is a list of files.  As we saw earlier (@pxref{Loop
14427 Example}), you can write a @code{while} loop so that the body of the
14428 loop is evaluated if such a list contains elements, but to exit the
14429 loop if the list is empty.  For this design to work, the body of the
14430 loop must contain an expression that shortens the list each time the
14431 body is evaluated, so that eventually the list is empty.  The usual
14432 technique is to set the value of the list to the value of the @sc{cdr}
14433 of the list each time the body is evaluated.
14435 @need 800
14436 The template looks like this:
14438 @smallexample
14439 @group
14440 (while @var{test-whether-list-is-empty}
14441   @var{body}@dots{}
14442   @var{set-list-to-cdr-of-list})
14443 @end group
14444 @end smallexample
14446 Also, we remember that a @code{while} loop returns @code{nil} (the
14447 result of evaluating the true-or-false-test), not the result of any
14448 evaluation within its body.  (The evaluations within the body of the
14449 loop are done for their side effects.)  However, the expression that
14450 sets the lengths' list is part of the body---and that is the value
14451 that we want returned by the function as a whole.  To do this, we
14452 enclose the @code{while} loop within a @code{let} expression, and
14453 arrange that the last element of the @code{let} expression contains
14454 the value of the lengths' list.  (@xref{Incrementing Example, , Loop
14455 Example with an Incrementing Counter}.)
14457 @findex lengths-list-many-files
14458 @need 1250
14459 These considerations lead us directly to the function itself:
14461 @smallexample
14462 @group
14463 ;;; @r{Use @code{while} loop.}
14464 (defun lengths-list-many-files (list-of-files)
14465   "Return list of lengths of defuns in LIST-OF-FILES."
14466 @end group
14467 @group
14468   (let (lengths-list)
14470 ;;; @r{true-or-false-test}
14471     (while list-of-files
14472       (setq lengths-list
14473             (append
14474              lengths-list
14476 ;;; @r{Generate a lengths' list.}
14477              (lengths-list-file
14478               (expand-file-name (car list-of-files)))))
14479 @end group
14481 @group
14482 ;;; @r{Make files' list shorter.}
14483       (setq list-of-files (cdr list-of-files)))
14485 ;;; @r{Return final value of lengths' list.}
14486     lengths-list))
14487 @end group
14488 @end smallexample
14490 @code{expand-file-name} is a built-in function that converts a file
14491 name to the absolute, long, path name form of the directory in which
14492 the function is called.
14494 @c !!! 21.0.100 lisp sources location here
14495 @need 1500
14496 Thus, if @code{expand-file-name} is called on @code{debug.el} when
14497 Emacs is visiting the
14498 @file{/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/} directory,
14500 @smallexample
14501 debug.el
14502 @end smallexample
14504 @need 800
14505 @noindent
14506 becomes
14508 @c !!! 21.0.100 lisp sources location here
14509 @smallexample
14510 /usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14511 @end smallexample
14513 The only other new element of this function definition is the as yet
14514 unstudied function @code{append}, which merits a short section for
14515 itself.
14517 @node append,  , lengths-list-many-files, Several files
14518 @subsection The @code{append} Function
14520 @need 800
14521 The @code{append} function attaches one list to another.  Thus,
14523 @smallexample
14524 (append '(1 2 3 4) '(5 6 7 8))
14525 @end smallexample
14527 @need 800
14528 @noindent
14529 produces the list
14531 @smallexample
14532 (1 2 3 4 5 6 7 8)
14533 @end smallexample
14535 This is exactly how we want to attach two lengths' lists produced by
14536 @code{lengths-list-file} to each other.  The results contrast with
14537 @code{cons},
14539 @smallexample
14540 (cons '(1 2 3 4) '(5 6 7 8))
14541 @end smallexample
14543 @need 1250
14544 @noindent
14545 which constructs a new list in which the first argument to @code{cons}
14546 becomes the first element of the new list:
14548 @smallexample
14549 ((1 2 3 4) 5 6 7 8)
14550 @end smallexample
14552 @node Several files recursively, Prepare the data, Several files, Words in a defun
14553 @section Recursively Count Words in Different Files
14555 Besides a @code{while} loop, you can work on each of a list of files
14556 with recursion.  A recursive version of @code{lengths-list-many-files}
14557 is short and simple.
14559 The recursive function has the usual parts: the `do-again-test', the
14560 `next-step-expression', and the recursive call.  The `do-again-test'
14561 determines whether the function should call itself again, which it
14562 will do if the @code{list-of-files} contains any remaining elements;
14563 the `next-step-expression' resets the @code{list-of-files} to the
14564 @sc{cdr} of itself, so eventually the list will be empty; and the
14565 recursive call calls itself on the shorter list.  The complete
14566 function is shorter than this description!
14567 @findex recursive-lengths-list-many-files
14569 @smallexample
14570 @group
14571 (defun recursive-lengths-list-many-files (list-of-files)
14572   "Return list of lengths of each defun in LIST-OF-FILES."
14573   (if list-of-files                     ; @r{do-again-test}
14574       (append
14575        (lengths-list-file
14576         (expand-file-name (car list-of-files)))
14577        (recursive-lengths-list-many-files
14578         (cdr list-of-files)))))
14579 @end group
14580 @end smallexample
14582 @noindent
14583 In a sentence, the function returns the lengths' list for the first of
14584 the @code{list-of-files} appended to the result of calling itself on
14585 the rest of the @code{list-of-files}.
14587 Here is a test of @code{recursive-lengths-list-many-files}, along with
14588 the results of running @code{lengths-list-file} on each of the files
14589 individually.
14591 Install @code{recursive-lengths-list-many-files} and
14592 @code{lengths-list-file}, if necessary, and then evaluate the
14593 following expressions.  You may need to change the files' pathnames;
14594 those here work when this Info file and the Emacs sources are located
14595 in their customary places.  To change the expressions, copy them to
14596 the @file{*scratch*} buffer, edit them, and then evaluate them.
14598 The results are shown after the @samp{@result{}}.  (These results are
14599 for files from Emacs Version 21.0.100; files from other versions of
14600 Emacs may produce different results.)
14602 @c !!! 21.0.100 lisp sources location here
14603 @smallexample
14604 @group
14605 (cd "/usr/local/share/emacs/21.0.100/")
14607 (lengths-list-file "./lisp/macros.el")
14608      @result{} (273 263 456 90)
14609 @end group
14611 @group
14612 (lengths-list-file "./lisp/mail/mailalias.el")
14613      @result{} (38 32 26 77 174 180 321 198 324)
14614 @end group
14616 @group
14617 (lengths-list-file "./lisp/makesum.el")
14618      @result{} (85 181)
14619 @end group
14621 @group
14622 (recursive-lengths-list-many-files
14623  '("./lisp/macros.el"
14624    "./lisp/mail/mailalias.el"
14625    "./lisp/makesum.el"))
14626        @result{} (273 263 456 90 38 32 26 77 174 180 321 198 324 85 181)
14627 @end group
14628 @end smallexample
14630 The @code{recursive-lengths-list-many-files} function produces the
14631 output we want.
14633 The next step is to prepare the data in the list for display in a graph.
14635 @node Prepare the data,  , Several files recursively, Words in a defun
14636 @section Prepare the Data for Display in a Graph
14638 The @code{recursive-lengths-list-many-files} function returns a list
14639 of numbers.  Each number records the length of a function definition.
14640 What we need to do now is transform this data into a list of numbers
14641 suitable for generating a graph.  The new list will tell how many
14642 functions definitions contain less than 10 words and
14643 symbols, how many contain between 10 and 19 words and symbols, how
14644 many contain between 20 and 29 words and symbols, and so on.
14646 In brief, we need to go through the lengths' list produced by the
14647 @code{recursive-lengths-list-many-files} function and count the number
14648 of defuns within each range of lengths, and produce a list of those
14649 numbers.
14651 Based on what we have done before, we can readily foresee that it
14652 should not be too hard to write a function that `@sc{cdr}s' down the
14653 lengths' list, looks at each element, determines which length range it
14654 is in, and increments a counter for that range.
14656 However, before beginning to write such a function, we should consider
14657 the advantages of sorting the lengths' list first, so the numbers are
14658 ordered from smallest to largest.  First, sorting will make it easier
14659 to count the numbers in each range, since two adjacent numbers will
14660 either be in the same length range or in adjacent ranges.  Second, by
14661 inspecting a sorted list, we can discover the highest and lowest
14662 number, and thereby determine the largest and smallest length range
14663 that we will need.
14665 @menu
14666 * Sorting::                     Sorting lists.
14667 * Files List::                  Making a list of files.
14668 * Counting function definitions::
14669 @end menu
14671 @node Sorting, Files List, Prepare the data, Prepare the data
14672 @subsection Sorting Lists
14673 @findex sort
14675 Emacs contains a function to sort lists, called (as you might guess)
14676 @code{sort}.  The @code{sort} function takes two arguments, the list
14677 to be sorted, and a predicate that determines whether the first of
14678 two list elements is ``less'' than the second.
14680 As we saw earlier (@pxref{Wrong Type of Argument, , Using the Wrong
14681 Type Object as an Argument}), a predicate is a function that
14682 determines whether some property is true or false.  The @code{sort}
14683 function will reorder a list according to whatever property the
14684 predicate uses; this means that @code{sort} can be used to sort
14685 non-numeric lists by non-numeric criteria---it can, for example,
14686 alphabetize a list.
14688 @need 1250
14689 The @code{<} function is used when sorting a numeric list.  For example,
14691 @smallexample
14692 (sort '(4 8 21 17 33 7 21 7) '<)
14693 @end smallexample
14695 @need 800
14696 @noindent
14697 produces this:
14699 @smallexample
14700 (4 7 7 8 17 21 21 33)
14701 @end smallexample
14703 @noindent
14704 (Note that in this example, both the arguments are quoted so that the
14705 symbols are not evaluated before being passed to @code{sort} as
14706 arguments.)
14708 Sorting the list returned by the
14709 @code{recursive-lengths-list-many-files} function is straightforward;
14710 it uses the @code{<} function:
14712 @smallexample
14713 @group
14714 (sort
14715  (recursive-lengths-list-many-files
14716   '("../lisp/macros.el"
14717     "../lisp/mailalias.el"
14718     "../lisp/makesum.el"))
14719  '<)
14720 @end group
14721 @end smallexample
14723 @need 800
14724 @noindent
14725 which produces:
14727 @smallexample
14728 (85 86 116 122 154 176 179 265)
14729 @end smallexample
14731 @noindent
14732 (Note that in this example, the first argument to @code{sort} is not
14733 quoted, since the expression must be evaluated so as to produce the
14734 list that is passed to @code{sort}.)
14736 @node Files List, Counting function definitions, Sorting, Prepare the data
14737 @subsection Making a List of Files
14739 The @code{recursive-lengths-list-many-files} function requires a list
14740 of files as its argument.  For our test examples, we constructed such
14741 a list by hand; but the Emacs Lisp source directory is too large for
14742 us to do for that.  Instead, we will write a function to do the job
14743 for us.  In this function, we will use both a @code{while} loop and a
14744 recursive call.
14746 @findex directory-files
14747 We did not have to write a function like this for older versions of
14748 GNU Emacs, since they placed all the @samp{.el} files in one
14749 directory.  Instead, we were able to use the @code{directory-files}
14750 function, which lists the names of files that match a specified
14751 pattern within a single directory.
14753 However, recent versions of Emacs place Emacs Lisp files in
14754 sub-directories of the top level @file{lisp} directory.  This
14755 re-arrangement eases navigation.  For example, all the mail related
14756 files are in a @file{lisp} sub-directory called @file{mail}.  But at
14757 the same time, this arrangement forces us to create a file listing
14758 function that descends into the sub-directories.
14760 @findex files-in-below-directory
14761 We can create this function, called @code{files-in-below-directory},
14762 using familiar functions such as @code{car}, @code{nthcdr}, and
14763 @code{substring} in conjunction with an existing function called
14764 @code{directory-files-and-attributes}.  This latter function not only
14765 lists all the filenames in a directory, including the names
14766 of sub-directories, but also their attributes.
14768 To restate our goal: to create a function that will enable us
14769 to feed filenames to @code{recursive-lengths-list-many-files}
14770 as a list that looks like this (but with more elements):
14772 @smallexample
14773 @group
14774 ("../lisp/macros.el"
14775  "../lisp/mail/rmail.el"
14776  "../lisp/makesum.el")
14777 @end group
14778 @end smallexample
14780 The @code{directory-files-and-attributes} function returns a list of
14781 lists.  Each of the lists within the main list consists of 13
14782 elements.  The first element is a string that contains the name of the
14783 file -- which, in GNU/Linux, may be a `directory file', that is to
14784 say, a file with the special attributes of a directory.  The second
14785 element of the list is @code{t} for a directory, a string
14786 for symbolic link (the string is the name linked to), or @code{nil}.
14788 For example, the first @samp{.el} file in the @file{lisp/} directory
14789 is @file{abbrev.el}.  Its name is
14790 @file{/usr/local/share/emacs/21.0.100/lisp/abbrev.el} and it is not a
14791 directory or a symbolic link.
14793 @need 1000
14794 This is how @code{directory-files-and-attributes} lists that file and
14795 its attributes:
14797 @smallexample
14798 @group
14799 ("/usr/local/share/emacs/21.0.100/lisp/abbrev.el"
14802 1000
14804 @end group
14805 @group
14806 (15019 32380)
14807 (14883 48041)
14808 (15214 49336)
14809 11583
14810 "-rw-rw-r--"
14811 @end group
14812 @group
14814 341385
14815 776)
14816 @end group
14817 @end smallexample
14819 @need 1200
14820 On the other hand, @file{mail/} is a directory within the @file{lisp/}
14821 directory.  The beginning of its listing looks like this:
14823 @smallexample
14824 @group
14825 ("/usr/local/share/emacs/21.0.100/lisp/mail"
14827 @dots{}
14829 @end group
14830 @end smallexample
14832 (Look at the documentation of @code{file-attributes} to learn about
14833 the different attributes.  Bear in mind that the
14834 @code{file-attributes} function does not list the filename, so its
14835 first element is @code{directory-files-and-attributes}'s second
14836 element.)
14838 We will want our new function, @code{files-in-below-directory}, to
14839 list the @samp{.el} files in the directory it is told to check, and in
14840 any directories below that directory.
14842 This gives us a hint on how to construct
14843 @code{files-in-below-directory}:  within a directory, the function
14844 should add @samp{.el} filenames to a list; and if, within a directory,
14845 the function comes upon a sub-directory, it should go into that
14846 sub-directory and repeat its actions.
14848 However, we should note that every directory contains a name that
14849 refers to itself, called @file{.}, (``dot'') and a name that refers to
14850 its parent directory, called @file{..} (``double dot'').  (In
14851 @file{/}, the root directory, @file{..} refers to itself, since
14852 @file{/} has no parent.)  Clearly, we do not want our
14853 @code{files-in-below-directory} function to enter those directories,
14854 since they always lead us, directly or indirectly, to the current
14855 directory.
14857 Consequently, our @code{files-in-below-directory} function must do
14858 several tasks:
14860 @itemize @bullet
14861 @item
14862 Check to see whether it is looking at a filename that ends in
14863 @samp{.el}; and if so, add its name to a list.
14865 @item
14866 Check to see whether it is looking at a filename that is the name of a
14867 directory; and if so,
14869 @itemize @minus
14870 @item
14871 Check to see whether it is looking at @file{.}  or @file{..}; and if
14872 so skip it.
14874 @item
14875 Or else, go into that directory and repeat the process.
14876 @end itemize
14877 @end itemize
14879 Let's write a function definition to do these tasks.  We will use a
14880 @code{while} loop to move from one filename to another within a
14881 directory, checking what needs to be done; and we will use a recursive
14882 call to repeat the actions on each sub-directory.  The recursive
14883 pattern is `accumulate'
14884 (@pxref{Accumulate, , Recursive Pattern: @emph{accumulate}}),
14885 using @code{append} as the combiner.
14887 @ignore
14888 (directory-files "/usr/local/share/emacs/21.0.100/lisp/" t "\\.el$")
14889 (shell-command "find /usr/local/share/emacs/21.0.100/lisp/ -name '*.el'")
14890 @end ignore
14892 @c  /usr/local/share/emacs/21.0.100/lisp/
14894 @need 800
14895 Here is the function:
14897 @smallexample
14898 @group
14899 (defun files-in-below-directory (directory)
14900   "List the .el files in DIRECTORY and in its sub-directories."
14901   ;; Although the function will be used non-interactively,
14902   ;; it will be easier to test if we make it interactive.
14903   ;; The directory will have a name such as
14904   ;;  "/usr/local/share/emacs/21.0.100/lisp/"
14905   (interactive "DDirectory name: ")
14906 @end group
14907 @group
14908   (let (el-files-list
14909         (current-directory-list
14910          (directory-files-and-attributes directory t)))
14911     ;; while we are in the current directory
14912     (while current-directory-list
14913 @end group
14914 @group
14915       (cond
14916        ;; check to see whether filename ends in `.el'
14917        ;; and if so, append its name to a list.
14918        ((equal ".el" (substring (car (car current-directory-list)) -3))
14919         (setq el-files-list
14920               (cons (car (car current-directory-list)) el-files-list)))
14921 @end group
14922 @group
14923        ;; check whether filename is that of a directory
14924        ((eq t (car (cdr (car current-directory-list))))
14925         ;; decide whether to skip or recurse
14926         (if
14927             (equal (or "." "..")
14928                    (substring (car (car current-directory-list)) -1))
14929             ;; then do nothing if filename is that of
14930             ;;   current directory or parent
14931             ()
14932 @end group
14933 @group
14934           ;; else descend into the directory and repeat the process
14935           (setq el-files-list
14936                 (append
14937                  (files-in-below-directory
14938                   (car (car current-directory-list)))
14939                  el-files-list)))))
14940       ;; move to the next filename in the list; this also
14941       ;; shortens the list so the while loop eventually comes to an end
14942       (setq current-directory-list (cdr current-directory-list)))
14943     ;; return the filenames
14944     el-files-list))
14945 @end group
14946 @end smallexample
14948 @c (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14950 The @code{files-in-below-directory} @code{directory-files} function
14951 takes one argument, the name of a directory.
14953 @need 1250
14954 Thus, on my system,
14956 @c !!! 21.0.100 lisp sources location here
14957 @smallexample
14958 @group
14959 (length
14960  (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/"))
14961 @end group
14962 @end smallexample
14964 @noindent
14965 tells me that my version 21.0.100 Lisp sources directory contains 754
14966 @samp{.el} files.
14968 @code{files-in-below-directory} returns a list in reverse alphabetical
14969 order.  An expression to sort the list in alphabetical order looks
14970 like this:
14972 @smallexample
14973 @group
14974 (sort
14975  (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14976  'string-lessp)
14977 @end group
14978 @end smallexample
14980 @ignore
14981 (defun test ()
14982   "Test how long it takes to find lengths of all elisp defuns."
14983   (insert "\n" (current-time-string) "\n")
14984   (sit-for 0)
14985   (sort
14986    (recursive-lengths-list-many-files
14987     '("../lisp/macros.el"
14988       "../lisp/mailalias.el"
14989       "../lisp/makesum.el"))
14990    '<)
14991   (insert (format "%s" (current-time-string))))
14993 @end ignore
14995 @node Counting function definitions,  , Files List, Prepare the data
14996 @subsection Counting function definitions
14998 Our immediate goal is to generate a list that tells us how many
14999 function definitions contain fewer than 10 words and symbols, how many
15000 contain between 10 and 19 words and symbols, how many contain between
15001 20 and 29 words and symbols, and so on.
15003 With a sorted list of numbers, this is easy: count how many elements
15004 of the list are smaller than 10, then, after moving past the numbers
15005 just counted, count how many are smaller than 20, then, after moving
15006 past the numbers just counted, count how many are smaller than 30, and
15007 so on.  Each of the numbers, 10, 20, 30, 40, and the like, is one
15008 larger than the top of that range.  We can call the list of such
15009 numbers the @code{top-of-ranges} list.
15011 @need 1200
15012 If we wished, we could generate this list automatically, but it is
15013 simpler to write a list manually.  Here it is:
15014 @vindex top-of-ranges
15016 @smallexample
15017 @group
15018 (defvar top-of-ranges
15019  '(10  20  30  40  50
15020    60  70  80  90 100
15021   110 120 130 140 150
15022   160 170 180 190 200
15023   210 220 230 240 250
15024   260 270 280 290 300)
15025  "List specifying ranges for `defuns-per-range'.")
15026 @end group
15027 @end smallexample
15029 To change the ranges, we edit this list.
15031 Next, we need to write the function that creates the list of the
15032 number of definitions within each range.  Clearly, this function must
15033 take the @code{sorted-lengths} and the @code{top-of-ranges} lists
15034 as arguments.
15036 The @code{defuns-per-range} function must do two things again and
15037 again: it must count the number of definitions within a range
15038 specified by the current top-of-range value; and it must shift to the
15039 next higher value in the @code{top-of-ranges} list after counting the
15040 number of definitions in the current range.  Since each of these
15041 actions is repetitive, we can use @code{while} loops for the job.
15042 One loop counts the number of definitions in the range defined by the
15043 current top-of-range value, and the other loop selects each of the
15044 top-of-range values in turn.
15046 Several entries of the @code{sorted-lengths} list are counted for each
15047 range; this means that the loop for the @code{sorted-lengths} list
15048 will be inside the loop for the @code{top-of-ranges} list, like a
15049 small gear inside a big gear.
15051 The inner loop counts the number of definitions within the range.  It
15052 is a simple counting loop of the type we have seen before.
15053 (@xref{Incrementing Loop, , A loop with an incrementing counter}.)
15054 The true-or-false test of the loop tests whether the value from the
15055 @code{sorted-lengths} list is smaller than the current value of the
15056 top of the range.  If it is, the function increments the counter and
15057 tests the next value from the @code{sorted-lengths} list.
15059 @need 1250
15060 The inner loop looks like this:
15062 @smallexample
15063 @group
15064 (while @var{length-element-smaller-than-top-of-range}
15065   (setq number-within-range (1+ number-within-range))
15066   (setq sorted-lengths (cdr sorted-lengths)))
15067 @end group
15068 @end smallexample
15070 The outer loop must start with the lowest value of the
15071 @code{top-of-ranges} list, and then be set to each of the succeeding
15072 higher values in turn.  This can be done with a loop like this:
15074 @smallexample
15075 @group
15076 (while top-of-ranges
15077   @var{body-of-loop}@dots{}
15078   (setq top-of-ranges (cdr top-of-ranges)))
15079 @end group
15080 @end smallexample
15082 @need 1200
15083 Put together, the two loops look like this:
15085 @smallexample
15086 @group
15087 (while top-of-ranges
15089   ;; @r{Count the number of elements within the current range.}
15090   (while @var{length-element-smaller-than-top-of-range}
15091     (setq number-within-range (1+ number-within-range))
15092     (setq sorted-lengths (cdr sorted-lengths)))
15094   ;; @r{Move to next range.}
15095   (setq top-of-ranges (cdr top-of-ranges)))
15096 @end group
15097 @end smallexample
15099 In addition, in each circuit of the outer loop, Emacs should record
15100 the number of definitions within that range (the value of
15101 @code{number-within-range}) in a list.  We can use @code{cons} for
15102 this purpose.  (@xref{cons, , @code{cons}}.)
15104 The @code{cons} function works fine, except that the list it
15105 constructs will contain the number of definitions for the highest
15106 range at its beginning and the number of definitions for the lowest
15107 range at its end.  This is because @code{cons} attaches new elements
15108 of the list to the beginning of the list, and since the two loops are
15109 working their way through the lengths' list from the lower end first,
15110 the @code{defuns-per-range-list} will end up largest number first.
15111 But we will want to print our graph with smallest values first and the
15112 larger later.  The solution is to reverse the order of the
15113 @code{defuns-per-range-list}.  We can do this using the
15114 @code{nreverse} function, which reverses the order of a list.
15115 @findex nreverse
15117 @need 800
15118 For example,
15120 @smallexample
15121 (nreverse '(1 2 3 4))
15122 @end smallexample
15124 @need 800
15125 @noindent
15126 produces:
15128 @smallexample
15129 (4 3 2 1)
15130 @end smallexample
15132 Note that the @code{nreverse} function is ``destructive''---that is,
15133 it changes the list to which it is applied; this contrasts with the
15134 @code{car} and @code{cdr} functions, which are non-destructive.  In
15135 this case, we do not want the original @code{defuns-per-range-list},
15136 so it does not matter that it is destroyed.  (The @code{reverse}
15137 function provides a reversed copy of a list, leaving the original list
15138 as is.)
15139 @findex reverse
15141 @need 1250
15142 Put all together, the @code{defuns-per-range} looks like this:
15144 @smallexample
15145 @group
15146 (defun defuns-per-range (sorted-lengths top-of-ranges)
15147   "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
15148   (let ((top-of-range (car top-of-ranges))
15149         (number-within-range 0)
15150         defuns-per-range-list)
15151 @end group
15153 @group
15154     ;; @r{Outer loop.}
15155     (while top-of-ranges
15156 @end group
15158 @group
15159       ;; @r{Inner loop.}
15160       (while (and
15161               ;; @r{Need number for numeric test.}
15162               (car sorted-lengths)
15163               (< (car sorted-lengths) top-of-range))
15164 @end group
15166 @group
15167         ;; @r{Count number of definitions within current range.}
15168         (setq number-within-range (1+ number-within-range))
15169         (setq sorted-lengths (cdr sorted-lengths)))
15171       ;; @r{Exit inner loop but remain within outer loop.}
15172 @end group
15174 @group
15175       (setq defuns-per-range-list
15176             (cons number-within-range defuns-per-range-list))
15177       (setq number-within-range 0)      ; @r{Reset count to zero.}
15178 @end group
15180 @group
15181       ;; @r{Move to next range.}
15182       (setq top-of-ranges (cdr top-of-ranges))
15183       ;; @r{Specify next top of range value.}
15184       (setq top-of-range (car top-of-ranges)))
15185 @end group
15187 @group
15188     ;; @r{Exit outer loop and count the number of defuns larger than}
15189     ;; @r{  the largest top-of-range value.}
15190     (setq defuns-per-range-list
15191           (cons
15192            (length sorted-lengths)
15193            defuns-per-range-list))
15194 @end group
15196 @group
15197     ;; @r{Return a list of the number of definitions within each range,}
15198     ;; @r{  smallest to largest.}
15199     (nreverse defuns-per-range-list)))
15200 @end group
15201 @end smallexample
15203 @need 1200
15204 @noindent
15205 The function is straightforward except for one subtle feature.  The
15206 true-or-false test of the inner loop looks like this:
15208 @smallexample
15209 @group
15210 (and (car sorted-lengths)
15211      (< (car sorted-lengths) top-of-range))
15212 @end group
15213 @end smallexample
15215 @need 800
15216 @noindent
15217 instead of like this:
15219 @smallexample
15220 (< (car sorted-lengths) top-of-range)
15221 @end smallexample
15223 The purpose of the test is to determine whether the first item in the
15224 @code{sorted-lengths} list is less than the value of the top of the
15225 range.
15227 The simple version of the test works fine unless the
15228 @code{sorted-lengths} list has a @code{nil} value.  In that case, the
15229 @code{(car sorted-lengths)} expression function returns
15230 @code{nil}.  The @code{<} function cannot compare a number to
15231 @code{nil}, which is an empty list, so Emacs signals an error and
15232 stops the function from attempting to continue to execute.
15234 The @code{sorted-lengths} list always becomes @code{nil} when the
15235 counter reaches the end of the list.  This means that any attempt to
15236 use the @code{defuns-per-range} function with the simple version of
15237 the test will fail.
15239 We solve the problem by using the @code{(car sorted-lengths)}
15240 expression in conjunction with the @code{and} expression.  The
15241 @code{(car sorted-lengths)} expression returns a non-@code{nil}
15242 value so long as the list has at least one number within it, but
15243 returns @code{nil} if the list is empty.  The @code{and} expression
15244 first evaluates the @code{(car sorted-lengths)} expression, and
15245 if it is @code{nil}, returns false @emph{without} evaluating the
15246 @code{<} expression.  But if the @code{(car sorted-lengths)}
15247 expression returns a non-@code{nil} value, the @code{and} expression
15248 evaluates the @code{<} expression, and returns that value as the value
15249 of the @code{and} expression.
15251 @c colon in printed section title causes problem in Info cross reference
15252 This way, we avoid an error.
15253 @iftex
15254 @xref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
15255 Functions}, for more information about @code{and}.
15256 @end iftex
15257 @ifinfo
15258 @xref{forward-paragraph}, for more information about @code{and}.
15259 @end ifinfo
15261 Here is a short test of the @code{defuns-per-range} function.  First,
15262 evaluate the expression that binds (a shortened)
15263 @code{top-of-ranges} list to the list of values, then evaluate the
15264 expression for binding the @code{sorted-lengths} list, and then
15265 evaluate the @code{defuns-per-range} function.
15267 @smallexample
15268 @group
15269 ;; @r{(Shorter list than we will use later.)}
15270 (setq top-of-ranges
15271  '(110 120 130 140 150
15272    160 170 180 190 200))
15274 (setq sorted-lengths
15275       '(85 86 110 116 122 129 154 176 179 200 265 300 300))
15277 (defuns-per-range sorted-lengths top-of-ranges)
15278 @end group
15279 @end smallexample
15281 @need 800
15282 @noindent
15283 The list returned looks like this:
15285 @smallexample
15286 (2 2 2 0 0 1 0 2 0 0 4)
15287 @end smallexample
15289 @noindent
15290 Indeed, there are two elements of the @code{sorted-lengths} list
15291 smaller than 110, two elements between 110 and 119, two elements
15292 between 120 and 129, and so on.  There are four elements with a value
15293 of 200 or larger.
15295 @c The next step is to turn this numbers' list into a graph.
15297 @node Readying a Graph, Emacs Initialization, Words in a defun, Top
15298 @chapter Readying a Graph
15299 @cindex Readying a graph
15300 @cindex Graph prototype
15301 @cindex Prototype graph
15302 @cindex Body of graph
15304 Our goal is to construct a graph showing the numbers of function
15305 definitions of various lengths in the Emacs lisp sources.
15307 As a practical matter, if you were creating a graph, you would
15308 probably use a program such as @code{gnuplot} to do the job.
15309 (@code{gnuplot} is nicely integrated into GNU Emacs.)  In this case,
15310 however, we create one from scratch, and in the process we will
15311 re-acquaint ourselves with some of what we learned before and learn
15312 more.
15314 In this chapter, we will first write a simple graph printing function.
15315 This first definition will be a @dfn{prototype}, a rapidly written
15316 function that enables us to reconnoiter this unknown graph-making
15317 territory.  We will discover dragons, or find that they are myth.
15318 After scouting the terrain, we will feel more confident and enhance
15319 the function to label the axes automatically.
15321 @menu
15322 * Columns of a graph::
15323 * graph-body-print::            How to print the body of a graph.
15324 * recursive-graph-body-print::
15325 * Printed Axes::
15326 * Line Graph Exercise::
15327 @end menu
15329 @node Columns of a graph, graph-body-print, Readying a Graph, Readying a Graph
15330 @ifnottex
15331 @unnumberedsec Printing the Columns of a Graph
15332 @end ifnottex
15334 Since Emacs is designed to be flexible and work with all kinds of
15335 terminals, including character-only terminals, the graph will need to
15336 be made from one of the `typewriter' symbols.  An asterisk will do; as
15337 we enhance the graph-printing function, we can make the choice of
15338 symbol a user option.
15340 We can call this function @code{graph-body-print}; it will take a
15341 @code{numbers-list} as its only argument.  At this stage, we will not
15342 label the graph, but only print its body.
15344 The @code{graph-body-print} function inserts a vertical column of
15345 asterisks for each element in the @code{numbers-list}.  The height of
15346 each line is determined by the value of that element of the
15347 @code{numbers-list}.
15349 Inserting columns is a repetitive act; that means that this function can
15350 be written either with a @code{while} loop or recursively.
15352 Our first challenge is to discover how to print a column of asterisks.
15353 Usually, in Emacs, we print characters onto a screen horizontally,
15354 line by line, by typing.  We have two routes we can follow: write our
15355 own column-insertion function or discover whether one exists in Emacs.
15357 To see whether there is one in Emacs, we can use the @kbd{M-x apropos}
15358 command.  This command is like the @kbd{C-h a} (command-apropos)
15359 command, except that the latter finds only those functions that are
15360 commands.  The @kbd{M-x apropos} command lists all symbols that match
15361 a regular expression, including functions that are not interactive.
15362 @findex apropos
15364 What we want to look for is some command that prints or inserts
15365 columns.  Very likely, the name of the function will contain either
15366 the word `print' or the word `insert' or the word `column'.
15367 Therefore, we can simply type @kbd{M-x apropos RET
15368 print\|insert\|column RET} and look at the result.  On my system, this
15369 command takes quite some time, and then produces a list of 79
15370 functions and variables.  Scanning down the list, the only function
15371 that looks as if it might do the job is @code{insert-rectangle}.
15373 @need 1200
15374 Indeed, this is the function we want; its documentation says:
15376 @smallexample
15377 @group
15378 insert-rectangle:
15379 Insert text of RECTANGLE with upper left corner at point.
15380 RECTANGLE's first line is inserted at point,
15381 its second line is inserted at a point vertically under point, etc.
15382 RECTANGLE should be a list of strings.
15383 @end group
15384 @end smallexample
15386 We can run a quick test, to make sure it does what we expect of it.
15388 Here is the result of placing the cursor after the
15389 @code{insert-rectangle} expression and typing @kbd{C-u C-x C-e}
15390 (@code{eval-last-sexp}).  The function inserts the strings
15391 @samp{"first"}, @samp{"second"}, and @samp{"third"} at and below
15392 point.  Also the function returns @code{nil}.
15394 @smallexample
15395 @group
15396 (insert-rectangle '("first" "second" "third"))first
15397                                               second
15398                                               third
15400 @end group
15401 @end smallexample
15403 @noindent
15404 Of course, we won't be inserting the text of the
15405 @code{insert-rectangle} expression itself into the buffer in which we
15406 are making the graph, but will call the function from our program.  We
15407 shall, however, have to make sure that point is in the buffer at the
15408 place where the @code{insert-rectangle} function will insert its
15409 column of strings.
15411 If you are reading this in Info, you can see how this works by
15412 switching to another buffer, such as the @file{*scratch*} buffer,
15413 placing point somewhere in the buffer, typing @kbd{M-:},
15414 typing the @code{insert-rectangle} expression into the minibuffer at
15415 the prompt, and then typing @key{RET}.  This causes Emacs to evaluate
15416 the expression in the minibuffer, but to use as the value of point the
15417 position of point in the @file{*scratch*} buffer.  (@kbd{M-:}
15418 is the keybinding for @code{eval-expression}.)
15420 We find when we do this that point ends up at the end of the last
15421 inserted line---that is to say, this function moves point as a
15422 side-effect.  If we were to repeat the command, with point at this
15423 position, the next insertion would be below and to the right of the
15424 previous insertion.  We don't want this!  If we are going to make a
15425 bar graph, the columns need to be beside each other.
15427 So we discover that each cycle of the column-inserting @code{while}
15428 loop must reposition point to the place we want it, and that place
15429 will be at the top, not the bottom, of the column.  Moreover, we
15430 remember that when we print a graph, we do not expect all the columns
15431 to be the same height.  This means that the top of each column may be
15432 at a different height from the previous one.  We cannot simply
15433 reposition point to the same line each time, but moved over to the
15434 right---or perhaps we can@dots{}
15436 We are planning to make the columns of the bar graph out of asterisks.
15437 The number of asterisks in the column is the number specified by the
15438 current element of the @code{numbers-list}.  We need to construct a
15439 list of asterisks of the right length for each call to
15440 @code{insert-rectangle}.  If this list consists solely of the requisite
15441 number of asterisks, then we will have position point the right number
15442 of lines above the base for the graph to print correctly.  This could
15443 be difficult.
15445 Alternatively, if we can figure out some way to pass
15446 @code{insert-rectangle} a list of the same length each time, then we
15447 can place point on the same line each time, but move it over one
15448 column to the right for each new column.  If we do this, however, some
15449 of the entries in the list passed to @code{insert-rectangle} must be
15450 blanks rather than asterisks.  For example, if the maximum height of
15451 the graph is 5, but the height of the column is 3, then
15452 @code{insert-rectangle} requires an argument that looks like this:
15454 @smallexample
15455 (" " " " "*" "*" "*")
15456 @end smallexample
15458 This last proposal is not so difficult, so long as we can determine
15459 the column height.  There are two ways for us to specify the column
15460 height: we can arbitrarily state what it will be, which would work
15461 fine for graphs of that height; or we can search through the list of
15462 numbers and use the maximum height of the list as the maximum height
15463 of the graph.  If the latter operation were difficult, then the former
15464 procedure would be easiest, but there is a function built into Emacs
15465 that determines the maximum of its arguments.  We can use that
15466 function.  The function is called @code{max} and it returns the
15467 largest of all its arguments, which must be numbers.  Thus, for
15468 example,
15470 @smallexample
15471 (max  3 4 6 5 7 3)
15472 @end smallexample
15474 @noindent
15475 returns 7.  (A corresponding function called @code{min} returns the
15476 smallest of all its arguments.)
15477 @findex max
15478 @findex min
15480 However, we cannot simply call @code{max} on the @code{numbers-list};
15481 the @code{max} function expects numbers as its argument, not a list of
15482 numbers.  Thus, the following expression,
15484 @smallexample
15485 (max  '(3 4 6 5 7 3))
15486 @end smallexample
15488 @need 800
15489 @noindent
15490 produces the following error message;
15492 @smallexample
15493 Wrong type of argument:  number-or-marker-p, (3 4 6 5 7 3)
15494 @end smallexample
15496 @findex apply
15497 We need a function that passes a list of arguments to a function.
15498 This function is @code{apply}.  This function `applies' its first
15499 argument (a function) to its remaining arguments, the last of which
15500 may be a list.
15502 @need 1250
15503 For example,
15505 @smallexample
15506 (apply 'max 3 4 7 3 '(4 8 5))
15507 @end smallexample
15509 @noindent
15510 returns 8.
15512 (Incidentally, I don't know how you would learn of this function
15513 without a book such as this.  It is possible to discover other
15514 functions, like @code{search-forward} or @code{insert-rectangle}, by
15515 guessing at a part of their names and then using @code{apropos}.  Even
15516 though its base in metaphor is clear---`apply' its first argument to
15517 the rest---I doubt a novice would come up with that particular word
15518 when using @code{apropos} or other aid.  Of course, I could be wrong;
15519 after all, the function was first named by someone who had to invent
15520 it.)
15522 The second and subsequent arguments to @code{apply} are optional, so
15523 we can use @code{apply} to call a function and pass the elements of a
15524 list to it, like this, which also returns 8:
15526 @smallexample
15527 (apply 'max '(4 8 5))
15528 @end smallexample
15530 This latter way is how we will use @code{apply}.  The
15531 @code{recursive-lengths-list-many-files} function returns a numbers'
15532 list to which we can apply @code{max} (we could also apply @code{max} to
15533 the sorted numbers' list; it does not matter whether the list is
15534 sorted or not.)
15536 @need 800
15537 Hence, the operation for finding the maximum height of the graph is this:
15539 @smallexample
15540 (setq max-graph-height (apply 'max numbers-list))
15541 @end smallexample
15543 Now we can return to the question of how to create a list of strings
15544 for a column of the graph.  Told the maximum height of the graph
15545 and the number of asterisks that should appear in the column, the
15546 function should return a list of strings for the
15547 @code{insert-rectangle} command to insert.
15549 Each column is made up of asterisks or blanks.  Since the function is
15550 passed the value of the height of the column and the number of
15551 asterisks in the column, the number of blanks can be found by
15552 subtracting the number of asterisks from the height of the column.
15553 Given the number of blanks and the number of asterisks, two
15554 @code{while} loops can be used to construct the list:
15556 @smallexample
15557 @group
15558 ;;; @r{First version.}
15559 (defun column-of-graph (max-graph-height actual-height)
15560   "Return list of strings that is one column of a graph."
15561   (let ((insert-list nil)
15562         (number-of-top-blanks
15563          (- max-graph-height actual-height)))
15564 @end group
15566 @group
15567     ;; @r{Fill in asterisks.}
15568     (while (> actual-height 0)
15569       (setq insert-list (cons "*" insert-list))
15570       (setq actual-height (1- actual-height)))
15571 @end group
15573 @group
15574     ;; @r{Fill in blanks.}
15575     (while (> number-of-top-blanks 0)
15576       (setq insert-list (cons " " insert-list))
15577       (setq number-of-top-blanks
15578             (1- number-of-top-blanks)))
15579 @end group
15581 @group
15582     ;; @r{Return whole list.}
15583     insert-list))
15584 @end group
15585 @end smallexample
15587 If you install this function and then evaluate the following
15588 expression you will see that it returns the list as desired:
15590 @smallexample
15591 (column-of-graph 5 3)
15592 @end smallexample
15594 @need 800
15595 @noindent
15596 returns
15598 @smallexample
15599 (" " " " "*" "*" "*")
15600 @end smallexample
15602 As written, @code{column-of-graph} contains a major flaw: the symbols
15603 used for the blank and for the marked entries in the column are
15604 `hard-coded' as a space and asterisk.  This is fine for a prototype,
15605 but you, or another user, may wish to use other symbols.  For example,
15606 in testing the graph function, you many want to use a period in place
15607 of the space, to make sure the point is being repositioned properly
15608 each time the @code{insert-rectangle} function is called; or you might
15609 want to substitute a @samp{+} sign or other symbol for the asterisk.
15610 You might even want to make a graph-column that is more than one
15611 display column wide.  The program should be more flexible.  The way to
15612 do that is to replace the blank and the asterisk with two variables
15613 that we can call @code{graph-blank} and @code{graph-symbol} and define
15614 those variables separately.
15616 Also, the documentation is not well written.  These considerations
15617 lead us to the second version of the function:
15619 @smallexample
15620 @group
15621 (defvar graph-symbol "*"
15622   "String used as symbol in graph, usually an asterisk.")
15623 @end group
15625 @group
15626 (defvar graph-blank " "
15627   "String used as blank in graph, usually a blank space.
15628 graph-blank must be the same number of columns wide
15629 as graph-symbol.")
15630 @end group
15631 @end smallexample
15633 @noindent
15634 (For an explanation of @code{defvar}, see
15635 @ref{defvar, , Initializing a Variable with @code{defvar}}.)
15637 @smallexample
15638 @group
15639 ;;; @r{Second version.}
15640 (defun column-of-graph (max-graph-height actual-height)
15641   "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
15643 @end group
15644 @group
15645 The graph-symbols are contiguous entries at the end
15646 of the list.
15647 The list will be inserted as one column of a graph.
15648 The strings are either graph-blank or graph-symbol."
15649 @end group
15651 @group
15652   (let ((insert-list nil)
15653         (number-of-top-blanks
15654          (- max-graph-height actual-height)))
15655 @end group
15657 @group
15658     ;; @r{Fill in @code{graph-symbols}.}
15659     (while (> actual-height 0)
15660       (setq insert-list (cons graph-symbol insert-list))
15661       (setq actual-height (1- actual-height)))
15662 @end group
15664 @group
15665     ;; @r{Fill in @code{graph-blanks}.}
15666     (while (> number-of-top-blanks 0)
15667       (setq insert-list (cons graph-blank insert-list))
15668       (setq number-of-top-blanks
15669             (1- number-of-top-blanks)))
15671     ;; @r{Return whole list.}
15672     insert-list))
15673 @end group
15674 @end smallexample
15676 If we wished, we could rewrite @code{column-of-graph} a third time to
15677 provide optionally for a line graph as well as for a bar graph.  This
15678 would not be hard to do.  One way to think of a line graph is that it
15679 is no more than a bar graph in which the part of each bar that is
15680 below the top is blank.  To construct a column for a line graph, the
15681 function first constructs a list of blanks that is one shorter than
15682 the value, then it uses @code{cons} to attach a graph symbol to the
15683 list; then it uses @code{cons} again to attach the `top blanks' to
15684 the list.
15686 It is easy to see how to write such a function, but since we don't
15687 need it, we will not do it.  But the job could be done, and if it were
15688 done, it would be done with @code{column-of-graph}.  Even more
15689 important, it is worth noting that few changes would have to be made
15690 anywhere else.  The enhancement, if we ever wish to make it, is
15691 simple.
15693 Now, finally, we come to our first actual graph printing function.
15694 This prints the body of a graph, not the labels for the vertical and
15695 horizontal axes, so we can call this @code{graph-body-print}.
15697 @node graph-body-print, recursive-graph-body-print, Columns of a graph, Readying a Graph
15698 @section The @code{graph-body-print} Function
15699 @findex graph-body-print
15701 After our preparation in the preceding section, the
15702 @code{graph-body-print} function is straightforward.  The function
15703 will print column after column of asterisks and blanks, using the
15704 elements of a numbers' list to specify the number of asterisks in each
15705 column.  This is a repetitive act, which means we can use a
15706 decrementing @code{while} loop or recursive function for the job.  In
15707 this section, we will write the definition using a @code{while} loop.
15709 The @code{column-of-graph} function requires the height of the graph
15710 as an argument, so we should determine and record that as a local variable.
15712 This leads us to the following template for the @code{while} loop
15713 version of this function:
15715 @smallexample
15716 @group
15717 (defun graph-body-print (numbers-list)
15718   "@var{documentation}@dots{}"
15719   (let ((height  @dots{}
15720          @dots{}))
15721 @end group
15723 @group
15724     (while numbers-list
15725       @var{insert-columns-and-reposition-point}
15726       (setq numbers-list (cdr numbers-list)))))
15727 @end group
15728 @end smallexample
15730 @noindent
15731 We need to fill in the slots of the template.
15733 Clearly, we can use the @code{(apply 'max numbers-list)} expression to
15734 determine the height of the graph.
15736 The @code{while} loop will cycle through the @code{numbers-list} one
15737 element at a time.  As it is shortened by the @code{(setq numbers-list
15738 (cdr numbers-list))} expression, the @sc{car} of each instance of the
15739 list is the value of the argument for @code{column-of-graph}.
15741 At each cycle of the @code{while} loop, the @code{insert-rectangle}
15742 function inserts the list returned by @code{column-of-graph}.  Since
15743 the @code{insert-rectangle} function moves point to the lower right of
15744 the inserted rectangle, we need to save the location of point at the
15745 time the rectangle is inserted, move back to that position after the
15746 rectangle is inserted, and then move horizontally to the next place
15747 from which @code{insert-rectangle} is called.
15749 If the inserted columns are one character wide, as they will be if
15750 single blanks and asterisks are used, the repositioning command is
15751 simply @code{(forward-char 1)}; however, the width of a column may be
15752 greater than one.  This means that the repositioning command should be
15753 written @code{(forward-char symbol-width)}.  The @code{symbol-width}
15754 itself is the length of a @code{graph-blank} and can be found using
15755 the expression @code{(length graph-blank)}.  The best place to bind
15756 the @code{symbol-width} variable to the value of the width of graph
15757 column is in the varlist of the @code{let} expression.
15759 @need 1250
15760 These considerations lead to the following function definition:
15762 @smallexample
15763 @group
15764 (defun graph-body-print (numbers-list)
15765   "Print a bar graph of the NUMBERS-LIST.
15766 The numbers-list consists of the Y-axis values."
15768   (let ((height (apply 'max numbers-list))
15769         (symbol-width (length graph-blank))
15770         from-position)
15771 @end group
15773 @group
15774     (while numbers-list
15775       (setq from-position (point))
15776       (insert-rectangle
15777        (column-of-graph height (car numbers-list)))
15778       (goto-char from-position)
15779       (forward-char symbol-width)
15780 @end group
15781 @group
15782       ;; @r{Draw graph column by column.}
15783       (sit-for 0)
15784       (setq numbers-list (cdr numbers-list)))
15785 @end group
15786 @group
15787     ;; @r{Place point for X axis labels.}
15788     (forward-line height)
15789     (insert "\n")
15791 @end group
15792 @end smallexample
15794 @noindent
15795 The one unexpected expression in this function is the
15796 @w{@code{(sit-for 0)}} expression in the @code{while} loop.  This
15797 expression makes the graph printing operation more interesting to
15798 watch than it would be otherwise.  The expression causes Emacs to
15799 `sit' or do nothing for a zero length of time and then redraw the
15800 screen.  Placed here, it causes Emacs to redraw the screen column by
15801 column.  Without it, Emacs would not redraw the screen until the
15802 function exits.
15804 We can test @code{graph-body-print} with a short list of numbers.
15806 @enumerate
15807 @item
15808 Install @code{graph-symbol}, @code{graph-blank},
15809 @code{column-of-graph}, which are in
15810 @iftex
15811 @ref{Readying a Graph, , Readying a Graph},
15812 @end iftex
15813 @ifinfo
15814 @ref{Columns of a graph},
15815 @end ifinfo
15816 and @code{graph-body-print}.
15818 @need 800
15819 @item
15820 Copy the following expression:
15822 @smallexample
15823 (graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
15824 @end smallexample
15826 @item
15827 Switch to the @file{*scratch*} buffer and place the cursor where you
15828 want the graph to start.
15830 @item
15831 Type @kbd{M-:} (@code{eval-expression}).
15833 @item
15834 Yank the @code{graph-body-print} expression into the minibuffer
15835 with @kbd{C-y} (@code{yank)}.
15837 @item
15838 Press @key{RET} to evaluate the @code{graph-body-print} expression.
15839 @end enumerate
15841 @need 800
15842 Emacs will print a graph like this:
15844 @smallexample
15845 @group
15846                     *
15847                 *   **
15848                 *  ****
15849                *** ****
15850               ********* *
15851              ************
15852             *************
15853 @end group
15854 @end smallexample
15856 @node recursive-graph-body-print, Printed Axes, graph-body-print, Readying a Graph
15857 @section The @code{recursive-graph-body-print} Function
15858 @findex recursive-graph-body-print
15860 The @code{graph-body-print} function may also be written recursively.
15861 The recursive solution is divided into two parts: an outside `wrapper'
15862 that uses a @code{let} expression to determine the values of several
15863 variables that need only be found once, such as the maximum height of
15864 the graph, and an inside function that is called recursively to print
15865 the graph.
15867 @need 1250
15868 The `wrapper' is uncomplicated:
15870 @smallexample
15871 @group
15872 (defun recursive-graph-body-print (numbers-list)
15873   "Print a bar graph of the NUMBERS-LIST.
15874 The numbers-list consists of the Y-axis values."
15875   (let ((height (apply 'max numbers-list))
15876         (symbol-width (length graph-blank))
15877         from-position)
15878     (recursive-graph-body-print-internal
15879      numbers-list
15880      height
15881      symbol-width)))
15882 @end group
15883 @end smallexample
15885 The recursive function is a little more difficult.  It has four parts:
15886 the `do-again-test', the printing code, the recursive call, and the
15887 `next-step-expression'.  The `do-again-test' is an @code{if}
15888 expression that determines whether the @code{numbers-list} contains
15889 any remaining elements; if it does, the function prints one column of
15890 the graph using the printing code and calls itself again.  The
15891 function calls itself again according to the value produced by the
15892 `next-step-expression' which causes the call to act on a shorter
15893 version of the @code{numbers-list}.
15895 @smallexample
15896 @group
15897 (defun recursive-graph-body-print-internal
15898   (numbers-list height symbol-width)
15899   "Print a bar graph.
15900 Used within recursive-graph-body-print function."
15901 @end group
15903 @group
15904   (if numbers-list
15905       (progn
15906         (setq from-position (point))
15907         (insert-rectangle
15908          (column-of-graph height (car numbers-list)))
15909 @end group
15910 @group
15911         (goto-char from-position)
15912         (forward-char symbol-width)
15913         (sit-for 0)     ; @r{Draw graph column by column.}
15914         (recursive-graph-body-print-internal
15915          (cdr numbers-list) height symbol-width))))
15916 @end group
15917 @end smallexample
15919 @need 1250
15920 After installation, this expression can be tested; here is a sample:
15922 @smallexample
15923 (recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
15924 @end smallexample
15926 @need 800
15927 Here is what @code{recursive-graph-body-print} produces:
15929 @smallexample
15930 @group
15931                 *
15932                **   *
15933               ****  *
15934               **** ***
15935             * *********
15936             ************
15937             *************
15938 @end group
15939 @end smallexample
15941 Either of these two functions, @code{graph-body-print} or
15942 @code{recursive-graph-body-print}, create the body of a graph.
15944 @node Printed Axes, Line Graph Exercise, recursive-graph-body-print, Readying a Graph
15945 @section Need for Printed Axes
15947 A graph needs printed axes, so you can orient yourself.  For a do-once
15948 project, it may be reasonable to draw the axes by hand using Emacs'
15949 Picture mode; but a graph drawing function may be used more than once.
15951 For this reason, I have written enhancements to the basic
15952 @code{print-graph-body} function that automatically print labels for
15953 the horizontal and vertical axes.  Since the label printing functions
15954 do not contain much new material, I have placed their description in
15955 an appendix.  @xref{Full Graph, , A Graph with Labelled Axes}.
15957 @node Line Graph Exercise,  , Printed Axes, Readying a Graph
15958 @section Exercise
15960 Write a line graph version of the graph printing functions.
15962 @node Emacs Initialization, Debugging, Readying a Graph, Top
15963 @chapter Your @file{.emacs} File
15964 @cindex @file{.emacs} file
15965 @cindex Customizing your @file{.emacs} file
15966 @cindex Initialization file
15968 ``You don't have to like Emacs to like it'' -- this seemingly
15969 paradoxical statement is the secret of GNU Emacs.  The plain, `out of
15970 the box' Emacs is a generic tool.  Most people who use it, customize
15971 it to suit themselves.
15973 GNU Emacs is mostly written in Emacs Lisp; this means that by writing
15974 expressions in Emacs Lisp you can change or extend Emacs.
15976 @menu
15977 * Default Configuration::
15978 * Site-wide Init::              You can write site-wide init files.
15979 * defcustom::                   Emacs will write code for you.
15980 * Beginning a .emacs File::     How to write a @code{.emacs file}.
15981 * Text and Auto-fill::          Automatically wrap lines.
15982 * Mail Aliases::                Use abbreviations for email addresses.
15983 * Indent Tabs Mode::            Don't use tabs with @TeX{}
15984 * Keybindings::                 Create some personal keybindings.
15985 * Keymaps::                     More about key binding.
15986 * Loading Files::               Load (i.e., evaluate) files automatically.
15987 * Autoload::                    Make functions available.
15988 * Simple Extension::            Define a function; bind it to a key.
15989 * X11 Colors::                  Colors in version 19 in X.
15990 * Miscellaneous::
15991 * Mode Line::                   How to customize your mode line.
15992 @end menu
15994 @node Default Configuration, Site-wide Init, Emacs Initialization, Emacs Initialization
15995 @ifnottex
15996 @unnumberedsec Emacs' Default Configuration
15997 @end ifnottex
15999 There are those who appreciate Emacs' default configuration.  After
16000 all, Emacs starts you in C mode when you edit a C file, starts you in
16001 Fortran mode when you edit a Fortran file, and starts you in
16002 Fundamental mode when you edit an unadorned file.  This all makes
16003 sense, if you do not know who is going to use Emacs.  Who knows what a
16004 person hopes to do with an unadorned file?  Fundamental mode is the
16005 right default for such a file, just as C mode is the right default for
16006 editing C code.  But when you do know who is going to use Emacs---you,
16007 yourself---then it makes sense to customize Emacs.
16009 For example, I seldom want Fundamental mode when I edit an
16010 otherwise undistinguished file; I want Text mode.  This is why I
16011 customize Emacs: so it suits me.
16013 You can customize and extend Emacs by writing or adapting a
16014 @file{~/.emacs} file.  This is your personal initialization file; its
16015 contents, written in Emacs Lisp, tell Emacs what to do.@footnote{You
16016 may also add @file{.el} to @file{~/.emacs} and call it a
16017 @file{~/.emacs.el} file.  In the past, you were forbidden to type the
16018 extra keystrokes that the name @file{~/.emacs.el} requires, but now
16019 you may.  The new format is consistent with the Emacs Lisp file
16020 naming conventions; the old format saves typing.}
16022 A @file{~/.emacs} file contains Emacs Lisp code.  You can write this
16023 code yourself; or you can use Emacs' @code{customize} feature to write
16024 the code for you.  You can combine your own expressions and
16025 auto-written Customize expressions in your @file{.emacs} file.
16027 (I myself prefer to write my own expressions, except for those,
16028 particularly fonts, that I find easier to manipulate using the
16029 @code{customize} command.  I combine the two methods.)
16031 Most of this chapter is about writing expressions yourself.  It
16032 describes a simple @file{.emacs} file; for more information, see
16033 @ref{Init File, , The Init File, emacs, The GNU Emacs Manual}, and
16034 @ref{Init File, , The Init File, elisp, The GNU Emacs Lisp Reference
16035 Manual}.
16037 @node Site-wide Init, defcustom, Default Configuration, Emacs Initialization
16038 @section Site-wide Initialization Files
16040 @cindex @file{default.el} init file
16041 @cindex @file{site-init.el} init file
16042 @cindex @file{site-load.el} init file
16043 In addition to your personal initialization file, Emacs automatically
16044 loads various site-wide initialization files, if they exist.  These
16045 have the same form as your @file{.emacs} file, but are loaded by
16046 everyone.
16048 Two site-wide initialization files, @file{site-load.el} and
16049 @file{site-init.el}, are loaded into Emacs and then `dumped' if a
16050 `dumped' version of Emacs is created, as is most common.  (Dumped
16051 copies of Emacs load more quickly.  However, once a file is loaded and
16052 dumped, a change to it does not lead to a change in Emacs unless you
16053 load it yourself or re-dump Emacs.  @xref{Building Emacs, , Building
16054 Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the
16055 @file{INSTALL} file.)
16057 Three other site-wide initialization files are loaded automatically
16058 each time you start Emacs, if they exist.  These are
16059 @file{site-start.el}, which is loaded @emph{before} your @file{.emacs}
16060 file, and @file{default.el}, and the terminal type file, which are both
16061 loaded @emph{after} your @file{.emacs} file.
16063 Settings and definitions in your @file{.emacs} file will overwrite
16064 conflicting settings and definitions in a @file{site-start.el} file,
16065 if it exists; but the settings and definitions in a @file{default.el}
16066 or terminal type file will overwrite those in your @file{.emacs} file.
16067 (You can prevent interference from a terminal type file by setting
16068 @code{term-file-prefix} to @code{nil}.  @xref{Simple Extension, , A
16069 Simple Extension}.)
16071 @c Rewritten to avoid overfull hbox.
16072 The @file{INSTALL} file that comes in the distribution contains
16073 descriptions of the @file{site-init.el} and @file{site-load.el} files.
16075 The @file{loadup.el}, @file{startup.el}, and @file{loaddefs.el} files
16076 control loading.  These files are in the @file{lisp} directory of the
16077 Emacs distribution and are worth perusing.
16079 The @file{loaddefs.el} file contains a good many suggestions as to
16080 what to put into your own @file{.emacs} file, or into a site-wide
16081 initialization file.
16083 @node defcustom, Beginning a .emacs File, Site-wide Init, Emacs Initialization
16084 @section Specifying Variables using @code{defcustom}
16085 @findex defcustom
16087 You can specify variables using @code{defcustom} so that you and
16088 others can then use Emacs' @code{customize} feature to set their
16089 values.  (You cannot use @code{customize} to write function
16090 definitions; but you can write @code{defuns} in your @file{.emacs}
16091 file.  Indeed, you can write any Lisp expression in your @file{.emacs}
16092 file.)
16094 The @code{customize} feature depends on the @code{defcustom} special
16095 form.  Although you can use @code{defvar} or @code{setq} for variables
16096 that users set, the @code{defcustom} special form is designed for the
16097 job.
16099 You can use your knowledge of @code{defvar} for writing the
16100 first three arguments for @code{defcustom}.  The first argument to
16101 @code{defcustom} is the name of the variable.  The second argument is
16102 the variable's initial value, if any; and this value is set only if
16103 the value has not already been set.  The third argument is the
16104 documentation.
16106 The fourth and subsequent arguments to @code{defcustom} specify types
16107 and options; these are not featured in @code{defvar}.  (These
16108 arguments are optional.)
16110 Each of these arguments consists of a keyword followed by a value.
16111 Each keyword starts with the colon character @samp{:}.
16113 @need 1250
16114 For example, the customizable user option variable
16115 @code{text-mode-hook} looks like this:
16117 @smallexample
16118 @group
16119 (defcustom text-mode-hook nil
16120   "Normal hook run when entering Text mode and many related modes."
16121   :type 'hook
16122   :options '(turn-on-auto-fill flyspell-mode)
16123   :group 'data)
16124 @end group
16125 @end smallexample
16127 @noindent
16128 The name of the variable is @code{text-mode-hook}; it has no default
16129 value; and its documentation string tells you what it does.
16131 The @code{:type} keyword tells Emacs the kind of data to which
16132 @code{text-mode-hook} should be set and how to display the value in a
16133 Customization buffer.
16135 The @code{:options} keyword specifies a suggested list of values for
16136 the variable.  Currently, you can use @code{:options} only for a hook.
16137 The list is only a suggestion; it is not exclusive; a person who sets
16138 the variable may set it to other values; the list shown following the
16139 @code{:options} keyword is intended to offer convenient choices to a
16140 user.
16142 Finally, the @code{:group} keyword tells the Emacs Customization
16143 command in which group the variable is located.  This tells where to
16144 find it.
16146 For more information, see @ref{Customization, , Writing Customization
16147 Definitions, elisp, The GNU Emacs Lisp Reference Manual}.
16149 Consider @code{text-mode-hook} as an example.
16151 There are two ways to customize this variable.  You can use the
16152 customization command or write the appropriate expressions yourself.
16154 @need 800
16155 Using the customization command,  you can type:
16157 @smallexample
16158 M-x customize
16159 @end smallexample
16161 @noindent
16162 and find that the group for editing files of data is called `data'.
16163 Enter that group.  Text Mode Hook is the first member.  You can click
16164 on its various options to set the values.  After you click on the
16165 button to
16167 @smallexample
16168 Save for Future Sessions
16169 @end smallexample
16171 @noindent
16172 Emacs will write an expression into your @file{.emacs} file.
16173 It will look like this:
16175 @smallexample
16176 @group
16177 (custom-set-variables
16178   ;; custom-set-variables was added by Custom --
16179   ;;                           don't edit or cut/paste it!
16180   ;; Your init file should contain only one such instance.
16181  '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
16182 @end group
16183 @end smallexample
16185 @noindent
16186 (The @code{text-mode-hook-identify} function tells
16187 @code{toggle-text-mode-auto-fill} which buffers are in Text mode.)
16189 In spite of the warning, you certainly may edit, cut, and paste the
16190 expression!  I do all time.  The purpose of the warning is to scare
16191 those who do not know what they are doing, so they do not
16192 inadvertently generate an error.
16194 The @code{custom-set-variables} function works somewhat differently
16195 than a @code{setq}.  While I have never learned the differences, I do
16196 modify the @code{custom-set-variables} expressions in my @file{.emacs}
16197 file by hand:  I make the changes in what appears to me to be a
16198 reasonable manner and have not had any problems.  Others prefer to use
16199 the Customization command and let Emacs do the work for them.
16201 Another @code{custom-set-@dots{}} function is @code{custom-set-faces}.
16202 This function sets the various font faces.  Over time, I have set a
16203 considerable number of faces.  Some of the time, I re-set them using
16204 @code{customize}; other times, I simply edit the
16205 @code{custom-set-faces} expression in my @file{.emacs} file itself.
16207 The second way to customize your @code{text-mode-hook} is to set it
16208 yourself in your @file{.emacs} file using code that has nothing to do
16209 with the @code{custom-set-@dots{}} functions.
16211 @need 800
16212 When you do this, and later use @code{customize}, you will see a
16213 message that says
16215 @smallexample
16216 this option has been changed outside the customize buffer.
16217 @end smallexample
16219 @need 800
16220 This message is only a warning.  If you click on the button to
16222 @smallexample
16223 Save for Future Sessions
16224 @end smallexample
16226 @noindent
16227 Emacs will write a @code{custom-set-@dots{}} expression near the end
16228 of your @file{.emacs} file that will be evaluated after your
16229 hand-written expression.  It will, therefore, overrule your
16230 hand-written expression.  No harm will be done.  When you do this,
16231 however, be careful to remember which expression is active; if you
16232 forget, you may confuse yourself.
16234 So long as you remember where the values are set, you will have no
16235 trouble.  In any event, the values are always set in your
16236 initialization file, which is usually called @file{.emacs}.
16238 I myself use @code{customize} for hardly anything.  Mostly, I write
16239 expressions myself.
16241 @node Beginning a .emacs File, Text and Auto-fill, defcustom, Emacs Initialization
16242 @section Beginning a @file{.emacs} File
16243 @cindex @file{.emacs} file, beginning of
16245 When you start Emacs, it loads your @file{.emacs} file unless you tell
16246 it not to by specifying @samp{-q} on the command line.  (The
16247 @code{emacs -q} command gives you a plain, out-of-the-box Emacs.)
16249 A @file{.emacs} file contains Lisp expressions.  Often, these are no
16250 more than expressions to set values; sometimes they are function
16251 definitions.
16253 @xref{Init File, , The Init File @file{~/.emacs}, emacs, The GNU Emacs
16254 Manual}, for a short description of initialization files.
16256 This chapter goes over some of the same ground, but is a walk among
16257 extracts from a complete, long-used @file{.emacs} file---my own.
16259 The first part of the file consists of comments: reminders to myself.
16260 By now, of course, I remember these things, but when I started, I did
16261 not.
16263 @need 1200
16264 @smallexample
16265 @group
16266 ;;;; Bob's .emacs file
16267 ; Robert J. Chassell
16268 ; 26 September 1985
16269 @end group
16270 @end smallexample
16272 @noindent
16273 Look at that date!  I started this file a long time ago.  I have been
16274 adding to it ever since.
16276 @smallexample
16277 @group
16278 ; Each section in this file is introduced by a
16279 ; line beginning with four semicolons; and each
16280 ; entry is introduced by a line beginning with
16281 ; three semicolons.
16282 @end group
16283 @end smallexample
16285 @noindent
16286 This describes the usual conventions for comments in Emacs Lisp.
16287 Everything on a line that follows a semicolon is a comment.  Two,
16288 three, and four semicolons are used as section and subsection
16289 markers.  (@xref{Comments, ,, elisp, The GNU Emacs Lisp Reference
16290 Manual}, for more about comments.)
16292 @smallexample
16293 @group
16294 ;;;; The Help Key
16295 ; Control-h is the help key;
16296 ; after typing control-h, type a letter to
16297 ; indicate the subject about which you want help.
16298 ; For an explanation of the help facility,
16299 ; type control-h two times in a row.
16300 @end group
16301 @end smallexample
16303 @noindent
16304 Just remember: type @kbd{C-h} two times for help.
16306 @smallexample
16307 @group
16308 ; To find out about any mode, type control-h m
16309 ; while in that mode.  For example, to find out
16310 ; about mail mode, enter mail mode and then type
16311 ; control-h m.
16312 @end group
16313 @end smallexample
16315 @noindent
16316 `Mode help', as I call this, is very helpful.  Usually, it tells you
16317 all you need to know.
16319 Of course, you don't need to include comments like these in your
16320 @file{.emacs} file.  I included them in mine because I kept forgetting
16321 about Mode help or the conventions for comments---but I was able to
16322 remember to look here to remind myself.
16324 @node Text and Auto-fill, Mail Aliases, Beginning a .emacs File, Emacs Initialization
16325 @section Text and Auto Fill Mode
16327 Now we come to the part that `turns on' Text mode and
16328 Auto Fill mode.
16330 @smallexample
16331 @group
16332 ;;; Text mode and Auto Fill mode
16333 ; The next three lines put Emacs into Text mode
16334 ; and Auto Fill mode, and are for writers who
16335 ; want to start writing prose rather than code.
16337 (setq default-major-mode 'text-mode)
16338 (add-hook 'text-mode-hook 'text-mode-hook-identify)
16339 (add-hook 'text-mode-hook 'turn-on-auto-fill)
16340 @end group
16341 @end smallexample
16343 Here is the first part of this @file{.emacs} file that does something
16344 besides remind a forgetful human!
16346 The first of the two lines in parentheses tells Emacs to turn on Text
16347 mode when you find a file, @emph{unless} that file should go into some
16348 other mode, such as C mode.
16350 @cindex Per-buffer, local variables list
16351 @cindex Local variables list, per-buffer,
16352 @cindex Automatic mode selection
16353 @cindex Mode selection, automatic
16354 When Emacs reads a file, it looks at the extension to the file name,
16355 if any.  (The extension is the part that comes after a @samp{.}.)  If
16356 the file ends with a @samp{.c} or @samp{.h} extension then Emacs turns
16357 on C mode.  Also, Emacs looks at first nonblank line of the file; if
16358 the line says @w{@samp{-*- C -*-}}, Emacs turns on C mode.  Emacs
16359 possesses a list of extensions and specifications that it uses
16360 automatically.  In addition, Emacs looks near the last page for a
16361 per-buffer, ``local variables list'', if any.
16363 @ifinfo
16364 @xref{Choosing Modes, , How Major Modes are Chosen, emacs, The GNU
16365 Emacs Manual}.
16367 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16368 Manual}.
16369 @end ifinfo
16370 @iftex
16371 See sections ``How Major Modes are Chosen'' and ``Local Variables in
16372 Files'' in @cite{The GNU Emacs Manual}.
16373 @end iftex
16375 Now, back to the @file{.emacs} file.
16377 @need 800
16378 Here is the line again; how does it work?
16380 @cindex Text Mode turned on
16381 @smallexample
16382 (setq default-major-mode 'text-mode)
16383 @end smallexample
16385 @noindent
16386 This line is a short, but complete Emacs Lisp expression.
16388 We are already familiar with @code{setq}.  It sets the following variable,
16389 @code{default-major-mode}, to the subsequent value, which is
16390 @code{text-mode}.  The single quote mark before @code{text-mode} tells
16391 Emacs to deal directly with the @code{text-mode} variable, not with
16392 whatever it might stand for.  @xref{set & setq, , Setting the Value of
16393 a Variable}, for a reminder of how @code{setq} works.  The main point
16394 is that there is no difference between the procedure you use to set
16395 a value in your @file{.emacs} file and the procedure you use anywhere
16396 else in Emacs.
16398 @need 800
16399 Here are the next two lines:
16401 @cindex Auto Fill mode turned on
16402 @findex add-hook
16403 @smallexample
16404 (add-hook 'text-mode-hook 'text-mode-hook-identify)
16405 (add-hook 'text-mode-hook 'turn-on-auto-fill)
16406 @end smallexample
16408 @noindent
16409 In these two lines, the @code{add-hook} command first adds
16410 @code{text-mode-hook-identify} to the variable called
16411 @code{text-mode-hook} and then adds @code{turn-on-auto-fill} to the
16412 variable.
16414 @code{turn-on-auto-fill} is the name of a program, that, you guessed
16415 it!, turns on Auto Fill mode.  @code{text-mode-hook-identify} is a
16416 function that tells @code{toggle-text-mode-auto-fill} which buffers
16417 are in Text mode.
16419 Every time Emacs turns on Text mode, Emacs runs the commands `hooked'
16420 onto Text mode.  So every time Emacs turns on Text mode, Emacs also
16421 turns on Auto Fill mode.
16423 In brief, the first line causes Emacs to enter Text mode when you edit
16424 a file, unless the file name extension, first non-blank line, or local
16425 variables tell Emacs otherwise.
16427 Text mode among other actions, sets the syntax table to work
16428 conveniently for writers.  In Text mode, Emacs considers an apostrophe
16429 as part of a word like a letter; but Emacs does not consider a period
16430 or a space as part of a word.  Thus, @kbd{M-f} moves you over
16431 @samp{it's}.  On the other hand, in C mode, @kbd{M-f} stops just after
16432 the @samp{t} of @samp{it's}.
16434 The second and third lines causes Emacs to turn on Auto Fill mode when
16435 it turns on Text mode.  In Auto Fill mode, Emacs automatically breaks
16436 a line that is too wide and brings the excessively wide part of the
16437 line down to the next line.  Emacs breaks lines between words, not
16438 within them.
16440 When Auto Fill mode is turned off, lines continue to the right as you
16441 type them.  Depending on how you set the value of
16442 @code{truncate-lines}, the words you type either disappear off the
16443 right side of the screen, or else are shown, in a rather ugly and
16444 unreadable manner, as a continuation line on the screen.
16446 @need 1250
16447 In addition, in this part of my @file{.emacs} file, I tell the Emacs
16448 fill commands to insert two spaces after a colon:
16450 @smallexample
16451 (setq colon-double-space t)
16452 @end smallexample
16454 @node Mail Aliases, Indent Tabs Mode, Text and Auto-fill, Emacs Initialization
16455 @section Mail Aliases
16457 Here is a @code{setq} that `turns on' mail aliases, along with more
16458 reminders.
16460 @smallexample
16461 @group
16462 ;;; Mail mode
16463 ; To enter mail mode, type `C-x m'
16464 ; To enter RMAIL (for reading mail),
16465 ; type `M-x rmail'
16467 (setq mail-aliases t)
16468 @end group
16469 @end smallexample
16471 @cindex Mail aliases
16472 @noindent
16473 This @code{setq} command sets the value of the variable
16474 @code{mail-aliases} to @code{t}.  Since @code{t} means true, the line
16475 says, in effect, ``Yes, use mail aliases.''
16477 Mail aliases are convenient short names for long email addresses or
16478 for lists of email addresses.  The file where you keep your `aliases'
16479 is @file{~/.mailrc}.  You write an alias like this:
16481 @smallexample
16482 alias geo george@@foobar.wiz.edu
16483 @end smallexample
16485 @noindent
16486 When you write a message to George, address it to @samp{geo}; the
16487 mailer will automatically expand @samp{geo} to the full address.
16489 @node Indent Tabs Mode, Keybindings, Mail Aliases, Emacs Initialization
16490 @section Indent Tabs Mode
16491 @cindex Tabs, preventing
16492 @findex indent-tabs-mode
16494 By default, Emacs inserts tabs in place of multiple spaces when it
16495 formats a region.  (For example, you might indent many lines of text
16496 all at once with the @code{indent-region} command.)  Tabs look fine on
16497 a terminal or with ordinary printing, but they produce badly indented
16498 output when you use @TeX{} or Texinfo since @TeX{} ignores tabs.
16500 @need 1250
16501 The following turns off Indent Tabs mode:
16503 @smallexample
16504 @group
16505 ;;; Prevent Extraneous Tabs
16506 (setq-default indent-tabs-mode nil)
16507 @end group
16508 @end smallexample
16510 Note that this line uses @code{setq-default} rather than the
16511 @code{setq} command that we have seen before.  The @code{setq-default}
16512 command sets values only in buffers that do not have their own local
16513 values for the variable.
16515 @ifinfo
16516 @xref{Just Spaces, , Tabs vs. Spaces, emacs, The GNU Emacs Manual}.
16518 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16519 Manual}.
16520 @end ifinfo
16521 @iftex
16522 See sections ``Tabs vs.@: Spaces'' and ``Local Variables in
16523 Files'' in @cite{The GNU Emacs Manual}.
16524 @end iftex
16526 @node Keybindings, Keymaps, Indent Tabs Mode, Emacs Initialization
16527 @section Some Keybindings
16529 Now for some personal keybindings:
16531 @smallexample
16532 @group
16533 ;;; Compare windows
16534 (global-set-key "\C-cw" 'compare-windows)
16535 @end group
16536 @end smallexample
16538 @findex compare-windows
16539 @code{compare-windows} is a nifty command that compares the text in
16540 your current window with text in the next window.  It makes the
16541 comparison by starting at point in each window, moving over text in
16542 each window as far as they match.  I use this command all the time.
16544 This also shows how to set a key globally, for all modes.
16546 @cindex Setting a key globally
16547 @cindex Global set key
16548 @cindex Key setting globally
16549 @findex global-set-key
16550 The command is @code{global-set-key}.  It is followed by the
16551 keybinding.  In a @file{.emacs} file, the keybinding is written as
16552 shown: @code{\C-c} stands for `control-c', which means `press the
16553 control key and the @kbd{c} key at the same time'.  The @code{w} means
16554 `press the @kbd{w} key'.  The keybinding is surrounded by double
16555 quotation marks.  In documentation, you would write this as @kbd{C-c
16556 w}.  (If you were binding a @key{META} key, such as @kbd{M-c}, rather
16557 than a @key{CTL} key, you would write @code{\M-c}.  @xref{Init
16558 Rebinding, , Rebinding Keys in Your Init File, emacs, The GNU Emacs
16559 Manual}, for details.)
16561 The command invoked by the keys is @code{compare-windows}.  Note that
16562 @code{compare-windows} is preceded by a single quote; otherwise, Emacs
16563 would first try to evaluate the symbol to determine its value.
16565 These three things, the double quotation marks, the backslash before
16566 the @samp{C}, and the single quote mark are necessary parts of
16567 keybinding that I tend to forget.  Fortunately, I have come to
16568 remember that I should look at my existing @file{.emacs} file, and
16569 adapt what is there.
16571 As for the keybinding itself: @kbd{C-c w}.  This combines the prefix
16572 key, @kbd{C-c}, with a single character, in this case, @kbd{w}.  This
16573 set of keys, @kbd{C-c} followed by a single character, is strictly
16574 reserved for individuals' own use.  (I call these `own' keys, since
16575 these are for my own use.)  You should always be able to create such a
16576 keybinding for your own use without stomping on someone else's
16577 keybinding.  If you ever write an extension to Emacs, please avoid
16578 taking any of these keys for public use.  Create a key like @kbd{C-c
16579 C-w} instead.  Otherwise, we will run out of `own' keys.
16581 @need 1250
16582 Here is another keybinding, with a comment:
16584 @smallexample
16585 @group
16586 ;;; Keybinding for `occur'
16587 ; I use occur a lot, so let's bind it to a key:
16588 (global-set-key "\C-co" 'occur)
16589 @end group
16590 @end smallexample
16592 @findex occur
16593 The @code{occur} command shows all the lines in the current buffer
16594 that contain a match for a regular expression.  Matching lines are
16595 shown in a buffer called @file{*Occur*}.  That buffer serves as a menu
16596 to jump to occurrences.
16598 @findex global-unset-key
16599 @cindex Unbinding key
16600 @cindex Key unbinding
16601 @need 1250
16602 Here is how to unbind a key, so it does not
16603 work:
16605 @smallexample
16606 @group
16607 ;;; Unbind `C-x f'
16608 (global-unset-key "\C-xf")
16609 @end group
16610 @end smallexample
16612 There is a reason for this unbinding: I found I inadvertently typed
16613 @w{@kbd{C-x f}} when I meant to type @kbd{C-x C-f}.  Rather than find a
16614 file, as I intended, I accidentally set the width for filled text,
16615 almost always to a width I did not want.  Since I hardly ever reset my
16616 default width, I simply unbound the key.
16618 @findex list-buffers, @r{rebound}
16619 @findex buffer-menu, @r{bound to key}
16620 @need 1250
16621 The following rebinds an existing key:
16623 @smallexample
16624 @group
16625 ;;; Rebind `C-x C-b' for `buffer-menu'
16626 (global-set-key "\C-x\C-b" 'buffer-menu)
16627 @end group
16628 @end smallexample
16630 By default, @kbd{C-x C-b} runs the
16631 @code{list-buffers} command.  This command lists
16632 your buffers in @emph{another} window.  Since I
16633 almost always want to do something in that
16634 window, I prefer the  @code{buffer-menu}
16635 command, which not only lists the buffers,
16636 but moves point into that window.
16638 @node Keymaps, Loading Files, Keybindings, Emacs Initialization
16639 @section Keymaps
16640 @cindex Keymaps
16641 @cindex Rebinding keys
16643 Emacs uses @dfn{keymaps} to record which keys call which commands.
16644 When you use @code{global-set-key} to set the keybinding for a single
16645 command in all parts of Emacs, you are specifying the keybinding in
16646 @code{current-global-map}.
16648 Specific modes, such as C mode or Text mode, have their own keymaps;
16649 the mode-specific keymaps override the global map that is shared by
16650 all buffers.
16652 The @code{global-set-key} function binds, or rebinds, the global
16653 keymap.  For example, the following binds the key @kbd{C-x C-b} to the
16654 function @code{buffer-menu}:
16656 @smallexample
16657 (global-set-key "\C-x\C-b" 'buffer-menu)
16658 @end smallexample
16660 Mode-specific keymaps are bound using the @code{define-key} function,
16661 which takes a specific keymap as an argument, as well as the key and
16662 the command.  For example, my @file{.emacs} file contains the
16663 following expression to bind the @code{texinfo-insert-@@group} command
16664 to @kbd{C-c C-c g}:
16666 @smallexample
16667 @group
16668 (define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@@group)
16669 @end group
16670 @end smallexample
16672 @noindent
16673 The @code{texinfo-insert-@@group} function itself is a little extension
16674 to Texinfo mode that inserts @samp{@@group} into a Texinfo file.  I
16675 use this command all the time and prefer to type the three strokes
16676 @kbd{C-c C-c g} rather than the six strokes @kbd{@@ g r o u p}.
16677 (@samp{@@group} and its matching @samp{@@end group} are commands that
16678 keep all enclosed text together on one page; many multi-line examples
16679 in this book are surrounded by @samp{@@group @dots{} @@end group}.)
16681 @need 1250
16682 Here is the @code{texinfo-insert-@@group} function definition:
16684 @smallexample
16685 @group
16686 (defun texinfo-insert-@@group ()
16687   "Insert the string @@group in a Texinfo buffer."
16688   (interactive)
16689   (beginning-of-line)
16690   (insert "@@group\n"))
16691 @end group
16692 @end smallexample
16694 (Of course, I could have used Abbrev mode to save typing, rather than
16695 write a function to insert a word; but I prefer key strokes consistent
16696 with other Texinfo mode key bindings.)
16698 You will see numerous @code{define-key} expressions in
16699 @file{loaddefs.el} as well as in the various mode libraries, such as
16700 @file{cc-mode.el} and @file{lisp-mode.el}.
16702 @xref{Key Bindings, , Customizing Key Bindings, emacs, The GNU Emacs
16703 Manual}, and @ref{Keymaps, , Keymaps, elisp, The GNU Emacs Lisp
16704 Reference Manual}, for more information about keymaps.
16706 @node Loading Files, Autoload, Keymaps, Emacs Initialization
16707 @section Loading Files
16708 @cindex Loading files
16709 @c findex load
16711 Many people in the GNU Emacs community have written extensions to
16712 Emacs.  As time goes by, these extensions are often included in new
16713 releases.  For example, the Calendar and Diary packages are now part
16714 of the standard GNU Emacs, as is Calc.
16716 You can use a @code{load} command to evaluate a complete file and
16717 thereby install all the functions and variables in the file into Emacs.
16718 For example:
16720 @c (auto-compression-mode t)
16722 @smallexample
16723 (load "~/emacs/slowsplit")
16724 @end smallexample
16726 This evaluates, i.e.@: loads, the @file{slowsplit.el} file or if it
16727 exists, the faster, byte compiled @file{slowsplit.elc} file from the
16728 @file{emacs} sub-directory of your home directory.  The file contains
16729 the function @code{split-window-quietly}, which John Robinson wrote in
16730 1989.
16732 The @code{split-window-quietly} function splits a window with the
16733 minimum of redisplay.  I installed it in 1989 because it worked well
16734 with the slow 1200 baud terminals I was then using.  Nowadays, I only
16735 occasionally come across such a slow connection, but I continue to use
16736 the function because I like the way it leaves the bottom half of a
16737 buffer in the lower of the new windows and the top half in the upper
16738 window.
16740 @need 1250
16741 To replace the key binding for the default
16742 @code{split-window-vertically}, you must also unset that key and bind
16743 the keys to @code{split-window-quietly}, like this:
16745 @smallexample
16746 @group
16747 (global-unset-key "\C-x2")
16748 (global-set-key "\C-x2" 'split-window-quietly)
16749 @end group
16750 @end smallexample
16752 @vindex load-path
16753 If you load many extensions, as I do, then instead of specifying the
16754 exact location of the extension file, as shown above, you can specify
16755 that directory as part of Emacs' @code{load-path}.  Then, when Emacs
16756 loads a file, it will search that directory as well as its default
16757 list of directories.  (The default list is specified in @file{paths.h}
16758 when Emacs is built.)
16760 @need 1250
16761 The following command adds your @file{~/emacs} directory to the
16762 existing load path:
16764 @smallexample
16765 @group
16766 ;;; Emacs Load Path
16767 (setq load-path (cons "~/emacs" load-path))
16768 @end group
16769 @end smallexample
16771 Incidentally, @code{load-library} is an interactive interface to the
16772 @code{load} function.  The complete function looks like this:
16774 @findex load-library
16775 @smallexample
16776 @group
16777 (defun load-library (library)
16778   "Load the library named LIBRARY.
16779 This is an interface to the function `load'."
16780   (interactive "sLoad library: ")
16781   (load library))
16782 @end group
16783 @end smallexample
16785 The name of the function, @code{load-library}, comes from the use of
16786 `library' as a conventional synonym for `file'.  The source for the
16787 @code{load-library} command is in the @file{files.el} library.
16789 Another interactive command that does a slightly different job is
16790 @code{load-file}.  @xref{Lisp Libraries, , Libraries of Lisp Code for
16791 Emacs, emacs, The GNU Emacs Manual}, for information on the
16792 distinction between @code{load-library} and this command.
16794 @node Autoload, Simple Extension, Loading Files, Emacs Initialization
16795 @section Autoloading
16796 @findex autoload
16798 Instead of installing a function by loading the file that contains it,
16799 or by evaluating the function definition, you can make the function
16800 available but not actually install it until it is first called.  This
16801 is called @dfn{autoloading}.
16803 When you execute an autoloaded function, Emacs automatically evaluates
16804 the file that contains the definition, and then calls the function.
16806 Emacs starts quicker with autoloaded functions, since their libraries
16807 are not loaded right away; but you need to wait a moment when you
16808 first use such a function, while its containing file is evaluated.
16810 Rarely used functions are frequently autoloaded.  The
16811 @file{loaddefs.el} library contains hundreds of autoloaded functions,
16812 from @code{bookmark-set} to @code{wordstar-mode}.  Of course, you may
16813 come to use a `rare' function frequently.  When you do, you should
16814 load that function's file with a @code{load} expression in your
16815 @file{.emacs} file.
16817 In my @file{.emacs} file for Emacs version 21, I load 12 libraries
16818 that contain functions that would otherwise be autoloaded.  (Actually,
16819 it would have been better to include these files in my `dumped' Emacs
16820 when I built it, but I forgot.  @xref{Building Emacs, , Building
16821 Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the @file{INSTALL}
16822 file for more about dumping.)
16824 You may also want to include autoloaded expressions in your @file{.emacs}
16825 file.  @code{autoload} is a built-in function that takes up to five
16826 arguments, the final three of which are optional.  The first argument
16827 is the name of the function to be autoloaded; the second is the name
16828 of the file to be loaded.  The third argument is documentation for the
16829 function, and the fourth tells whether the function can be called
16830 interactively.  The fifth argument tells what type of
16831 object---@code{autoload} can handle a keymap or macro as well as a
16832 function (the default is a function).
16834 @need 800
16835 Here is a typical example:
16837 @smallexample
16838 @group
16839 (autoload 'html-helper-mode
16840   "html-helper-mode" "Edit HTML documents" t)
16841 @end group
16842 @end smallexample
16844 @noindent
16845 (@code{html-helper-mode} is an alternative to @code{html-mode}, which
16846 is a standard part of the distribution).
16848 @noindent
16849 This expression autoloads the @code{html-helper-mode} function.  It
16850 takes it from the @file{html-helper-mode.el} file (or from the byte
16851 compiled file @file{html-helper-mode.elc}, if it exists.)  The file
16852 must be located in a directory specified by @code{load-path}.  The
16853 documentation says that this is a mode to help you edit documents
16854 written in the HyperText Markup Language.  You can call this mode
16855 interactively by typing @kbd{M-x html-helper-mode}.  (You need to
16856 duplicate the function's regular documentation in the autoload
16857 expression because the regular function is not yet loaded, so its
16858 documentation is not available.)
16860 @xref{Autoload, , Autoload, elisp, The GNU Emacs Lisp Reference
16861 Manual}, for more information.
16863 @node Simple Extension, X11 Colors, Autoload, Emacs Initialization
16864 @section A Simple Extension: @code{line-to-top-of-window}
16865 @findex line-to-top-of-window
16866 @cindex Simple extension in @file{.emacs} file
16868 Here is a simple extension to Emacs that moves the line point is on to
16869 the top of the window.  I use this all the time, to make text easier
16870 to read.
16872 You can put the following code into a separate file and then load it
16873 from your @file{.emacs} file, or you can include it within your
16874 @file{.emacs} file.
16876 @need 1250
16877 Here is the definition:
16879 @smallexample
16880 @group
16881 ;;; Line to top of window;
16882 ;;; replace three keystroke sequence  C-u 0 C-l
16883 (defun line-to-top-of-window ()
16884   "Move the line point is on to top of window."
16885   (interactive)
16886   (recenter 0))
16887 @end group
16888 @end smallexample
16890 @need 1250
16891 Now for the keybinding.
16893 Nowadays, function keys as well as mouse button events and
16894 non-@sc{ascii} characters are written within square brackets, without
16895 quotation marks.  (In Emacs version 18 and before, you had to write
16896 different function key bindings for each different make of terminal.)
16898 I bind @code{line-to-top-of-window} to my @key{F6} function key like
16899 this:
16901 @smallexample
16902 (global-set-key [f6] 'line-to-top-of-window)
16903 @end smallexample
16905 For more information, see @ref{Init Rebinding, , Rebinding Keys in
16906 Your Init File, emacs, The GNU Emacs Manual}.
16908 @cindex Conditional 'twixt two versions of Emacs
16909 @cindex Version of Emacs, choosing
16910 @cindex Emacs version, choosing
16911 If you run two versions of GNU Emacs, such as versions 20 and 21, and
16912 use one @file{.emacs} file, you can select which code to evaluate with
16913 the following conditional:
16915 @smallexample
16916 @group
16917 (cond
16918  ((string-equal (number-to-string 20) (substring (emacs-version) 10 12))
16919   ;; evaluate version 20 code
16920   ( @dots{} ))
16921  ((string-equal (number-to-string 21) (substring (emacs-version) 10 12))
16922   ;; evaluate version 21 code
16923   ( @dots{} )))
16924 @end group
16925 @end smallexample
16927 For example, in contrast to version 20, version 21 blinks its cursor
16928 by default.  I hate such blinking, as well as some other features in
16929 version 21, so I placed the following in my @file{.emacs}
16930 file@footnote{When I start instances of Emacs that do not load my
16931 @file{.emacs} file or any site file, I also turn off blinking:
16933 @smallexample
16934 emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
16935 @end smallexample
16938 @smallexample
16939 @group
16940 (if (string-equal "21" (substring (emacs-version) 10 12))
16941     (progn
16942       (blink-cursor-mode 0)
16943       ;; Insert newline when you press `C-n' (next-line)
16944       ;; at the end of the buffer
16945       (setq next-line-add-newlines t)
16946 @end group
16947 @group
16948       ;; Turn on image viewing
16949       (auto-image-file-mode t)
16950 @end group
16951 @group
16952       ;; Turn on menu bar (this bar has text)
16953       ;; (Use numeric argument to turn on)
16954       (menu-bar-mode 1)
16955 @end group
16956 @group
16957       ;; Turn off tool bar (this bar has icons)
16958       ;; (Use numeric argument to turn on)
16959       (tool-bar-mode nil)
16960 @end group
16961 @group
16962       ;; Turn off tooltip mode for tool bar
16963       ;; (This mode causes icon explanations to pop up)
16964       ;; (Use numeric argument to turn on)
16965       (tooltip-mode nil)
16966       ;; If tooltips turned on, make tips appear promptly
16967       (setq tooltip-delay 0.1)  ; default is one second
16968        ))
16969 @end group
16970 @end smallexample
16972 @noindent
16973 (You will note that instead of typing @code{(number-to-string 21)}, I
16974 decided to save typing and wrote `21' as a string, @code{"21"}, rather
16975 than convert it from an integer to a string.  In this instance, this
16976 expression is better than the longer, but more general
16977 @code{(number-to-string 21)}.  However, if you do not know ahead of
16978 time what type of information will be returned, then the
16979 @code{number-to-string} function will be needed.)
16981 @node X11 Colors, Miscellaneous, Simple Extension, Emacs Initialization
16982 @section X11 Colors
16984 You can specify colors when you use Emacs with the MIT X Windowing
16985 system.
16987 I dislike the default colors and specify my own.
16989 @need 1250
16990 Here are the expressions in my @file{.emacs}
16991 file that set values:
16993 @smallexample
16994 @group
16995 ;; Set cursor color
16996 (set-cursor-color "white")
16998 ;; Set mouse color
16999 (set-mouse-color "white")
17001 ;; Set foreground and background
17002 (set-foreground-color "white")
17003 (set-background-color "darkblue")
17004 @end group
17006 @group
17007 ;;; Set highlighting colors for isearch and drag
17008 (set-face-foreground 'highlight "white")
17009 (set-face-background 'highlight "blue")
17010 @end group
17012 @group
17013 (set-face-foreground 'region "cyan")
17014 (set-face-background 'region "blue")
17015 @end group
17017 @group
17018 (set-face-foreground 'secondary-selection "skyblue")
17019 (set-face-background 'secondary-selection "darkblue")
17020 @end group
17022 @group
17023 ;; Set calendar highlighting colors
17024 (setq calendar-load-hook
17025       '(lambda ()
17026          (set-face-foreground 'diary-face   "skyblue")
17027          (set-face-background 'holiday-face "slate blue")
17028          (set-face-foreground 'holiday-face "white")))
17029 @end group
17030 @end smallexample
17032 The various shades of blue soothe my eye and prevent me from seeing
17033 the screen flicker.
17035 Alternatively, I could have set my specifications in various X
17036 initialization files.  For example, I could set the foreground,
17037 background, cursor, and pointer (i.e., mouse) colors in my
17038 @file{~/.Xresources} file like this:
17040 @smallexample
17041 @group
17042 Emacs*foreground:   white
17043 Emacs*background:   darkblue
17044 Emacs*cursorColor:  white
17045 Emacs*pointerColor: white
17046 @end group
17047 @end smallexample
17049 In any event, since it is not part of Emacs, I set the root color of
17050 my X window in my @file{~/.xinitrc} file, like this@footnote{I
17051 occasionally run more modern window managers, such as Sawfish with
17052 GNOME, Enlightenment, SCWM, or KDE; in those cases, I often specify an
17053 image rather than a plain color.}:
17055 @smallexample
17056 @group
17057 # I use TWM for window manager.
17058 xsetroot -solid Navy -fg white &
17059 @end group
17060 @end smallexample
17062 @node Miscellaneous, Mode Line, X11 Colors, Emacs Initialization
17063 @section Miscellaneous Settings for a @file{.emacs} File
17065 Here are a few miscellaneous settings:
17066 @sp 1
17068 @itemize @minus
17069 @item
17070 Set the shape and color of the mouse cursor:
17071 @smallexample
17072 @group
17073 ; Cursor shapes are defined in
17074 ; `/usr/include/X11/cursorfont.h';
17075 ; for example, the `target' cursor is number 128;
17076 ; the `top_left_arrow' cursor is number 132.
17077 @end group
17079 @group
17080 (let ((mpointer (x-get-resource "*mpointer"
17081                                 "*emacs*mpointer")))
17082   ;; If you have not set your mouse pointer
17083   ;;     then set it, otherwise leave as is:
17084   (if (eq mpointer nil)
17085       (setq mpointer "132")) ; top_left_arrow
17086 @end group
17087 @group
17088   (setq x-pointer-shape (string-to-int mpointer))
17089   (set-mouse-color "white"))
17090 @end group
17091 @end smallexample
17093 @item
17094 Convert @kbd{@key{CTL}-h} into @key{DEL} and @key{DEL}
17095 into @kbd{@key{CTL}-h}.@*
17096 (Some olders keyboards needed this, although I have not seen the
17097 problem recently.)
17099 @smallexample
17100 @group
17101 ;; Translate `C-h' to <DEL>.
17102 ; (keyboard-translate ?\C-h ?\C-?)
17104 ;; Translate <DEL> to `C-h'.
17105 (keyboard-translate ?\C-? ?\C-h)
17106 @end group
17107 @end smallexample
17109 @item Turn off a blinking cursor!
17111 @smallexample
17112 @group
17113 (if (fboundp 'blink-cursor-mode)
17114     (blink-cursor-mode -1))
17115 @end group
17116 @end smallexample
17118 @item  Ignore case when using `grep'@*
17119 @samp{-n}@w{  }   Prefix each line of output with line number@*
17120 @samp{-i}@w{  }   Ignore case distinctions@*
17121 @samp{-e}@w{  }   Protect patterns beginning with a hyphen character, @samp{-} 
17123 @smallexample
17124 (setq grep-command "grep  -n -i -e ")
17125 @end smallexample
17127 @item Automatically uncompress compressed files when visiting them
17129 @smallexample
17130 (load "uncompress")
17131 @end smallexample
17133 @item Find an existing buffer, even if it has a different name@*
17134 This avoids problems with symbolic links.
17136 @smallexample
17137 (setq find-file-existing-other-name t)
17138 @end smallexample
17140 @item Set your language environment and default input method
17142 @smallexample
17143 @group
17144 (set-language-environment "latin-1")
17145 ;; Remember you can enable or disable multilingual text input
17146 ;; with the @code{toggle-input-method'} (@kbd{C-\}) command
17147 (setq default-input-method "latin-1-prefix")
17148 @end group
17149 @end smallexample
17151 If you want to write with Chinese `GB' characters, set this instead:
17153 @smallexample
17154 @group
17155 (set-language-environment "Chinese-GB")
17156 (setq default-input-method "chinese-tonepy")
17157 @end group
17158 @end smallexample
17159 @end itemize
17161 @subsubheading Fixing Unpleasant Key Bindings
17162 @cindex Key bindings, fixing 
17163 @cindex Bindings, key, fixing unpleasant
17165 Some systems bind keys unpleasantly.  Sometimes, for example, the
17166 @key{CTL} key appears in an awkward spot rather than at the far left
17167 of the home row.
17169 Usually, when people fix these sorts of keybindings, they do not
17170 change their @file{~/.emacs} file.  Instead, they bind the proper keys
17171 on their consoles with the @code{loadkeys} or @code{install-keymap}
17172 commands in their boot script and then include @code{xmodmap} commands
17173 in their @file{.xinitrc} or @file{.Xsession} file for X Windows.
17175 @need 1250
17176 @noindent
17177 For a boot script:
17179 @smallexample
17180 @group
17181 loadkeys /usr/share/keymaps/i386/qwerty/emacs2.kmap.gz
17183 @exdent or
17185 install-keymap emacs2
17186 @end group
17187 @end smallexample
17189 @need 1250
17190 @noindent
17191 For a @file{.xinitrc} or @file{.Xsession} file when the @key{Caps
17192 Lock} key is at the far left of the home row:
17194 @smallexample
17195 @group
17196 # Bind the key labeled `Caps Lock' to `Control'
17197 # (Such a broken user interface suggests that keyboard manufacturers
17198 # think that computers are typewriters from 1885.)
17200 xmodmap -e "clear Lock"
17201 xmodmap -e "add Control = Caps_Lock"
17202 @end group
17203 @end smallexample
17205 @need 1250
17206 @noindent
17207 In a @file{.xinitrc} or @file{.Xsession} file, to convert an @key{ALT}
17208 key to a @key{META} key:
17210 @smallexample
17211 @group
17212 # Some ill designed keyboards have a key labeled ALT and no Meta
17213 xmodmap -e "keysym Alt_L = Meta_L Alt_L"
17214 @end group
17215 @end smallexample
17217 @node Mode Line,  , Miscellaneous, Emacs Initialization
17218 @section A Modified Mode Line
17219 @vindex default-mode-line-format
17220 @cindex Mode line format
17222 Finally, a feature I really like: a modified mode line.
17224 When I work over a network, I forget which machine I am using.  Also,
17225 I tend to I lose track of where I am, and which line point is on.
17227 So I reset my mode line to look like this:
17229 @smallexample
17230 -:-- foo.texi   rattlesnake:/home/bob/  Line 1  (Texinfo Fill) Top
17231 @end smallexample
17233 I am visiting a file called @file{foo.texi}, on my machine
17234 @file{rattlesnake} in my @file{/home/bob} buffer.  I am on line 1, in
17235 Texinfo mode, and am at the top of the buffer.
17237 @need 1200
17238 My @file{.emacs} file has a section that looks like this:
17240 @smallexample
17241 @group
17242 ;; Set a Mode Line that tells me which machine, which directory,
17243 ;; and which line I am on, plus the other customary information.
17244 (setq default-mode-line-format
17245  (quote
17246   (#("-" 0 1
17247      (help-echo
17248       "mouse-1: select window, mouse-2: delete others ..."))
17249    mode-line-mule-info
17250    mode-line-modified
17251    mode-line-frame-identification
17252    "    "
17253 @end group
17254 @group
17255    mode-line-buffer-identification
17256    "    "
17257    (:eval (substring
17258            (system-name) 0 (string-match "\\..+" (system-name))))
17259    ":"
17260    default-directory
17261    #(" " 0 1
17262      (help-echo
17263       "mouse-1: select window, mouse-2: delete others ..."))
17264    (line-number-mode " Line %l ")
17265    global-mode-string
17266 @end group
17267 @group
17268    #("   %[(" 0 6
17269      (help-echo
17270       "mouse-1: select window, mouse-2: delete others ..."))
17271    (:eval (mode-line-mode-name))
17272    mode-line-process
17273    minor-mode-alist
17274    #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
17275    ")%] "
17276    (-3 . "%P")
17277    ;;   "-%-"
17278    )))
17279 @end group
17280 @end smallexample
17282 @noindent
17283 Here, I redefine the default mode line.  Most of the parts are from
17284 the original; but I make a few changes.  I set the @emph{default} mode
17285 line format so as to permit various modes, such as Info, to override
17288 Many elements in the list are self-explanatory:
17289 @code{mode-line-modified} is a variable that tells whether the buffer
17290 has been modified, @code{mode-name} tells the name of the mode, and so
17291 on.  However, the format looks complicated because of two features we
17292 have not discussed.
17294 @cindex Properties, in mode line example
17295 The first string in the mode line is a dash or hyphen, @samp{-}.  In
17296 the old days, it would have been specified simply as @code{"-"}.  But
17297 nowadays, Emacs can add properties to a string, such as highlighting
17298 or, as in this case, a help feature.  If you place your mouse cursor
17299 over the hyphen, some help information appears (By default, you must
17300 wait one second before the information appears.  You can change that
17301 timing by changing the value of @code{tooltip-delay}.)
17303 @need 1000
17304 The new string format has a special syntax:
17306 @smallexample
17307 #("-" 0 1 (help-echo "mouse-1: select window, ..."))
17308 @end smallexample
17310 @noindent
17311 The @code{#(} begins a list.  The first element of the list is the
17312 string itself, just one @samp{-}.  The second and third
17313 elements specify the range over which the fourth element applies.  A
17314 range starts @emph{after} a character, so a zero means the range
17315 starts just before the first character; a 1 means that the range ends
17316 just after the first character.  The third element is the property for
17317 the range.  It consists of a property list,  a
17318 property name, in this case, @samp{help-echo}, followed by a value, in this
17319 case, a string.  The second, third, and fourth elements of this new
17320 string format can be repeated.
17322 @xref{Text Properties, , Text Properties, elisp, The GNU Emacs Lisp
17323 Reference Manual}, and see @ref{Mode Line Format, , Mode Line Format,
17324 elisp, The GNU Emacs Lisp Reference Manual}, for more information.
17326 @code{mode-line-buffer-identification}
17327 displays the current buffer name.  It is a list
17328 beginning @code{(#("%12b" 0 4 @dots{}}.
17329 The @code{#(} begins the list.
17331 The @samp{"%12b"} displays the current buffer name, using the
17332 @code{buffer-name} function with which we are familiar; the `12'
17333 specifies the maximum number of characters that will be displayed.
17334 When a name has fewer characters, whitespace is added to fill out to
17335 this number.  (Buffer names can and often should be longer than 12
17336 characters; this length works well in a typical 80 column wide
17337 window.)
17339 @code{:eval} is a new feature in GNU Emacs version 21.  It says to
17340 evaluate the following form and use the result as a string to display.
17341 In this case, the expression displays the first component of the full
17342 system name.  The end of the first component is a @samp{.} (`period'),
17343 so I use the @code{string-match} function to tell me the length of the
17344 first component.  The substring from the zeroth character to that
17345 length is the name of the machine.
17347 @need 1250
17348 This is the expression:
17350 @smallexample
17351 @group
17352 (:eval (substring
17353         (system-name) 0 (string-match "\\..+" (system-name))))
17354 @end group
17355 @end smallexample
17357 @samp{%[} and @samp{%]} cause a pair of square brackets
17358 to appear for each recursive editing level.  @samp{%n} says `Narrow'
17359 when narrowing is in effect.  @samp{%P} tells you the percentage of
17360 the buffer that is above the bottom of the window, or `Top', `Bottom',
17361 or `All'.  (A lower case @samp{p} tell you the percentage above the
17362 @emph{top} of the window.)  @samp{%-} inserts enough dashes to fill
17363 out the line.
17365 Remember, ``You don't have to like Emacs to like it'' --- your own
17366 Emacs can have different colors, different commands, and different
17367 keys than a default Emacs.
17369 On the other hand, if you want to bring up a plain `out of the box'
17370 Emacs, with no customization, type:
17372 @smallexample
17373 emacs -q
17374 @end smallexample
17376 @noindent
17377 This will start an Emacs that does @emph{not} load your
17378 @file{~/.emacs} initialization file.  A plain, default Emacs.  Nothing
17379 more.
17381 @node Debugging, Conclusion, Emacs Initialization, Top
17382 @chapter Debugging
17383 @cindex debugging
17385 GNU Emacs has two debuggers, @code{debug} and @code{edebug}.  The
17386 first is built into the internals of Emacs and is always with you;
17387 the second requires that you instrument a function before you can use it.
17389 Both debuggers are described extensively in @ref{Debugging, ,
17390 Debugging Lisp Programs, elisp, The GNU Emacs Lisp Reference Manual}.
17391 In this chapter, I will walk through a short example of each.
17393 @menu
17394 * debug::                       How to use the built-in debugger.
17395 * debug-on-entry::              Start debugging when you call a function.
17396 * debug-on-quit::               Start debugging when you quit with @kbd{C-g}.
17397 * edebug::                      How to use Edebug, a source level debugger.
17398 * Debugging Exercises::
17399 @end menu
17401 @node debug, debug-on-entry, Debugging, Debugging
17402 @section @code{debug}
17403 @findex debug
17405 Suppose you have written a function definition that is intended to
17406 return the sum of the numbers 1 through a given number.  (This is the
17407 @code{triangle} function discussed earlier.  @xref{Decrementing
17408 Example, , Example with Decrementing Counter}, for a discussion.)
17409 @c xref{Decrementing Loop,, Loop with a Decrementing Counter}, for a discussion.)
17411 However, your function definition has a bug.  You have mistyped
17412 @samp{1=} for @samp{1-}.  Here is the broken definition:
17414 @findex triangle-bugged
17415 @smallexample
17416 @group
17417 (defun triangle-bugged (number)
17418   "Return sum of numbers 1 through NUMBER inclusive."
17419   (let ((total 0))
17420     (while (> number 0)
17421       (setq total (+ total number))
17422       (setq number (1= number)))      ; @r{Error here.}
17423     total))
17424 @end group
17425 @end smallexample
17427 If you are reading this in Info, you can evaluate this definition in
17428 the normal fashion.  You will see @code{triangle-bugged} appear in the
17429 echo area.
17431 @need 1250
17432 Now evaluate the @code{triangle-bugged} function with an
17433 argument of 4:
17435 @smallexample
17436 (triangle-bugged 4)
17437 @end smallexample
17439 @noindent
17440 In GNU Emacs version 21, you will create and enter a
17441 @file{*Backtrace*} buffer that says:
17443 @noindent
17444 @smallexample
17445 @group
17446 ---------- Buffer: *Backtrace* ----------
17447 Debugger entered--Lisp error: (void-function 1=)
17448   (1= number)
17449   (setq number (1= number))
17450   (while (> number 0) (setq total (+ total number))
17451         (setq number (1= number)))
17452   (let ((total 0)) (while (> number 0) (setq total ...)
17453     (setq number ...)) total)
17454   triangle-bugged(4)
17455 @end group
17456 @group
17457   eval((triangle-bugged 4))
17458   eval-last-sexp-1(nil)
17459   eval-last-sexp(nil)
17460   call-interactively(eval-last-sexp)
17461 ---------- Buffer: *Backtrace* ----------
17462 @end group
17463 @end smallexample
17465 @noindent
17466 (I have reformatted this example slightly; the debugger does not fold
17467 long lines.  As usual, you can quit the debugger by typing @kbd{q} in
17468 the @file{*Backtrace*} buffer.)
17470 In practice, for a bug as simple as this, the `Lisp error' line will
17471 tell you what you need to know to correct the definition.  The
17472 function @code{1=} is `void'.
17474 @need 800
17475 In GNU Emacs 20 and before, you will see:
17477 @smallexample
17478 Symbol's function definition is void:@: 1=
17479 @end smallexample
17481 @noindent
17482 which has the same meaning as the @file{*Backtrace*} buffer line in
17483 version 21.
17485 However, suppose you are not quite certain what is going on?
17486 You can read the complete backtrace.
17488 In this case, you need to run GNU Emacs 21, which automatically starts
17489 the debugger that puts you in the @file{*Backtrace*} buffer; or else,
17490 you need to start the debugger manually as described below.
17492 Read the @file{*Backtrace*} buffer from the bottom up; it tells you
17493 what Emacs did that led to the error.  Emacs made an interactive call
17494 to @kbd{C-x C-e} (@code{eval-last-sexp}), which led to the evaluation
17495 of the @code{triangle-bugged} expression.  Each line above tells you
17496 what the Lisp interpreter evaluated next.
17498 @need 1250
17499 The third line from the top of the buffer is
17501 @smallexample
17502 (setq number (1= number))
17503 @end smallexample
17505 @noindent
17506 Emacs tried to evaluate this expression; in order to do so, it tried
17507 to evaluate the inner expression shown on the second line from the
17508 top:
17510 @smallexample
17511 (1= number)
17512 @end smallexample
17514 @need 1250
17515 @noindent
17516 This is where the error occurred; as the top line says:
17518 @smallexample
17519 Debugger entered--Lisp error: (void-function 1=)
17520 @end smallexample
17522 @noindent
17523 You can correct the mistake, re-evaluate the function definition, and
17524 then run your test again.
17526 @node debug-on-entry, debug-on-quit, debug, Debugging
17527 @section @code{debug-on-entry}
17528 @findex debug-on-entry
17530 GNU Emacs 21 starts the debugger automatically when your function has
17531 an error.  GNU Emacs version 20 and before did not; it simply
17532 presented you with an error message.  You had to start the debugger
17533 manually.
17535 You can start the debugger manually for all versions of Emacs; the
17536 advantage is that the debugger runs even if you do not have a bug in
17537 your code.  Sometimes your code will be free of bugs!
17539 You can enter the debugger when you call the function by calling
17540 @code{debug-on-entry}.
17542 @need 1250
17543 @noindent
17544 Type:
17546 @smallexample
17547 M-x debug-on-entry RET triangle-bugged RET
17548 @end smallexample
17550 @need 1250
17551 @noindent
17552 Now, evaluate the following:
17554 @smallexample
17555 (triangle-bugged 5)
17556 @end smallexample
17558 @noindent
17559 All versions of Emacs will create a @file{*Backtrace*} buffer and tell
17560 you that it is beginning to evaluate the @code{triangle-bugged}
17561 function:
17563 @smallexample
17564 @group
17565 ---------- Buffer: *Backtrace* ----------
17566 Debugger entered--entering a function:
17567 * triangle-bugged(5)
17568   eval((triangle-bugged 5))
17569 @end group
17570 @group
17571   eval-last-sexp-1(nil)
17572   eval-last-sexp(nil)
17573   call-interactively(eval-last-sexp)
17574 ---------- Buffer: *Backtrace* ----------
17575 @end group
17576 @end smallexample
17578 In the @file{*Backtrace*} buffer, type @kbd{d}.  Emacs will evaluate
17579 the first expression in @code{triangle-bugged}; the buffer will look
17580 like this:
17582 @smallexample
17583 @group
17584 ---------- Buffer: *Backtrace* ----------
17585 Debugger entered--beginning evaluation of function call form:
17586 * (let ((total 0)) (while (> number 0) (setq total ...)
17587         (setq number ...)) total)
17588 * triangle-bugged(5)
17589   eval((triangle-bugged 5))
17590 @end group
17591 @group
17592   eval-last-sexp-1(nil)
17593   eval-last-sexp(nil)
17594   call-interactively(eval-last-sexp)
17595 ---------- Buffer: *Backtrace* ----------
17596 @end group
17597 @end smallexample
17599 @noindent
17600 Now, type @kbd{d} again, eight times, slowly.  Each time you type
17601 @kbd{d}, Emacs will evaluate another expression in the function
17602 definition.
17604 @need 1750
17605 Eventually, the buffer will look like this:
17607 @smallexample
17608 @group
17609 ---------- Buffer: *Backtrace* ----------
17610 Debugger entered--beginning evaluation of function call form:
17611 * (setq number (1= number))
17612 * (while (> number 0) (setq total (+ total number))
17613         (setq number (1= number)))
17614 @group
17615 @end group
17616 * (let ((total 0)) (while (> number 0) (setq total ...)
17617         (setq number ...)) total)
17618 * triangle-bugged(5)
17619   eval((triangle-bugged 5))
17620 @group
17621 @end group
17622   eval-last-sexp-1(nil)
17623   eval-last-sexp(nil)
17624   call-interactively(eval-last-sexp)
17625 ---------- Buffer: *Backtrace* ----------
17626 @end group
17627 @end smallexample
17629 @need 1500
17630 @noindent
17631 Finally, after you type @kbd{d} two more times, Emacs will reach the
17632 error, and the top two lines of the @file{*Backtrace*} buffer will look
17633 like this:
17635 @smallexample
17636 @group
17637 ---------- Buffer: *Backtrace* ----------
17638 Debugger entered--Lisp error: (void-function 1=)
17639 * (1= number)
17640 @dots{}
17641 ---------- Buffer: *Backtrace* ----------
17642 @end group
17643 @end smallexample
17645 By typing @kbd{d}, you were able to step through the function.
17647 You can quit a @file{*Backtrace*} buffer by typing @kbd{q} in it; this
17648 quits the trace, but does not cancel @code{debug-on-entry}.
17650 @findex cancel-debug-on-entry
17651 To cancel the effect of @code{debug-on-entry}, call
17652 @code{cancel-debug-on-entry} and the name of the function, like this:
17654 @smallexample
17655 M-x cancel-debug-on-entry RET triangle-bugged RET
17656 @end smallexample
17658 @noindent
17659 (If you are reading this in Info, cancel @code{debug-on-entry} now.)
17661 @node debug-on-quit, edebug, debug-on-entry, Debugging
17662 @section @code{debug-on-quit} and @code{(debug)}
17664 In addition to setting @code{debug-on-error} or calling @code{debug-on-entry},
17665 there are two other ways to start @code{debug}.
17667 @findex debug-on-quit
17668 You can start @code{debug} whenever you type @kbd{C-g}
17669 (@code{keyboard-quit}) by setting the variable @code{debug-on-quit} to
17670 @code{t}.  This is useful for debugging infinite loops.
17672 @need 1500
17673 @cindex @code{(debug)} in code
17674 Or, you can insert a line that says @code{(debug)} into your code
17675 where you want the debugger to start, like this:
17677 @smallexample
17678 @group
17679 (defun triangle-bugged (number)
17680   "Return sum of numbers 1 through NUMBER inclusive."
17681   (let ((total 0))
17682     (while (> number 0)
17683       (setq total (+ total number))
17684       (debug)                         ; @r{Start debugger.}
17685       (setq number (1= number)))      ; @r{Error here.}
17686     total))
17687 @end group
17688 @end smallexample
17690 The @code{debug} function is described in detail in @ref{Debugger, ,
17691 The Lisp Debugger, elisp, The GNU Emacs Lisp Reference Manual}.
17693 @node edebug, Debugging Exercises, debug-on-quit, Debugging
17694 @section The @code{edebug} Source Level Debugger
17695 @cindex Source level debugger
17696 @findex edebug
17698 Edebug is a source level debugger.  Edebug normally displays the
17699 source of the code you are debugging, with an arrow at the left that
17700 shows which line you are currently executing.
17702 You can walk through the execution of a function, line by line, or run
17703 quickly until reaching a @dfn{breakpoint} where execution stops.
17705 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17706 Lisp Reference Manual}.
17708 @need 1250
17709 Here is a bugged function definition for @code{triangle-recursively}.
17710 @xref{Recursive triangle function, , Recursion in place of a counter},
17711 for a review of it.
17713 @smallexample
17714 @group
17715 (defun triangle-recursively-bugged (number)
17716   "Return sum of numbers 1 through NUMBER inclusive.
17717 Uses recursion."
17718   (if (= number 1)
17719       1
17720     (+ number
17721        (triangle-recursively-bugged
17722         (1= number)))))               ; @r{Error here.}
17723 @end group
17724 @end smallexample
17726 @noindent
17727 Normally, you would install this definition by positioning your cursor
17728 after the function's closing parenthesis and typing @kbd{C-x C-e}
17729 (@code{eval-last-sexp}) or else by positioning your cursor within the
17730 definition and typing @kbd{C-M-x} (@code{eval-defun}).  (By default,
17731 the @code{eval-defun} command works only in Emacs Lisp mode or in Lisp
17732 Interactive mode.)
17734 @need 1500
17735 However, to prepare this function definition for Edebug, you must
17736 first @dfn{instrument} the code using a different command.  You can do
17737 this by positioning your cursor within the definition and typing
17739 @smallexample
17740 M-x edebug-defun RET
17741 @end smallexample
17743 @noindent
17744 This will cause Emacs to load Edebug automatically if it is not
17745 already loaded, and properly instrument the function.
17747 After instrumenting the function, place your cursor after the
17748 following expression and type @kbd{C-x C-e} (@code{eval-last-sexp}):
17750 @smallexample
17751 (triangle-recursively-bugged 3)
17752 @end smallexample
17754 @noindent
17755 You will be jumped back to the source for
17756 @code{triangle-recursively-bugged} and the cursor positioned at the
17757 beginning of the @code{if} line of the function.  Also, you will see
17758 an arrowhead at the left hand side of that line.  The arrowhead marks
17759 the line where the function is executing.  (In the following examples,
17760 we show the arrowhead with @samp{=>}; in a windowing system, you may
17761 see the arrowhead as a solid triangle in the window `fringe'.)
17763 @smallexample
17764 =>@point{}(if (= number 1)
17765 @end smallexample
17767 @noindent
17768 @iftex
17769 In the example, the location of point is displayed with a star,
17770 @samp{@point{}} (in Info, it is displayed as @samp{-!-}).
17771 @end iftex
17772 @ifnottex
17773 In the example, the location of point is displayed as @samp{@point{}}
17774 (in a printed book, it is displayed with a five pointed star).
17775 @end ifnottex
17777 If you now press @key{SPC}, point will move to the next expression to
17778 be executed; the line will look like this:
17780 @smallexample
17781 =>(if @point{}(= number 1)
17782 @end smallexample
17784 @noindent
17785 As you continue to press @key{SPC}, point will move from expression to
17786 expression.  At the same time, whenever an expression returns a value,
17787 that value will be displayed in the echo area.  For example, after you
17788 move point past @code{number}, you will see the following:
17790 @smallexample
17791 Result: 3 = C-c
17792 @end smallexample
17794 @noindent
17795 This means the value of @code{number} is 3, which is @sc{ascii}
17796 `control-c' (the third letter of the alphabet, in case you need to
17797 know this information).
17799 You can continue moving through the code until you reach the line with
17800 the error.  Before evaluation, that line looks like this:
17802 @smallexample
17803 =>        @point{}(1= number)))))               ; @r{Error here.}
17804 @end smallexample
17806 @need 1250
17807 @noindent
17808 When you press @key{SPC} once again, you will produce an error message
17809 that says:
17811 @smallexample
17812 Symbol's function definition is void:@: 1=
17813 @end smallexample
17815 @noindent
17816 This is the bug.
17818 Press @kbd{q} to quit Edebug.
17820 To remove instrumentation from a function definition, simply
17821 re-evaluate it with a command that does not instrument it.
17822 For example, you could place your cursor after the definition's
17823 closing parenthesis and type @kbd{C-x C-e}.
17825 Edebug does a great deal more than walk with you through a function.
17826 You can set it so it races through on its own, stopping only at an
17827 error or at specified stopping points; you can cause it to display the
17828 changing values of various expressions; you can find out how many
17829 times a function is called, and more.
17831 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17832 Lisp Reference Manual}.
17834 @need 1500
17835 @node Debugging Exercises,  , edebug, Debugging
17836 @section Debugging Exercises
17838 @itemize @bullet
17839 @item
17840 Install the @code{count-words-region} function and then cause it to
17841 enter the built-in debugger when you call it.  Run the command on a
17842 region containing two words.  You will need to press @kbd{d} a
17843 remarkable number of times.  On your system, is a `hook' called after
17844 the command finishes?  (For information on hooks, see @ref{Command
17845 Overview, , Command Loop Overview, elisp, The GNU Emacs Lisp Reference
17846 Manual}.)
17848 @item
17849 Copy @code{count-words-region} into the @file{*scratch*} buffer,
17850 instrument the function for Edebug, and walk through its execution.
17851 The function does not need to have a bug, although you can introduce
17852 one if you wish.  If the function lacks a bug, the walk-through
17853 completes without problems.
17855 @item
17856 While running Edebug, type @kbd{?} to see a list of all the Edebug commands.
17857 (The @code{global-edebug-prefix} is usually @kbd{C-x X}, i.e.@:
17858 @kbd{@key{CTL}-x} followed by an upper case @kbd{X}; use this prefix
17859 for commands made outside of the Edebug debugging buffer.)
17861 @item
17862 In the Edebug debugging buffer, use the @kbd{p}
17863 (@code{edebug-bounce-point}) command to see where in the region the
17864 @code{count-words-region} is working.
17866 @item
17867 Move point to some spot further down function and then type the
17868 @kbd{h} (@code{edebug-goto-here}) command to jump to that location.
17870 @item
17871 Use the @kbd{t} (@code{edebug-trace-mode}) command to cause Edebug to
17872 walk through the function on its own; use an upper case @kbd{T} for
17873 @code{edebug-Trace-fast-mode}.
17875 @item
17876 Set a breakpoint, then run Edebug in Trace mode until it reaches the
17877 stopping point.
17878 @end itemize
17880 @node Conclusion, the-the, Debugging, Top
17881 @chapter Conclusion
17883 We have now reached the end of this Introduction.  You have now
17884 learned enough about programming in Emacs Lisp to set values, to write
17885 simple @file{.emacs} files for yourself and your friends, and write
17886 simple customizations and extensions to Emacs.
17888 This is a place to stop.  Or, if you wish, you can now go onward, and
17889 teach yourself.
17891 You have learned some of the basic nuts and bolts of programming.  But
17892 only some.  There are a great many more brackets and hinges that are
17893 easy to use that we have not touched.
17895 A path you can follow right now lies among the sources to GNU Emacs
17896 and in
17897 @ifnotinfo
17898 @cite{The GNU Emacs Lisp Reference Manual}.
17899 @end ifnotinfo
17900 @ifinfo
17901 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
17902 Emacs Lisp Reference Manual}.
17903 @end ifinfo
17905 The Emacs Lisp sources are an adventure.  When you read the sources and
17906 come across a function or expression that is unfamiliar, you need to
17907 figure out or find out what it does.
17909 Go to the Reference Manual.  It is a thorough, complete, and fairly
17910 easy-to-read description of Emacs Lisp.  It is written not only for
17911 experts, but for people who know what you know.  (The @cite{Reference
17912 Manual} comes with the standard GNU Emacs distribution.  Like this
17913 introduction, it comes as a Texinfo source file, so you can read it
17914 on-line and as a typeset, printed book.)
17916 Go to the other on-line help that is part of GNU Emacs: the on-line
17917 documentation for all functions, and @code{find-tags}, the program
17918 that takes you to sources.
17920 Here is an example of how I explore the sources.  Because of its name,
17921 @file{simple.el} is the file I looked at first, a long time ago.  As
17922 it happens some of the functions in @file{simple.el} are complicated,
17923 or at least look complicated at first sight.  The @code{open-line}
17924 function, for example, looks complicated.
17926 You may want to walk through this function slowly, as we did with the
17927 @code{forward-sentence} function.
17928 @ifnottex
17929 (@xref{forward-sentence}.)
17930 @end ifnottex
17931 @iftex
17932 (@xref{forward-sentence, , @code{forward-sentence}}.)
17933 @end iftex
17934 Or you may want to skip that function and look at another, such as
17935 @code{split-line}.  You don't need to read all the functions.
17936 According to @code{count-words-in-defun}, the @code{split-line}
17937 function contains 27 words and symbols.
17939 Even though it is short, @code{split-line} contains four expressions
17940 we have not studied: @code{skip-chars-forward}, @code{indent-to},
17941 @code{current-column} and @samp{?\n}.
17943 Consider the @code{skip-chars-forward} function.  (It is part of the
17944 function definition for @code{back-to-indentation}, which is shown in
17945 @ref{Review, , Review}.)
17947 In GNU Emacs, you can find out more about @code{skip-chars-forward} by
17948 typing @kbd{C-h f} (@code{describe-function}) and the name of the
17949 function.  This gives you the function documentation.
17951 You may be able to guess what is done by a well named function such as
17952 @code{indent-to}; or you can look it up, too.  Incidentally, the
17953 @code{describe-function} function itself is in @file{help.el}; it is
17954 one of those long, but decipherable functions.  You can look up
17955 @code{describe-function} using the @kbd{C-h f} command!
17957 In this instance, since the code is Lisp, the @file{*Help*} buffer
17958 contains the name of the library containing the function's source.
17959 You can put point over the name of the library and press the RET key,
17960 which in this situation is bound to @code{help-follow}, and be taken
17961 directly to the source, in the same way as @kbd{M-.}
17962 (@code{find-tag}).
17964 The definition for @code{describe-function} illustrates how to
17965 customize the @code{interactive} expression without using the standard
17966 character codes; and it shows how to create a temporary buffer.
17968 (The @code{indent-to} function is written in C rather than Emacs Lisp;
17969 it is a `built-in' function.  @code{help-follow} only provides you
17970 with the documentation of a built-in function; it does not take you to
17971 the source.  But @code{find-tag} will take you to the source, if
17972 properly set up.)
17974 You can look at a function's source using @code{find-tag}, which is
17975 bound to @kbd{M-.}  Finally, you can find out what the Reference
17976 Manual has to say by visiting the manual in Info, and typing @kbd{i}
17977 (@code{Info-index}) and the name of the function, or by looking up
17978 @code{skip-chars-forward} in the index to a printed copy of the
17979 manual.
17981 Similarly, you can find out what is meant by @samp{?\n}.  You can try
17982 using @code{Info-index} with @samp{?\n}.  It turns out that this
17983 action won't help; but don't give up.  If you search the index for
17984 @samp{\n} without the @samp{?}, you will be taken directly to the
17985 relevant section of the manual.  (@xref{Character Type, , Character
17986 Type, elisp, The GNU Emacs Lisp Reference Manual}.  @samp{?\n} stands
17987 for the newline character.)
17989 Other interesting source files include @file{paragraphs.el},
17990 @file{loaddefs.el}, and @file{loadup.el}.  The @file{paragraphs.el}
17991 file includes short, easily understood functions as well as longer
17992 ones.  The @file{loaddefs.el} file contains the many standard
17993 autoloads and many keymaps.  I have never looked at it all; only at
17994 parts.  @file{loadup.el} is the file that loads the standard parts of
17995 Emacs; it tells you a great deal about how Emacs is built.
17996 (@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
17997 Reference Manual}, for more about building.)
17999 As I said, you have learned some nuts and bolts; however, and very
18000 importantly, we have hardly touched major aspects of programming; I
18001 have said nothing about how to sort information, except to use the
18002 predefined @code{sort} function; I have said nothing about how to store
18003 information, except to use variables and lists; I have said nothing
18004 about how to write programs that write programs.  These are topics for
18005 another, and different kind of book, a different kind of learning.
18007 What you have done is learn enough for much practical work with GNU
18008 Emacs.  What you have done is get started.  This is the end of a
18009 beginning.
18011 @c ================ Appendix ================
18013 @node the-the, Kill Ring, Conclusion, Top
18014 @appendix The @code{the-the} Function
18015 @findex the-the
18016 @cindex Duplicated words function
18017 @cindex Words, duplicated
18019 Sometimes when you you write text, you duplicate words---as with ``you
18020 you'' near the beginning of this sentence.  I find that most
18021 frequently, I duplicate ``the'; hence, I call the function for
18022 detecting duplicated words, @code{the-the}.
18024 @need 1250
18025 As a first step, you could use the following regular expression to
18026 search for duplicates:
18028 @smallexample
18029 \\(\\w+[ \t\n]+\\)\\1
18030 @end smallexample
18032 @noindent
18033 This regexp matches one or more word-constituent characters followed
18034 by one or more spaces, tabs, or newlines.  However, it does not detect
18035 duplicated words on different lines, since the ending of the first
18036 word, the end of the line, is different from the ending of the second
18037 word, a space.  (For more information about regular expressions, see
18038 @ref{Regexp Search, , Regular Expression Searches}, as well as
18039 @ref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
18040 Manual}, and @ref{Regular Expressions, , Regular Expressions, elisp,
18041 The GNU Emacs Lisp Reference Manual}.)
18043 You might try searching just for duplicated word-constituent
18044 characters but that does not work since the pattern detects doubles
18045 such as the two occurrences of `th' in `with the'.
18047 Another possible regexp searches for word-constituent characters
18048 followed by non-word-constituent characters, reduplicated.  Here,
18049 @w{@samp{\\w+}} matches one or more word-constituent characters and
18050 @w{@samp{\\W*}} matches zero or more non-word-constituent characters.
18052 @smallexample
18053 \\(\\(\\w+\\)\\W*\\)\\1
18054 @end smallexample
18056 @noindent
18057 Again, not useful.
18059 Here is the pattern that I use.  It is not perfect, but good enough.
18060 @w{@samp{\\b}} matches the empty string, provided it is at the beginning
18061 or end of a word; @w{@samp{[^@@ \n\t]+}} matches one or more occurrences of
18062 any characters that are @emph{not} an @@-sign, space, newline, or tab.
18064 @smallexample
18065 \\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b
18066 @end smallexample
18068 One can write more complicated expressions, but I found that this
18069 expression is good enough, so I use it.
18071 Here is the @code{the-the} function, as I include it in my
18072 @file{.emacs} file, along with a handy global key binding:
18074 @smallexample
18075 @group
18076 (defun the-the ()
18077   "Search forward for for a duplicated word."
18078   (interactive)
18079   (message "Searching for for duplicated words ...")
18080   (push-mark)
18081 @end group
18082 @group
18083   ;; This regexp is not perfect
18084   ;; but is fairly good over all:
18085   (if (re-search-forward
18086        "\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
18087       (message "Found duplicated word.")
18088     (message "End of buffer")))
18089 @end group
18091 @group
18092 ;; Bind `the-the' to  C-c \
18093 (global-set-key "\C-c\\" 'the-the)
18094 @end group
18095 @end smallexample
18097 @sp 1
18098 Here is test text:
18100 @smallexample
18101 @group
18102 one two two three four five
18103 five six seven
18104 @end group
18105 @end smallexample
18107 You can substitute the other regular expressions shown above in the
18108 function definition and try each of them on this list.
18110 @node Kill Ring, Full Graph, the-the, Top
18111 @appendix Handling the Kill Ring
18112 @cindex Kill ring handling
18113 @cindex Handling the kill ring
18114 @cindex Ring, making a list like a
18116 The kill ring is a list that is transformed into a ring by the
18117 workings of the @code{rotate-yank-pointer} function.  The @code{yank}
18118 and @code{yank-pop} commands use the @code{rotate-yank-pointer}
18119 function.  This appendix describes the @code{rotate-yank-pointer}
18120 function as well as both the @code{yank} and the @code{yank-pop}
18121 commands.
18123 @menu
18124 * rotate-yank-pointer::         Move a pointer along a list and around.
18125 * yank::                        Paste a copy of a clipped element.
18126 * yank-pop::                    Insert first element pointed to.
18127 * ring file::
18128 @end menu
18130 @node rotate-yank-pointer, yank, Kill Ring, Kill Ring
18131 @comment  node-name,  next,  previous,  up
18132 @appendixsec The @code{rotate-yank-pointer} Function
18133 @findex rotate-yank-pointer
18135 The @code{rotate-yank-pointer} function changes the element in the kill
18136 ring to which @code{kill-ring-yank-pointer} points.  For example, it can
18137 change  @code{kill-ring-yank-pointer} from pointing to the second
18138 element to point to the third element.
18140 @need 800
18141 Here is the code for @code{rotate-yank-pointer}:
18143 @smallexample
18144 @group
18145 (defun rotate-yank-pointer (arg)
18146   "Rotate the yanking point in the kill ring."
18147   (interactive "p")
18148   (let ((length (length kill-ring)))
18149 @end group
18150 @group
18151     (if (zerop length)
18152         ;; @r{then-part}
18153         (error "Kill ring is empty")
18154 @end group
18155 @group
18156       ;; @r{else-part}
18157       (setq kill-ring-yank-pointer
18158             (nthcdr (% (+ arg
18159                           (- length
18160                              (length
18161                               kill-ring-yank-pointer)))
18162                        length)
18163                     kill-ring)))))
18164 @end group
18165 @end smallexample
18167 @menu
18168 * Understanding rotate-yk-ptr::
18169 * rotate-yk-ptr body::          The body of @code{rotate-yank-pointer}.
18170 @end menu
18172 @node Understanding rotate-yk-ptr, rotate-yk-ptr body, rotate-yank-pointer, rotate-yank-pointer
18173 @ifnottex
18174 @unnumberedsubsec @code{rotate-yank-pointer} in Outline
18175 @end ifnottex
18177 The @code{rotate-yank-pointer} function looks complex, but as usual,
18178 it can be understood by taking it apart piece by piece.  First look at
18179 it in skeletal form:
18181 @smallexample
18182 @group
18183 (defun rotate-yank-pointer (arg)
18184   "Rotate the yanking point in the kill ring."
18185   (interactive "p")
18186   (let @var{varlist}
18187     @var{body}@dots{})
18188 @end group
18189 @end smallexample
18191 This function takes one argument, called @code{arg}.  It has a brief
18192 documentation string; and it is interactive with a small @samp{p}, which
18193 means that the argument must be a processed prefix passed to the
18194 function as a number.
18196 The body of the function definition is a @code{let} expression, which
18197 itself has a body as well as a @var{varlist}.
18199 The @code{let} expression declares a variable that will be only usable
18200 within the bounds of this function.  This variable is called
18201 @code{length} and is bound to a value that is equal to the number of
18202 items in the kill ring.  This is done by using the function called
18203 @code{length}.  (Note that this function has the same name as the
18204 variable called @code{length}; but one use of the word is to name the
18205 function and the other is to name the variable.  The two are quite
18206 distinct.  Similarly, an English speaker will distinguish between the
18207 meanings of the word @samp{ship} when he says: "I must ship this package
18208 immediately." and "I must get aboard the ship immediately.")
18210 The function @code{length} tells the number of items there are in a list,
18211 so @code{(length kill-ring)} returns the number of items there are in the
18212 kill ring.
18214 @node rotate-yk-ptr body,  , Understanding rotate-yk-ptr, rotate-yank-pointer
18215 @comment  node-name,  next,  previous,  up
18216 @appendixsubsec The Body of @code{rotate-yank-pointer}
18218 The body of @code{rotate-yank-pointer} is a @code{let} expression and
18219 the body of the @code{let} expression is an @code{if} expression.
18221 The purpose of the @code{if} expression is to find out whether there is
18222 anything in the kill ring.  If the kill ring is empty, the @code{error}
18223 function stops evaluation of the function and prints a message in the
18224 echo area.  On the other hand, if the kill ring has something in it, the
18225 work of the function is done.
18227 Here is the if-part and then-part of the @code{if} expression:
18229 @findex zerop
18230 @findex error
18231 @smallexample
18232 @group
18233 (if (zerop length)                      ; @r{if-part}
18234     (error "Kill ring is empty")        ; @r{then-part}
18235   @dots{}
18236 @end group
18237 @end smallexample
18239 @noindent
18240 If there is not anything in the kill ring, its length must be zero and
18241 an error message sent to the user: @samp{Kill ring is empty}.  The
18242 @code{if} expression uses the function @code{zerop} which returns true
18243 if the value it is testing is zero.  When @code{zerop} tests true, the
18244 then-part of the @code{if} is evaluated.  The then-part is a list
18245 starting with the function @code{error}, which is a function that is
18246 similar to the @code{message} function (@pxref{message}), in that it
18247 prints a one-line message in the echo area.  However, in addition to
18248 printing a message, @code{error} also stops evaluation of the function
18249 within which it is embedded.  This means that the rest of the function
18250 will not be evaluated if the length of the kill ring is zero.
18252 @menu
18253 * Digression concerning error::  How to mislead humans, but not computers.
18254 * rotate-yk-ptr else-part::     The else-part of the @code{if} expression.
18255 * Remainder Function::          The remainder, @code{%}, function.
18256 * rotate-yk-ptr remainder::     Using @code{%} in @code{rotate-yank-pointer}.
18257 * kill-rng-yk-ptr last elt::    Pointing to the last element.
18258 @end menu
18260 @node Digression concerning error, rotate-yk-ptr else-part, rotate-yk-ptr body, rotate-yk-ptr body
18261 @ifnottex
18262 @unnumberedsubsubsec Digression about the word `error'
18263 @end ifnottex
18265 (In my opinion, it is slightly misleading, at least to humans, to use
18266 the term `error' as the name of the @code{error} function.  A better
18267 term would be `cancel'.  Strictly speaking, of course, you cannot
18268 point to, much less rotate a pointer to a list that has no length, so
18269 from the point of view of the computer, the word `error' is correct.
18270 But a human expects to attempt this sort of thing, if only to find out
18271 whether the kill ring is full or empty.  This is an act of
18272 exploration.
18274 (From the human point of view, the act of exploration and discovery is
18275 not necessarily an error, and therefore should not be labelled as one,
18276 even in the bowels of a computer.  As it is, the code in Emacs implies
18277 that a human who is acting virtuously, by exploring his or her
18278 environment, is making an error.  This is bad.  Even though the computer
18279 takes the same steps as it does when there is an `error', a term such as
18280 `cancel' would have a clearer connotation.)
18282 @node rotate-yk-ptr else-part, Remainder Function, Digression concerning error, rotate-yk-ptr body
18283 @unnumberedsubsubsec The else-part of the @code{if} expression
18285 The else-part of the @code{if} expression is dedicated to setting the
18286 value of @code{kill-ring-yank-pointer} when the kill ring has something
18287 in it.  The code looks like this:
18289 @smallexample
18290 @group
18291 (setq kill-ring-yank-pointer
18292       (nthcdr (% (+ arg
18293                     (- length
18294                        (length kill-ring-yank-pointer)))
18295                  length)
18296               kill-ring)))))
18297 @end group
18298 @end smallexample
18300 This needs some examination.  Clearly, @code{kill-ring-yank-pointer}
18301 is being set to be equal to some @sc{cdr} of the kill ring, using the
18302 @code{nthcdr} function that is described in an earlier section.
18303 (@xref{copy-region-as-kill}.)  But exactly how does it do this?
18305 Before looking at the details of the code let's first consider the
18306 purpose of the @code{rotate-yank-pointer} function.
18308 The @code{rotate-yank-pointer} function changes what
18309 @code{kill-ring-yank-pointer} points to.  If
18310 @code{kill-ring-yank-pointer} starts by pointing to the first element
18311 of a list, a call to @code{rotate-yank-pointer} causes it to point to
18312 the second element; and if @code{kill-ring-yank-pointer} points to the
18313 second element, a call to @code{rotate-yank-pointer} causes it to
18314 point to the third element.  (And if @code{rotate-yank-pointer} is
18315 given an argument greater than 1, it jumps the pointer that many
18316 elements.)
18318 The @code{rotate-yank-pointer} function uses @code{setq} to reset what
18319 the @code{kill-ring-yank-pointer} points to.  If
18320 @code{kill-ring-yank-pointer} points to the first element of the kill
18321 ring, then, in the simplest case, the @code{rotate-yank-pointer}
18322 function must cause it to point to the second element.  Put another
18323 way, @code{kill-ring-yank-pointer} must be reset to have a value equal
18324 to the @sc{cdr} of the kill ring.
18326 @need 1250
18327 That is, under these circumstances,
18329 @smallexample
18330 @group
18331 (setq kill-ring-yank-pointer
18332    ("some text" "a different piece of text" "yet more text"))
18334 (setq kill-ring
18335    ("some text" "a different piece of text" "yet more text"))
18336 @end group
18337 @end smallexample
18339 @need 800
18340 @noindent
18341 the code should do this:
18343 @smallexample
18344 (setq kill-ring-yank-pointer (cdr kill-ring))
18345 @end smallexample
18347 @need 1000
18348 @noindent
18349 As a result, the @code{kill-ring-yank-pointer} will look like this:
18351 @smallexample
18352 @group
18353 kill-ring-yank-pointer
18354      @result{} ("a different piece of text" "yet more text"))
18355 @end group
18356 @end smallexample
18358 The actual @code{setq} expression uses the @code{nthcdr} function to do
18359 the job.
18361 As we have seen before (@pxref{nthcdr}), the @code{nthcdr} function
18362 works by repeatedly taking the @sc{cdr} of a list---it takes the
18363 @sc{cdr} of the @sc{cdr} of the @sc{cdr} @dots{}
18365 @need 800
18366 The two following expressions produce the same result:
18368 @smallexample
18369 @group
18370 (setq kill-ring-yank-pointer (cdr kill-ring))
18372 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18373 @end group
18374 @end smallexample
18376 In the @code{rotate-yank-pointer} function, however, the first
18377 argument to @code{nthcdr} is a rather complex looking expression with
18378 lots of arithmetic inside of it:
18380 @smallexample
18381 @group
18382 (% (+ arg
18383       (- length
18384          (length kill-ring-yank-pointer)))
18385    length)
18386 @end group
18387 @end smallexample
18389 As usual, we need to look at the most deeply embedded expression first
18390 and then work our way towards the light.
18392 The most deeply embedded expression is @code{(length
18393 kill-ring-yank-pointer)}.  This finds the length of the current value of
18394 the @code{kill-ring-yank-pointer}.  (Remember that the
18395 @code{kill-ring-yank-pointer} is the name of a variable whose value is a
18396 list.)
18398 @need 800
18399 The measurement of the length is inside the expression:
18401 @smallexample
18402 (- length (length kill-ring-yank-pointer))
18403 @end smallexample
18405 @noindent
18406 In this expression, the first @code{length} is the variable that was
18407 assigned the length of the kill ring in the @code{let} statement at the
18408 beginning of the function.  (One might think this function would be
18409 clearer if the variable @code{length} were named
18410 @code{length-of-kill-ring} instead; but if you look at the text of the
18411 whole function, you will see that it is so short that naming this
18412 variable @code{length} is not a bother, unless you are pulling the
18413 function apart into very tiny pieces as we are doing here.)
18415 So the line @code{(- length (length kill-ring-yank-pointer))} tells the
18416 difference between the length of the kill ring and the length of the list
18417 whose name is @code{kill-ring-yank-pointer}.
18419 To see how all this fits into the @code{rotate-yank-pointer}
18420 function, let's begin by analyzing the case where
18421 @code{kill-ring-yank-pointer} points to the first element of the kill
18422 ring, just as @code{kill-ring} does, and see what happens when
18423 @code{rotate-yank-pointer} is called with an argument of 1.
18425 The variable @code{length} and the value of the expression
18426 @code{(length kill-ring-yank-pointer)} will be the same since the
18427 variable @code{length} is the length of the kill ring and the
18428 @code{kill-ring-yank-pointer} is pointing to the whole kill ring.
18429 Consequently, the value of
18431 @smallexample
18432 (- length (length kill-ring-yank-pointer))
18433 @end smallexample
18435 @noindent
18436 will be zero.  Since the value of @code{arg} will be 1, this will mean
18437 that the value of the whole expression
18439 @smallexample
18440 (+ arg (- length (length kill-ring-yank-pointer)))
18441 @end smallexample
18443 @noindent
18444 will be 1.
18446 @need 1200
18447 Consequently, the argument to @code{nthcdr} will be found as the result of
18448 the expression
18450 @smallexample
18451 (% 1 length)
18452 @end smallexample
18454 @node Remainder Function, rotate-yk-ptr remainder, rotate-yk-ptr else-part, rotate-yk-ptr body
18455 @unnumberedsubsubsec The @code{%} remainder function
18457 To understand @code{(% 1 length)}, we need to understand @code{%}.
18458 According to its documentation (which I just found by typing @kbd{C-h
18459 f @kbd{%} @key{RET}}), the @code{%} function returns the remainder of
18460 its first argument divided by its second argument.  For example, the
18461 remainder of 5 divided by 2 is 1.  (2 goes into 5 twice with a
18462 remainder of 1.)
18464 What surprises people who don't often do arithmetic is that a smaller
18465 number can be divided by a larger number and have a remainder.  In the
18466 example we just used, 5 was divided by 2.  We can reverse that and ask,
18467 what is the result of dividing 2 by 5?  If you can use fractions, the
18468 answer is obviously 2/5 or .4; but if, as here, you can only use whole
18469 numbers, the result has to be something different.  Clearly, 5 can go into
18470 2 zero times, but what of the remainder?  To see what the answer is,
18471 consider a case that has to be familiar from childhood:
18473 @itemize @bullet
18474 @item
18475 5 divided by 5 is 1 with a remainder of 0;
18477 @item
18478 6 divided by 5 is 1 with a remainder of 1;
18480 @item
18481 7 divided by 5 is 1 with a remainder of 2.
18483 @item
18484 Similarly, 10 divided by 5 is 2 with a remainder of 0;
18486 @item
18487 11 divided by 5 is 2 with a remainder of 1;
18489 @item
18490 12 divided by 5 is 1 with a remainder of 2.
18491 @end itemize
18493 @need 1250
18494 @noindent
18495 By considering the cases as parallel, we can see that
18497 @itemize @bullet
18498 @item
18499 zero divided by 5 must be zero with a remainder of zero;
18501 @item
18502 1 divided by 5 must be zero with a remainder of 1;
18504 @item
18505 2 divided by 5 must be zero with a remainder of 2;
18506 @end itemize
18508 @noindent
18509 and so on.
18511 @need 1250
18512 So, in this code, if the value of @code{length} is 5, then the result of
18513 evaluating
18515 @smallexample
18516 (% 1 5)
18517 @end smallexample
18519 @noindent
18520 is 1.  (I just checked this by placing the cursor after the expression
18521 and typing @kbd{C-x C-e}.  Indeed, 1 is printed in the echo area.)
18523 @need 2000
18524 @node rotate-yk-ptr remainder, kill-rng-yk-ptr last elt, Remainder Function, rotate-yk-ptr body
18525 @unnumberedsubsubsec Using @code{%} in @code{rotate-yank-pointer}
18527 When the @code{kill-ring-yank-pointer} points to the
18528 beginning of the kill ring, and the argument passed to
18529 @code{rotate-yank-pointer} is 1, the @code{%} expression returns 1:
18531 @smallexample
18532 @group
18533 (- length (length kill-ring-yank-pointer))
18534      @result{} 0
18535 @end group
18536 @end smallexample
18538 @need 1250
18539 @noindent
18540 therefore,
18542 @smallexample
18543 @group
18544 (+ arg (- length (length kill-ring-yank-pointer)))
18545      @result{} 1
18546 @end group
18547 @end smallexample
18549 @need 1250
18550 @noindent
18551 and consequently:
18553 @smallexample
18554 @group
18555 (% (+ arg (- length (length kill-ring-yank-pointer)))
18556    length)
18557      @result{} 1
18558 @end group
18559 @end smallexample
18561 @noindent
18562 regardless of the value of @code{length}.
18564 @need 1250
18565 @noindent
18566 As a result of this, the @code{setq kill-ring-yank-pointer} expression
18567 simplifies to:
18569 @smallexample
18570 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18571 @end smallexample
18573 @noindent
18574 What it does is now easy to understand.  Instead of pointing as it did
18575 to the first element of the kill ring, the
18576 @code{kill-ring-yank-pointer} is set to point to the second element.
18578 Clearly, if the argument passed to @code{rotate-yank-pointer} is two, then
18579 the @code{kill-ring-yank-pointer} is set to @code{(nthcdr 2 kill-ring)};
18580 and so on for different values of the argument.
18582 Similarly, if the @code{kill-ring-yank-pointer} starts out pointing to
18583 the second element of the kill ring, its length is shorter than the
18584 length of the kill ring by 1, so the computation of the remainder is
18585 based on the expression @code{(% (+ arg 1) length)}.  This means that
18586 the @code{kill-ring-yank-pointer} is moved from the second element of
18587 the kill ring to the third element if the argument passed to
18588 @code{rotate-yank-pointer} is 1.
18590 @node kill-rng-yk-ptr last elt,  , rotate-yk-ptr remainder, rotate-yk-ptr body
18591 @unnumberedsubsubsec Pointing to the last element
18593 The final question is, what happens if the @code{kill-ring-yank-pointer}
18594 is set to the @emph{last} element of the kill ring?  Will a call to
18595 @code{rotate-yank-pointer} mean that nothing more can be taken from the
18596 kill ring?  The answer is no.  What happens is different and useful.
18597 The @code{kill-ring-yank-pointer} is set to point to the beginning of
18598 the kill ring instead.
18600 Let's see how this works by looking at the code, assuming the length of the
18601 kill ring is 5 and the argument passed to @code{rotate-yank-pointer} is 1.
18602 When the @code{kill-ring-yank-pointer} points to the last element of
18603 the kill ring, its length is 1.  The code looks like this:
18605 @smallexample
18606 (% (+ arg (- length (length kill-ring-yank-pointer))) length)
18607 @end smallexample
18609 @need 1250
18610 When the variables are replaced by their numeric values, the expression
18611 looks like this:
18613 @smallexample
18614 (% (+ 1 (- 5 1)) 5)
18615 @end smallexample
18617 @noindent
18618 This expression can be evaluated by looking at the most embedded inner
18619 expression first and working outwards:  The value of @code{(- 5 1)} is 4;
18620 the sum of @code{(+ 1 4)} is 5; and the remainder of dividing 5 by 5 is
18621 zero.  So what @code{rotate-yank-pointer} will do is
18623 @smallexample
18624 (setq kill-ring-yank-pointer (nthcdr 0 kill-ring))
18625 @end smallexample
18627 @noindent
18628 which will set the @code{kill-ring-yank-pointer} to point to the beginning
18629 of the kill ring.
18631 So what happens with successive calls to @code{rotate-yank-pointer} is that
18632 it moves the @code{kill-ring-yank-pointer} from element to element in the
18633 kill ring until it reaches the end; then it jumps back to the beginning.
18634 And this is why the kill ring is called a ring, since by jumping back to
18635 the beginning, it is as if the list has no end!  (And what is a ring, but
18636 an entity with no end?)
18638 @node yank, yank-pop, rotate-yank-pointer, Kill Ring
18639 @comment  node-name,  next,  previous,  up
18640 @appendixsec @code{yank}
18641 @findex yank
18643 After learning about @code{rotate-yank-pointer}, the code for the
18644 @code{yank} function is almost easy.  It has only one tricky part, which is
18645 the computation of the argument to be passed to @code{rotate-yank-pointer}.
18647 @need 1250
18648 The code looks like this:
18650 @smallexample
18651 @group
18652 (defun yank (&optional arg)
18653   "Reinsert the last stretch of killed text.
18654 More precisely, reinsert the stretch of killed text most
18655 recently killed OR yanked.
18656 With just C-U as argument, same but put point in front
18657 (and mark at end).  With argument n, reinsert the nth
18658 most recently killed stretch of killed text.
18659 See also the command \\[yank-pop]."
18660 @end group
18661 @group
18663   (interactive "*P")
18664   (rotate-yank-pointer (if (listp arg) 0
18665                          (if (eq arg '-) -1
18666                            (1- arg))))
18667   (push-mark (point))
18668   (insert (car kill-ring-yank-pointer))
18669   (if (consp arg)
18670       (exchange-point-and-mark)))
18671 @end group
18672 @end smallexample
18674 Glancing over this code, we can understand the last few lines readily
18675 enough.  The mark is pushed, that is, remembered; then the first element
18676 (the @sc{car}) of what the @code{kill-ring-yank-pointer} points to is
18677 inserted; and then, if the argument passed the function is a
18678 @code{cons}, point and mark are exchanged so the point is put in the
18679 front of the inserted text rather than at the end.  This option is
18680 explained in the documentation.  The function itself is interactive with
18681 @code{"*P"}.  This means it will not work on a read-only buffer, and that
18682 the unprocessed prefix argument is passed to the function.
18684 @menu
18685 * rotate-yk-ptr arg::           Pass the argument to @code{rotate-yank-pointer}.
18686 * rotate-yk-ptr negative arg::  Pass a negative argument.
18687 @end menu
18689 @node rotate-yk-ptr arg, rotate-yk-ptr negative arg, yank, yank
18690 @unnumberedsubsubsec Passing the argument
18692 The hard part of @code{yank} is understanding the computation that
18693 determines the value of the argument passed to
18694 @code{rotate-yank-pointer}.  Fortunately, it is not so difficult as it
18695 looks at first sight.
18697 What happens is that the result of evaluating one or both of the
18698 @code{if} expressions will be a number and that number will be the
18699 argument passed to @code{rotate-yank-pointer}.
18701 @need 1250
18702 Laid out with comments, the code looks like this:
18704 @smallexample
18705 @group
18706 (if (listp arg)                         ; @r{if-part}
18707     0                                   ; @r{then-part}
18708   (if (eq arg '-)                       ; @r{else-part, inner if}
18709       -1                                ; @r{inner if's then-part}
18710     (1- arg))))                         ; @r{inner if's else-part}
18711 @end group
18712 @end smallexample
18714 @noindent
18715 This code consists of two @code{if} expression, one the else-part of
18716 the other.
18718 The first or outer @code{if} expression tests whether the argument
18719 passed to @code{yank} is a list.  Oddly enough, this will be true if
18720 @code{yank} is called without an argument---because then it will be
18721 passed the value of @code{nil} for the optional argument and an
18722 evaluation of @code{(listp nil)} returns true!  So, if no argument is
18723 passed to @code{yank}, the argument passed to
18724 @code{rotate-yank-pointer} inside of @code{yank} is zero.  This means
18725 the pointer is not moved and the first element to which
18726 @code{kill-ring-yank-pointer} points is inserted, as we expect.
18727 Similarly, if the argument for @code{yank} is @kbd{C-u}, this will be
18728 read as a list, so again, a zero will be passed to
18729 @code{rotate-yank-pointer}.  (@kbd{C-u} produces an unprocessed prefix
18730 argument of @code{(4)}, which is a list of one element.)  At the same
18731 time, later in the function, this argument will be read as a
18732 @code{cons} so point will be put in the front and mark at the end of
18733 the insertion.  (The @code{P} argument to @code{interactive} is
18734 designed to provide these values for the case when an optional
18735 argument is not provided or when it is @kbd{C-u}.)
18737 The then-part of the outer @code{if} expression handles the case when
18738 there is no argument or when it is @kbd{C-u}.  The else-part handles the
18739 other situations.  The else-part is itself another @code{if} expression.
18741 The inner @code{if} expression tests whether the argument is a minus
18742 sign.  (This is done by pressing the @key{META} and @kbd{-} keys at the
18743 same time, or the @key{ESC} key and then the @kbd{-} key).  In this
18744 case, the @code{rotate-yank-pointer} function is passed @kbd{-1} as an
18745 argument.  This moves the @code{kill-ring-yank-pointer} backwards, which
18746 is what is desired.
18748 If the true-or-false-test of the inner @code{if} expression is false
18749 (that is, if the argument is not a minus sign), the else-part of the
18750 expression is evaluated.  This is the expression @code{(1- arg)}.
18751 Because of the two @code{if} expressions, it will only occur when the
18752 argument is a positive number or when it is a negative number (not
18753 just a minus sign on its own).  What @code{(1- arg)} does is decrement
18754 the number and return it.  (The @code{1-} function subtracts one from
18755 its argument.)  This means that if the argument to
18756 @code{rotate-yank-pointer} is 1, it is reduced to zero, which means
18757 the first element to which @code{kill-ring-yank-pointer} points is
18758 yanked back, as you would expect.
18760 @node rotate-yk-ptr negative arg,  , rotate-yk-ptr arg, yank
18761 @unnumberedsubsubsec Passing a negative argument
18763 Finally, the question arises, what happens if either the remainder
18764 function, @code{%}, or the @code{nthcdr} function is passed a negative
18765 argument, as they quite well may?
18767 The answers can be found by a quick test.  When @code{(% -1 5)} is
18768 evaluated, a negative number is returned; and if @code{nthcdr} is
18769 called with a negative number, it returns the same value as if it were
18770 called with a first argument of zero.  This can be seen by evaluating
18771 the following code.
18773 Here the @samp{@result{}} points to the result of evaluating the code
18774 preceding it.  This was done by positioning the cursor after the code
18775 and typing @kbd{C-x C-e} (@code{eval-last-sexp}) in the usual fashion.
18776 You can do this if you are reading this in Info inside of GNU Emacs.
18778 @smallexample
18779 @group
18780 (% -1 5)
18781      @result{} -1
18782 @end group
18784 @group
18785 (setq animals '(cats dogs elephants))
18786      @result{} (cats dogs elephants)
18787 @end group
18789 @group
18790 (nthcdr 1 animals)
18791      @result{} (dogs elephants)
18792 @end group
18794 @group
18795 (nthcdr 0 animals)
18796      @result{} (cats dogs elephants)
18797 @end group
18799 @group
18800 (nthcdr -1 animals)
18801      @result{} (cats dogs elephants)
18802 @end group
18803 @end smallexample
18805 So, if a minus sign or a negative number is passed to @code{yank}, the
18806 @code{kill-ring-yank-point} is rotated backwards until it reaches the
18807 beginning of the list.  Then it stays there.  Unlike the other case,
18808 when it jumps from the end of the list to the beginning of the list,
18809 making a ring, it stops.  This makes sense.  You often want to get back
18810 to the most recently clipped out piece of text, but you don't usually
18811 want to insert text from as many as thirty kill commands ago.  So you
18812 need to work through the ring to get to the end, but won't cycle around
18813 it inadvertently if you are trying to come back to the beginning.
18815 Incidentally, any number passed to @code{yank} with a minus sign
18816 preceding it will be treated as @minus{}1.  This is evidently a
18817 simplification for writing the program.  You don't need to jump back
18818 towards the beginning of the kill ring more than one place at a time
18819 and doing this is easier than writing a function to determine the
18820 magnitude of the number that follows the minus sign.
18822 @node yank-pop, ring file, yank, Kill Ring
18823 @comment  node-name,  next,  previous,  up
18824 @appendixsec @code{yank-pop}
18825 @findex yank-pop
18827 After understanding @code{yank}, the @code{yank-pop} function is easy.
18828 Leaving out the documentation to save space, it looks like this:
18830 @smallexample
18831 @group
18832 (defun yank-pop (arg)
18833   (interactive "*p")
18834   (if (not (eq last-command 'yank))
18835       (error "Previous command was not a yank"))
18836 @end group
18837 @group
18838   (setq this-command 'yank)
18839   (let ((before (< (point) (mark))))
18840     (delete-region (point) (mark))
18841     (rotate-yank-pointer arg)
18842 @end group
18843 @group
18844     (set-mark (point))
18845     (insert (car kill-ring-yank-pointer))
18846     (if before (exchange-point-and-mark))))
18847 @end group
18848 @end smallexample
18850 The function is interactive with a small @samp{p} so the prefix
18851 argument is processed and passed to the function.  The command can
18852 only be used after a previous yank; otherwise an error message is
18853 sent.  This check uses the variable @code{last-command} which is
18854 discussed elsewhere.  (@xref{copy-region-as-kill}.)
18856 The @code{let} clause sets the variable @code{before} to true or false
18857 depending whether point is before or after mark and then the region
18858 between point and mark is deleted.  This is the region that was just
18859 inserted by the previous yank and it is this text that will be
18860 replaced.  Next the @code{kill-ring-yank-pointer} is rotated so that
18861 the previously inserted text is not reinserted yet again.  Mark is set
18862 at the beginning of the place the new text will be inserted and then
18863 the first element to which @code{kill-ring-yank-pointer} points is
18864 inserted.  This leaves point after the new text.  If in the previous
18865 yank, point was left before the inserted text, point and mark are now
18866 exchanged so point is again left in front of the newly inserted text.
18867 That is all there is to it!
18869 @node ring file,  , yank-pop, Kill Ring
18870 @comment  node-name,  next,  previous,  up
18871 @appendixsec The @file{ring.el} File
18872 @cindex @file{ring.el} file
18874 Interestingly, GNU Emacs posses a file called @file{ring.el} that
18875 provides many of the features we just discussed.  But functions such
18876 as @code{kill-ring-yank-pointer} do not use this library, possibly
18877 because they were written earlier.
18879 @node Full Graph, Free Software and Free Manuals, Kill Ring, Top
18880 @appendix A Graph with Labelled Axes
18882 Printed axes help you understand a graph.  They convey scale.  In an
18883 earlier chapter (@pxref{Readying a Graph, ,  Readying a Graph}), we
18884 wrote the code to print the body of a graph.  Here we write the code
18885 for printing and labelling vertical and horizontal axes, along with the
18886 body itself.
18888 @menu
18889 * Labelled Example::
18890 * print-graph Varlist::         @code{let} expression in @code{print-graph}.
18891 * print-Y-axis::                Print a label for the vertical axis.
18892 * print-X-axis::                Print a horizontal label.
18893 * Print Whole Graph::           The function to print a complete graph.
18894 @end menu
18896 @node Labelled Example, print-graph Varlist, Full Graph, Full Graph
18897 @ifnottex
18898 @unnumberedsec Labelled Example Graph
18899 @end ifnottex
18901 Since insertions fill a buffer to the right and below point, the new
18902 graph printing function should first print the Y or vertical axis,
18903 then the body of the graph, and finally the X or horizontal axis.
18904 This sequence lays out for us the contents of the function:
18906 @enumerate
18907 @item
18908 Set up code.
18910 @item
18911 Print Y axis.
18913 @item
18914 Print body of graph.
18916 @item
18917 Print X axis.
18918 @end enumerate
18920 @need 800
18921 Here is an example of how a finished graph should look:
18923 @smallexample
18924 @group
18925     10 -
18926                   *
18927                   *  *
18928                   *  **
18929                   *  ***
18930      5 -      *   *******
18931             * *** *******
18932             *************
18933           ***************
18934      1 - ****************
18935          |   |    |    |
18936          1   5   10   15
18937 @end group
18938 @end smallexample
18940 @noindent
18941 In this graph, both the vertical and the horizontal axes are labelled
18942 with numbers.  However, in some graphs, the horizontal axis is time
18943 and would be better labelled with months, like this:
18945 @smallexample
18946 @group
18947      5 -      *
18948             * ** *
18949             *******
18950           ********** **
18951      1 - **************
18952          |    ^      |
18953          Jan  June   Jan
18954 @end group
18955 @end smallexample
18957 Indeed, with a little thought, we can easily come up with a variety of
18958 vertical and horizontal labelling schemes.  Our task could become
18959 complicated.  But complications breed confusion.  Rather than permit
18960 this, it is better choose a simple labelling scheme for our first
18961 effort, and to modify or replace it later.
18963 @need 1200
18964 These considerations suggest the following outline for the
18965 @code{print-graph} function:
18967 @smallexample
18968 @group
18969 (defun print-graph (numbers-list)
18970   "@var{documentation}@dots{}"
18971   (let ((height  @dots{}
18972         @dots{}))
18973 @end group
18974 @group
18975     (print-Y-axis height @dots{} )
18976     (graph-body-print numbers-list)
18977     (print-X-axis @dots{} )))
18978 @end group
18979 @end smallexample
18981 We can work on each part of the @code{print-graph} function definition
18982 in turn.
18984 @node print-graph Varlist, print-Y-axis, Labelled Example, Full Graph
18985 @comment  node-name,  next,  previous,  up
18986 @appendixsec The @code{print-graph} Varlist
18987 @cindex @code{print-graph} varlist
18989 In writing the @code{print-graph} function, the first task is to write
18990 the varlist in the @code{let} expression.  (We will leave aside for the
18991 moment any thoughts about making the function interactive or about the
18992 contents of its documentation string.)
18994 The varlist should set several values.  Clearly, the top of the label
18995 for the vertical axis must be at least the height of the graph, which
18996 means that we must obtain this information here.  Note that the
18997 @code{print-graph-body} function also requires this information.  There
18998 is no reason to calculate the height of the graph in two different
18999 places, so we should change @code{print-graph-body} from the way we
19000 defined it earlier to take advantage of the calculation.
19002 Similarly, both the function for printing the X axis labels and the
19003 @code{print-graph-body} function need to learn the value of the width of
19004 each symbol.  We can perform the calculation here and change the
19005 definition for @code{print-graph-body} from the way we defined it in the
19006 previous chapter.
19008 The length of the label for the horizontal axis must be at least as long
19009 as the graph.  However, this information is used only in the function
19010 that prints the horizontal axis, so it does not need to be calculated here.
19012 These thoughts lead us directly to the following form for the varlist
19013 in the @code{let} for @code{print-graph}:
19015 @smallexample
19016 @group
19017 (let ((height (apply 'max numbers-list)) ; @r{First version.}
19018       (symbol-width (length graph-blank)))
19019 @end group
19020 @end smallexample
19022 @noindent
19023 As we shall see, this expression is not quite right.
19025 @need 2000
19026 @node print-Y-axis, print-X-axis, print-graph Varlist, Full Graph
19027 @comment  node-name,  next,  previous,  up
19028 @appendixsec The @code{print-Y-axis} Function
19029 @cindex Axis, print vertical
19030 @cindex Y axis printing
19031 @cindex Vertical axis printing
19032 @cindex Print vertical axis
19034 The job of the @code{print-Y-axis} function is to print a label for
19035 the vertical axis that looks like this:
19037 @smallexample
19038 @group
19039     10 -
19044      5 -
19048      1 -
19049 @end group
19050 @end smallexample
19052 @noindent
19053 The function should be passed the height of the graph, and then should
19054 construct and insert the appropriate numbers and marks.
19056 It is easy enough to see in the figure what the Y axis label should
19057 look like; but to say in words, and then to write a function
19058 definition to do the job is another matter.  It is not quite true to
19059 say that we want a number and a tic every five lines: there are only
19060 three lines between the @samp{1} and the @samp{5} (lines 2, 3, and 4),
19061 but four lines between the @samp{5} and the @samp{10} (lines 6, 7, 8,
19062 and 9).  It is better to say that we want a number and a tic mark on
19063 the base line (number 1) and then that we want a number and a tic on
19064 the fifth line from the bottom and on every line that is a multiple of
19065 five.
19067 @menu
19068 * Height of label::             What height for the Y axis?
19069 * Compute a Remainder::         How to compute the remainder of a division.
19070 * Y Axis Element::              Construct a line for the Y axis.
19071 * Y-axis-column::               Generate a list of Y axis labels.
19072 * print-Y-axis Penultimate::    A not quite final version.
19073 @end menu
19075 @node Height of label, Compute a Remainder, print-Y-axis, print-Y-axis
19076 @ifnottex
19077 @unnumberedsubsec What height should the label be?
19078 @end ifnottex
19080 The next issue is what height the label should be?  Suppose the maximum
19081 height of tallest column of the graph is seven.  Should the highest
19082 label on the Y axis be @samp{5 -}, and should the graph stick up above
19083 the label?  Or should the highest label be @samp{7 -}, and mark the peak
19084 of the graph?  Or should the highest label be @code{10 -}, which is a
19085 multiple of five, and be higher than the topmost value of the graph?
19087 The latter form is preferred.  Most graphs are drawn within rectangles
19088 whose sides are an integral number of steps long---5, 10, 15, and so
19089 on for a step distance of five.  But as soon as we decide to use a
19090 step height for the vertical axis, we discover that the simple
19091 expression in the varlist for computing the height is wrong.  The
19092 expression is @code{(apply 'max numbers-list)}.  This returns the
19093 precise height, not the maximum height plus whatever is necessary to
19094 round up to the nearest multiple of five.  A more complex expression
19095 is required.
19097 As usual in cases like this, a complex problem becomes simpler if it is
19098 divided into several smaller problems.
19100 First, consider the case when the highest value of the graph is an
19101 integral multiple of five---when it is 5, 10, 15, or some higher
19102 multiple of five.  We can use this value as the Y axis height.
19104 A fairly simply way to determine whether a number is a multiple of
19105 five is to divide it by five and see if the division results in a
19106 remainder.  If there is no remainder, the number is a multiple of
19107 five.  Thus, seven divided by five has a remainder of two, and seven
19108 is not an integral multiple of five.  Put in slightly different
19109 language, more reminiscent of the classroom, five goes into seven
19110 once, with a remainder of two.  However, five goes into ten twice,
19111 with no remainder: ten is an integral multiple of five.
19113 @node Compute a Remainder, Y Axis Element, Height of label, print-Y-axis
19114 @appendixsubsec Side Trip: Compute a Remainder
19116 @findex % @r{(remainder function)}
19117 @cindex Remainder function, @code{%}
19118 In Lisp, the function for computing a remainder is @code{%}.  The
19119 function returns the remainder of its first argument divided by its
19120 second argument.  As it happens, @code{%} is a function in Emacs Lisp
19121 that you cannot discover using @code{apropos}: you find nothing if you
19122 type @kbd{M-x apropos @key{RET} remainder @key{RET}}.  The only way to
19123 learn of the existence of @code{%} is to read about it in a book such
19124 as this or in the Emacs Lisp sources.  The @code{%} function is used
19125 in the code for @code{rotate-yank-pointer}, which is described in an
19126 appendix.  (@xref{rotate-yk-ptr body, , The Body of
19127 @code{rotate-yank-pointer}}.)
19129 You can try the @code{%} function by evaluating the following two
19130 expressions:
19132 @smallexample
19133 @group
19134 (% 7 5)
19136 (% 10 5)
19137 @end group
19138 @end smallexample
19140 @noindent
19141 The first expression returns 2 and the second expression returns 0.
19143 To test whether the returned value is zero or some other number, we
19144 can use the @code{zerop} function.  This function returns @code{t} if
19145 its argument, which must be a number, is zero.
19147 @smallexample
19148 @group
19149 (zerop (% 7 5))
19150      @result{} nil
19152 (zerop (% 10 5))
19153      @result{} t
19154 @end group
19155 @end smallexample
19157 Thus, the following expression will return @code{t} if the height
19158 of the graph is evenly divisible by five:
19160 @smallexample
19161 (zerop (% height 5))
19162 @end smallexample
19164 @noindent
19165 (The value of @code{height}, of course, can be found from @code{(apply
19166 'max numbers-list)}.)
19168 On the other hand, if the value of @code{height} is not a multiple of
19169 five, we want to reset the value to the next higher multiple of five.
19170 This is straightforward arithmetic using functions with which we are
19171 already familiar.  First, we divide the value of @code{height} by five
19172 to determine how many times five goes into the number.  Thus, five
19173 goes into twelve twice.  If we add one to this quotient and multiply by
19174 five, we will obtain the value of the next multiple of five that is
19175 larger than the height.  Five goes into twelve twice.  Add one to two,
19176 and multiply by five; the result is fifteen, which is the next multiple
19177 of five that is higher than twelve.  The Lisp expression for this is:
19179 @smallexample
19180 (* (1+ (/ height 5)) 5)
19181 @end smallexample
19183 @noindent
19184 For example, if you evaluate the following, the result is 15:
19186 @smallexample
19187 (* (1+ (/ 12 5)) 5)
19188 @end smallexample
19190 All through this discussion, we have been using `five' as the value
19191 for spacing labels on the Y axis; but we may want to use some other
19192 value.  For generality, we should replace `five' with a variable to
19193 which we can assign a value.  The best name I can think of for this
19194 variable is @code{Y-axis-label-spacing}.
19196 @need 1250
19197 Using this term, and an @code{if} expression, we produce the
19198 following:
19200 @smallexample
19201 @group
19202 (if (zerop (% height Y-axis-label-spacing))
19203     height
19204   ;; @r{else}
19205   (* (1+ (/ height Y-axis-label-spacing))
19206      Y-axis-label-spacing))
19207 @end group
19208 @end smallexample
19210 @noindent
19211 This expression returns the value of @code{height} itself if the height
19212 is an even multiple of the value of the @code{Y-axis-label-spacing} or
19213 else it computes and returns a value of @code{height} that is equal to
19214 the next higher multiple of the value of the @code{Y-axis-label-spacing}.
19216 We can now include this expression in the @code{let} expression of the
19217 @code{print-graph} function (after first setting the value of
19218 @code{Y-axis-label-spacing}):
19219 @vindex Y-axis-label-spacing
19221 @smallexample
19222 @group
19223 (defvar Y-axis-label-spacing 5
19224   "Number of lines from one Y axis label to next.")
19225 @end group
19227 @group
19228 @dots{}
19229 (let* ((height (apply 'max numbers-list))
19230        (height-of-top-line
19231         (if (zerop (% height Y-axis-label-spacing))
19232             height
19233 @end group
19234 @group
19235           ;; @r{else}
19236           (* (1+ (/ height Y-axis-label-spacing))
19237              Y-axis-label-spacing)))
19238        (symbol-width (length graph-blank))))
19239 @dots{}
19240 @end group
19241 @end smallexample
19243 @noindent
19244 (Note use of the  @code{let*} function: the initial value of height is
19245 computed once by the @code{(apply 'max numbers-list)} expression and
19246 then the resulting value of  @code{height} is used to compute its
19247 final value.  @xref{fwd-para let, , The @code{let*} expression}, for
19248 more about @code{let*}.)
19250 @node Y Axis Element, Y-axis-column, Compute a Remainder, print-Y-axis
19251 @appendixsubsec Construct a Y Axis Element
19253 When we print the vertical axis, we want to insert strings such as
19254 @w{@samp{5 -}} and @w{@samp{10 - }} every five lines.
19255 Moreover, we want the numbers and dashes to line up, so shorter
19256 numbers must be padded with leading spaces.  If some of the strings
19257 use two digit numbers, the strings with single digit numbers must
19258 include a leading blank space before the number.
19260 @findex number-to-string
19261 To figure out the length of the number, the @code{length} function is
19262 used.  But the @code{length} function works only with a string, not with
19263 a number.  So the number has to be converted from being a number to
19264 being a string.  This is done with the @code{number-to-string} function.
19265 For example,
19267 @smallexample
19268 @group
19269 (length (number-to-string 35))
19270      @result{} 2
19272 (length (number-to-string 100))
19273      @result{} 3
19274 @end group
19275 @end smallexample
19277 @noindent
19278 (@code{number-to-string} is also called @code{int-to-string}; you will
19279 see this alternative name in various sources.)
19281 In addition, in each label, each number is followed by a string such
19282 as @w{@samp{ - }}, which we will call the @code{Y-axis-tic} marker.
19283 This variable is defined with @code{defvar}:
19285 @vindex Y-axis-tic
19286 @smallexample
19287 @group
19288 (defvar Y-axis-tic " - "
19289    "String that follows number in a Y axis label.")
19290 @end group
19291 @end smallexample
19293 The length of the Y label is the sum of the length of the Y axis tic
19294 mark and the length of the number of the top of the graph.
19296 @smallexample
19297 (length (concat (number-to-string height) Y-axis-tic)))
19298 @end smallexample
19300 This value will be calculated by the @code{print-graph} function in
19301 its varlist as @code{full-Y-label-width} and passed on.  (Note that we
19302 did not think to include this in the varlist when we first proposed it.)
19304 To make a complete vertical axis label, a tic mark is concatenated
19305 with a number; and the two together may be preceded by one or more
19306 spaces depending on how long the number is.  The label consists of
19307 three parts: the (optional) leading spaces, the number, and the tic
19308 mark.  The function is passed the value of the number for the specific
19309 row, and the value of the width of the top line, which is calculated
19310 (just once) by @code{print-graph}.
19312 @smallexample
19313 @group
19314 (defun Y-axis-element (number full-Y-label-width)
19315   "Construct a NUMBERed label element.
19316 A numbered element looks like this `  5 - ',
19317 and is padded as needed so all line up with
19318 the element for the largest number."
19319 @end group
19320 @group
19321   (let* ((leading-spaces
19322          (- full-Y-label-width
19323             (length
19324              (concat (number-to-string number)
19325                      Y-axis-tic)))))
19326 @end group
19327 @group
19328     (concat
19329      (make-string leading-spaces ? )
19330      (number-to-string number)
19331      Y-axis-tic)))
19332 @end group
19333 @end smallexample
19335 The @code{Y-axis-element} function concatenates together the leading
19336 spaces, if any; the number, as a string; and the tic mark.
19338 To figure out how many leading spaces the label will need, the
19339 function subtracts the actual length of the label---the length of the
19340 number plus the length of the tic mark---from the desired label width.
19342 @findex make-string
19343 Blank spaces are inserted using the @code{make-string} function.  This
19344 function takes two arguments: the first tells it how long the string
19345 will be and the second is a symbol for the character to insert, in a
19346 special format.  The format is a question mark followed by a blank
19347 space, like this, @samp{? }.  @xref{Character Type, , Character Type,
19348 elisp, The GNU Emacs Lisp Reference Manual}, for a description of the
19349 syntax for characters.
19351 The @code{number-to-string} function is used in the concatenation
19352 expression, to convert the number to a string that is concatenated
19353 with the leading spaces and the tic mark.
19355 @node Y-axis-column, print-Y-axis Penultimate, Y Axis Element, print-Y-axis
19356 @appendixsubsec Create a Y Axis Column
19358 The preceding functions provide all the tools needed to construct a
19359 function that generates a list of numbered and blank strings to insert
19360 as the label for the vertical axis:
19362 @findex Y-axis-column
19363 @smallexample
19364 @group
19365 (defun Y-axis-column (height width-of-label)
19366   "Construct list of Y axis labels and blank strings.
19367 For HEIGHT of line above base and WIDTH-OF-LABEL."
19368   (let (Y-axis)
19369 @group
19370 @end group
19371     (while (> height 1)
19372       (if (zerop (% height Y-axis-label-spacing))
19373           ;; @r{Insert label.}
19374           (setq Y-axis
19375                 (cons
19376                  (Y-axis-element height width-of-label)
19377                  Y-axis))
19378 @group
19379 @end group
19380         ;; @r{Else, insert blanks.}
19381         (setq Y-axis
19382               (cons
19383                (make-string width-of-label ? )
19384                Y-axis)))
19385       (setq height (1- height)))
19386     ;; @r{Insert base line.}
19387     (setq Y-axis
19388           (cons (Y-axis-element 1 width-of-label) Y-axis))
19389     (nreverse Y-axis)))
19390 @end group
19391 @end smallexample
19393 In this function, we start with the value of @code{height} and
19394 repetitively subtract one from its value.  After each subtraction, we
19395 test to see whether the value is an integral multiple of the
19396 @code{Y-axis-label-spacing}.  If it is, we construct a numbered label
19397 using the @code{Y-axis-element} function; if not, we construct a
19398 blank label using the @code{make-string} function.  The base line
19399 consists of the number one followed by a tic mark.
19401 @need 2000
19402 @node print-Y-axis Penultimate,  , Y-axis-column, print-Y-axis
19403 @appendixsubsec The Not Quite Final Version of @code{print-Y-axis}
19405 The list constructed by the @code{Y-axis-column} function is passed to
19406 the @code{print-Y-axis} function, which inserts the list as a column.
19408 @findex print-Y-axis
19409 @smallexample
19410 @group
19411 (defun print-Y-axis (height full-Y-label-width)
19412   "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
19413 Height must be the maximum height of the graph.
19414 Full width is the width of the highest label element."
19415 ;; Value of height and full-Y-label-width
19416 ;; are passed by `print-graph'.
19417 @end group
19418 @group
19419   (let ((start (point)))
19420     (insert-rectangle
19421      (Y-axis-column height full-Y-label-width))
19422     ;; @r{Place point ready for inserting graph.}
19423     (goto-char start)
19424     ;; @r{Move point forward by value of} full-Y-label-width
19425     (forward-char full-Y-label-width)))
19426 @end group
19427 @end smallexample
19429 The @code{print-Y-axis} uses the @code{insert-rectangle} function to
19430 insert the Y axis labels created by the @code{Y-axis-column} function.
19431 In addition, it places point at the correct position for printing the body of
19432 the graph.
19434 You can test @code{print-Y-axis}:
19436 @enumerate
19437 @item
19438 Install
19440 @smallexample
19441 @group
19442 Y-axis-label-spacing
19443 Y-axis-tic
19444 Y-axis-element
19445 Y-axis-column
19446 print-Y-axis
19447 @end group
19448 @end smallexample
19450 @item
19451 Copy the following expression:
19453 @smallexample
19454 (print-Y-axis 12 5)
19455 @end smallexample
19457 @item
19458 Switch to the @file{*scratch*} buffer and place the cursor where you
19459 want the axis labels to start.
19461 @item
19462 Type @kbd{M-:} (@code{eval-expression}).
19464 @item
19465 Yank the @code{graph-body-print} expression into the minibuffer
19466 with @kbd{C-y} (@code{yank)}.
19468 @item
19469 Press @key{RET} to evaluate the expression.
19470 @end enumerate
19472 Emacs will print labels vertically, the top one being
19473 @w{@samp{10 -@w{ }}}.  (The @code{print-graph} function
19474 will pass the value of @code{height-of-top-line}, which
19475 in this case would end up as 15.)
19477 @need 2000
19478 @node print-X-axis, Print Whole Graph, print-Y-axis, Full Graph
19479 @appendixsec The @code{print-X-axis} Function
19480 @cindex Axis, print horizontal
19481 @cindex X axis printing
19482 @cindex Print horizontal axis
19483 @cindex Horizontal axis printing
19485 X axis labels are much like Y axis labels, except that the tics are on a
19486 line above the numbers.  Labels should look like this:
19488 @smallexample
19489 @group
19490     |   |    |    |
19491     1   5   10   15
19492 @end group
19493 @end smallexample
19495 The first tic is under the first column of the graph and is preceded by
19496 several blank spaces.  These spaces provide room in rows above for the Y
19497 axis labels.  The second, third, fourth, and subsequent tics are all
19498 spaced equally, according to the value of @code{X-axis-label-spacing}.
19500 The second row of the X axis consists of numbers, preceded by several
19501 blank spaces and also separated according to the value of the variable
19502 @code{X-axis-label-spacing}.
19504 The value of the variable @code{X-axis-label-spacing} should itself be
19505 measured in units of @code{symbol-width}, since you may want to change
19506 the width of the symbols that you are using to print the body of the
19507 graph without changing the ways the graph is labelled.
19509 @menu
19510 * Similarities differences::    Much like @code{print-Y-axis}, but not exactly.
19511 * X Axis Tic Marks::            Create tic marks for the horizontal axis.
19512 @end menu
19514 @node Similarities differences, X Axis Tic Marks, print-X-axis, print-X-axis
19515 @ifnottex
19516 @unnumberedsubsec Similarities and differences
19517 @end ifnottex
19519 The @code{print-X-axis} function is constructed in more or less the
19520 same fashion as the @code{print-Y-axis} function except that it has
19521 two lines: the line of tic marks and the numbers.  We will write a
19522 separate function to print each line and then combine them within the
19523 @code{print-X-axis} function.
19525 This is a three step process:
19527 @enumerate
19528 @item
19529 Write a function to print the X axis tic marks, @code{print-X-axis-tic-line}.
19531 @item
19532 Write a function to print the X numbers, @code{print-X-axis-numbered-line}.
19534 @item
19535 Write a function to print both lines, the @code{print-X-axis} function,
19536 using @code{print-X-axis-tic-line} and
19537 @code{print-X-axis-numbered-line}.
19538 @end enumerate
19540 @node X Axis Tic Marks,  , Similarities differences, print-X-axis
19541 @appendixsubsec X Axis Tic Marks
19543 The first function should print the X axis tic marks.  We must specify
19544 the tic marks themselves and their spacing:
19546 @smallexample
19547 @group
19548 (defvar X-axis-label-spacing
19549   (if (boundp 'graph-blank)
19550       (* 5 (length graph-blank)) 5)
19551   "Number of units from one X axis label to next.")
19552 @end group
19553 @end smallexample
19555 @noindent
19556 (Note that the value of @code{graph-blank} is set by another
19557 @code{defvar}.  The @code{boundp} predicate checks whether it has
19558 already been set; @code{boundp} returns @code{nil} if it has not.
19559 If @code{graph-blank} were unbound and we did not use this conditional
19560 construction, in GNU Emacs 21, we would enter the debugger and see an
19561 error message saying
19562 @samp{@w{Debugger entered--Lisp error:} @w{(void-variable graph-blank)}}.)
19564 @need 1200
19565 Here is the @code{defvar} for @code{X-axis-tic-symbol}:
19567 @smallexample
19568 @group
19569 (defvar X-axis-tic-symbol "|"
19570   "String to insert to point to a column in X axis.")
19571 @end group
19572 @end smallexample
19574 @need 1250
19575 The goal is to make a line that looks like this:
19577 @smallexample
19578        |   |    |    |
19579 @end smallexample
19581 The first tic is indented so that it is under the first column, which is
19582 indented to provide space for the Y axis labels.
19584 A tic element consists of the blank spaces that stretch from one tic to
19585 the next plus a tic symbol.  The number of blanks is determined by the
19586 width of the tic symbol and the @code{X-axis-label-spacing}.
19588 @need 1250
19589 The code looks like this:
19591 @smallexample
19592 @group
19593 ;;; X-axis-tic-element
19594 @dots{}
19595 (concat
19596  (make-string
19597   ;; @r{Make a string of blanks.}
19598   (-  (* symbol-width X-axis-label-spacing)
19599       (length X-axis-tic-symbol))
19600   ? )
19601  ;; @r{Concatenate blanks with tic symbol.}
19602  X-axis-tic-symbol)
19603 @dots{}
19604 @end group
19605 @end smallexample
19607 Next, we determine how many blanks are needed to indent the first tic
19608 mark to the first column of the graph.  This uses the value of
19609 @code{full-Y-label-width} passed it by the @code{print-graph} function.
19611 @need 1250
19612 The code to make @code{X-axis-leading-spaces}
19613 looks like this:
19615 @smallexample
19616 @group
19617 ;; X-axis-leading-spaces
19618 @dots{}
19619 (make-string full-Y-label-width ? )
19620 @dots{}
19621 @end group
19622 @end smallexample
19624 We also need to determine the length of the horizontal axis, which is
19625 the length of the numbers list, and the number of tics in the horizontal
19626 axis:
19628 @smallexample
19629 @group
19630 ;; X-length
19631 @dots{}
19632 (length numbers-list)
19633 @end group
19635 @group
19636 ;; tic-width
19637 @dots{}
19638 (* symbol-width X-axis-label-spacing)
19639 @end group
19641 @group
19642 ;; number-of-X-tics
19643 (if (zerop (% (X-length tic-width)))
19644     (/ (X-length tic-width))
19645   (1+ (/ (X-length tic-width))))
19646 @end group
19647 @end smallexample
19649 @need 1250
19650 All this leads us directly to the function for printing the X axis tic line:
19652 @findex print-X-axis-tic-line
19653 @smallexample
19654 @group
19655 (defun print-X-axis-tic-line
19656   (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
19657   "Print tics for X axis."
19658     (insert X-axis-leading-spaces)
19659     (insert X-axis-tic-symbol)  ; @r{Under first column.}
19660 @end group
19661 @group
19662     ;; @r{Insert second tic in the right spot.}
19663     (insert (concat
19664              (make-string
19665               (-  (* symbol-width X-axis-label-spacing)
19666                   ;; @r{Insert white space up to second tic symbol.}
19667                   (* 2 (length X-axis-tic-symbol)))
19668               ? )
19669              X-axis-tic-symbol))
19670 @end group
19671 @group
19672     ;; @r{Insert remaining tics.}
19673     (while (> number-of-X-tics 1)
19674       (insert X-axis-tic-element)
19675       (setq number-of-X-tics (1- number-of-X-tics))))
19676 @end group
19677 @end smallexample
19679 The line of numbers is equally straightforward:
19681 @need 1250
19682 First, we create a numbered element with blank spaces before each number:
19684 @findex X-axis-element
19685 @smallexample
19686 @group
19687 (defun X-axis-element (number)
19688   "Construct a numbered X axis element."
19689   (let ((leading-spaces
19690          (-  (* symbol-width X-axis-label-spacing)
19691              (length (number-to-string number)))))
19692     (concat (make-string leading-spaces ? )
19693             (number-to-string number))))
19694 @end group
19695 @end smallexample
19697 Next, we create the function to print the numbered line, starting with
19698 the number ``1'' under the first column:
19700 @findex print-X-axis-numbered-line
19701 @smallexample
19702 @group
19703 (defun print-X-axis-numbered-line
19704   (number-of-X-tics X-axis-leading-spaces)
19705   "Print line of X-axis numbers"
19706   (let ((number X-axis-label-spacing))
19707     (insert X-axis-leading-spaces)
19708     (insert "1")
19709 @end group
19710 @group
19711     (insert (concat
19712              (make-string
19713               ;; @r{Insert white space up to next number.}
19714               (-  (* symbol-width X-axis-label-spacing) 2)
19715               ? )
19716              (number-to-string number)))
19717 @end group
19718 @group
19719     ;; @r{Insert remaining numbers.}
19720     (setq number (+ number X-axis-label-spacing))
19721     (while (> number-of-X-tics 1)
19722       (insert (X-axis-element number))
19723       (setq number (+ number X-axis-label-spacing))
19724       (setq number-of-X-tics (1- number-of-X-tics)))))
19725 @end group
19726 @end smallexample
19728 Finally, we need to write the @code{print-X-axis} that uses
19729 @code{print-X-axis-tic-line} and
19730 @code{print-X-axis-numbered-line}.
19732 The function must determine the local values of the variables used by both
19733 @code{print-X-axis-tic-line} and @code{print-X-axis-numbered-line}, and
19734 then it must call them.  Also, it must print the carriage return that
19735 separates the two lines.
19737 The function consists of a varlist that specifies five local variables,
19738 and calls to each of the two line printing functions:
19740 @findex print-X-axis
19741 @smallexample
19742 @group
19743 (defun print-X-axis (numbers-list)
19744   "Print X axis labels to length of NUMBERS-LIST."
19745   (let* ((leading-spaces
19746           (make-string full-Y-label-width ? ))
19747 @end group
19748 @group
19749        ;; symbol-width @r{is provided by} graph-body-print
19750        (tic-width (* symbol-width X-axis-label-spacing))
19751        (X-length (length numbers-list))
19752 @end group
19753 @group
19754        (X-tic
19755         (concat
19756          (make-string
19757 @end group
19758 @group
19759           ;; @r{Make a string of blanks.}
19760           (-  (* symbol-width X-axis-label-spacing)
19761               (length X-axis-tic-symbol))
19762           ? )
19763 @end group
19764 @group
19765          ;; @r{Concatenate blanks with tic symbol.}
19766          X-axis-tic-symbol))
19767 @end group
19768 @group
19769        (tic-number
19770         (if (zerop (% X-length tic-width))
19771             (/ X-length tic-width)
19772           (1+ (/ X-length tic-width)))))
19773 @end group
19774 @group
19775     (print-X-axis-tic-line tic-number leading-spaces X-tic)
19776     (insert "\n")
19777     (print-X-axis-numbered-line tic-number leading-spaces)))
19778 @end group
19779 @end smallexample
19781 @need 1250
19782 You can test @code{print-X-axis}:
19784 @enumerate
19785 @item
19786 Install @code{X-axis-tic-symbol}, @code{X-axis-label-spacing},
19787 @code{print-X-axis-tic-line}, as well as @code{X-axis-element},
19788 @code{print-X-axis-numbered-line}, and @code{print-X-axis}.
19790 @item
19791 Copy the following expression:
19793 @smallexample
19794 @group
19795 (progn
19796  (let ((full-Y-label-width 5)
19797        (symbol-width 1))
19798    (print-X-axis
19799     '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
19800 @end group
19801 @end smallexample
19803 @item
19804 Switch to the @file{*scratch*} buffer and place the cursor where you
19805 want the axis labels to start.
19807 @item
19808 Type @kbd{M-:} (@code{eval-expression}).
19810 @item
19811 Yank the test expression into the minibuffer
19812 with @kbd{C-y} (@code{yank)}.
19814 @item
19815 Press @key{RET} to evaluate the expression.
19816 @end enumerate
19818 @need 1250
19819 Emacs will print the horizontal axis like this:
19820 @sp 1
19822 @smallexample
19823 @group
19824      |   |    |    |    |
19825      1   5   10   15   20
19826 @end group
19827 @end smallexample
19829 @node Print Whole Graph,  , print-X-axis, Full Graph
19830 @appendixsec Printing the Whole Graph
19831 @cindex Printing the whole graph
19832 @cindex Whole graph printing
19833 @cindex Graph, printing all
19835 Now we are nearly ready to print the whole graph.
19837 The function to print the graph with the proper labels follows the
19838 outline we created earlier (@pxref{Full Graph, , A Graph with Labelled
19839 Axes}), but with additions.
19841 @need 1250
19842 Here is the outline:
19844 @smallexample
19845 @group
19846 (defun print-graph (numbers-list)
19847   "@var{documentation}@dots{}"
19848   (let ((height  @dots{}
19849         @dots{}))
19850 @end group
19851 @group
19852     (print-Y-axis height @dots{} )
19853     (graph-body-print numbers-list)
19854     (print-X-axis @dots{} )))
19855 @end group
19856 @end smallexample
19858 @menu
19859 * The final version::           A few changes.
19860 * Test print-graph::            Run a short test.
19861 * Graphing words in defuns::    Executing the final code.
19862 * lambda::                      How to write an anonymous function.
19863 * mapcar::                      Apply a function to elements of a list.
19864 * Another Bug::                 Yet another bug @dots{} most insidious.
19865 * Final printed graph::         The graph itself!
19866 @end menu
19868 @node The final version, Test print-graph, Print Whole Graph, Print Whole Graph
19869 @ifnottex
19870 @unnumberedsubsec Changes for the Final Version
19871 @end ifnottex
19873 The final version is different from what we planned in two ways:
19874 first, it contains additional values calculated once in the varlist;
19875 second, it carries an option to specify the labels' increment per row.
19876 This latter feature turns out to be essential; otherwise, a graph may
19877 have more rows than fit on a display or on a sheet of paper.
19879 @need 1500
19880 This new feature requires a change to the @code{Y-axis-column}
19881 function, to add @code{vertical-step} to it.  The function looks like
19882 this:
19884 @findex Y-axis-column @r{Final version.}
19885 @smallexample
19886 @group
19887 ;;; @r{Final version.}
19888 (defun Y-axis-column
19889   (height width-of-label &optional vertical-step)
19890   "Construct list of labels for Y axis.
19891 HEIGHT is maximum height of graph.
19892 WIDTH-OF-LABEL is maximum width of label.
19893 VERTICAL-STEP, an option, is a positive integer
19894 that specifies how much a Y axis label increments
19895 for each line.  For example, a step of 5 means
19896 that each line is five units of the graph."
19897 @end group
19898 @group
19899   (let (Y-axis
19900         (number-per-line (or vertical-step 1)))
19901     (while (> height 1)
19902       (if (zerop (% height Y-axis-label-spacing))
19903 @end group
19904 @group
19905           ;; @r{Insert label.}
19906           (setq Y-axis
19907                 (cons
19908                  (Y-axis-element
19909                   (* height number-per-line)
19910                   width-of-label)
19911                  Y-axis))
19912 @end group
19913 @group
19914         ;; @r{Else, insert blanks.}
19915         (setq Y-axis
19916               (cons
19917                (make-string width-of-label ? )
19918                Y-axis)))
19919       (setq height (1- height)))
19920 @end group
19921 @group
19922     ;; @r{Insert base line.}
19923     (setq Y-axis (cons (Y-axis-element
19924                         (or vertical-step 1)
19925                         width-of-label)
19926                        Y-axis))
19927     (nreverse Y-axis)))
19928 @end group
19929 @end smallexample
19931 The values for the maximum height of graph and the width of a symbol
19932 are computed by @code{print-graph} in its @code{let} expression; so
19933 @code{graph-body-print} must be changed to accept them.
19935 @findex graph-body-print @r{Final version.}
19936 @smallexample
19937 @group
19938 ;;; @r{Final version.}
19939 (defun graph-body-print (numbers-list height symbol-width)
19940   "Print a bar graph of the NUMBERS-LIST.
19941 The numbers-list consists of the Y-axis values.
19942 HEIGHT is maximum height of graph.
19943 SYMBOL-WIDTH is number of each column."
19944 @end group
19945 @group
19946   (let (from-position)
19947     (while numbers-list
19948       (setq from-position (point))
19949       (insert-rectangle
19950        (column-of-graph height (car numbers-list)))
19951       (goto-char from-position)
19952       (forward-char symbol-width)
19953 @end group
19954 @group
19955       ;; @r{Draw graph column by column.}
19956       (sit-for 0)
19957       (setq numbers-list (cdr numbers-list)))
19958     ;; @r{Place point for X axis labels.}
19959     (forward-line height)
19960     (insert "\n")))
19961 @end group
19962 @end smallexample
19964 @need 1250
19965 Finally, the code for the @code{print-graph} function:
19967 @findex print-graph @r{Final version.}
19968 @smallexample
19969 @group
19970 ;;; @r{Final version.}
19971 (defun print-graph
19972   (numbers-list &optional vertical-step)
19973   "Print labelled bar graph of the NUMBERS-LIST.
19974 The numbers-list consists of the Y-axis values.
19975 @end group
19977 @group
19978 Optionally, VERTICAL-STEP, a positive integer,
19979 specifies how much a Y axis label increments for
19980 each line.  For example, a step of 5 means that
19981 each row is five units."
19982 @end group
19983 @group
19984   (let* ((symbol-width (length graph-blank))
19985          ;; @code{height} @r{is both the largest number}
19986          ;; @r{and the number with the most digits.}
19987          (height (apply 'max numbers-list))
19988 @end group
19989 @group
19990          (height-of-top-line
19991           (if (zerop (% height Y-axis-label-spacing))
19992               height
19993             ;; @r{else}
19994             (* (1+ (/ height Y-axis-label-spacing))
19995                Y-axis-label-spacing)))
19996 @end group
19997 @group
19998          (vertical-step (or vertical-step 1))
19999          (full-Y-label-width
20000           (length
20001 @end group
20002 @group
20003            (concat
20004             (number-to-string
20005              (* height-of-top-line vertical-step))
20006             Y-axis-tic))))
20007 @end group
20009 @group
20010     (print-Y-axis
20011      height-of-top-line full-Y-label-width vertical-step)
20012 @end group
20013 @group
20014     (graph-body-print
20015      numbers-list height-of-top-line symbol-width)
20016     (print-X-axis numbers-list)))
20017 @end group
20018 @end smallexample
20020 @node Test print-graph, Graphing words in defuns, The final version, Print Whole Graph
20021 @appendixsubsec Testing @code{print-graph}
20023 @need 1250
20024 We can test the @code{print-graph} function with a short list of numbers:
20026 @enumerate
20027 @item
20028 Install the final versions of @code{Y-axis-column},
20029 @code{graph-body-print}, and @code{print-graph} (in addition to the
20030 rest of the code.)
20032 @item
20033 Copy the following expression:
20035 @smallexample
20036 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
20037 @end smallexample
20039 @item
20040 Switch to the @file{*scratch*} buffer and place the cursor where you
20041 want the axis labels to start.
20043 @item
20044 Type @kbd{M-:} (@code{eval-expression}).
20046 @item
20047 Yank the test expression into the minibuffer
20048 with @kbd{C-y} (@code{yank)}.
20050 @item
20051 Press @key{RET} to evaluate the expression.
20052 @end enumerate
20054 @need 1250
20055 Emacs will print a graph that looks like this:
20057 @smallexample
20058 @group
20059 10 -
20062          *
20063         **   *
20064  5 -   ****  *
20065        **** ***
20066      * *********
20067      ************
20068  1 - *************
20070      |   |    |    |
20071      1   5   10   15
20072 @end group
20073 @end smallexample
20075 @need 1200
20076 On the other hand, if you pass @code{print-graph} a
20077 @code{vertical-step} value of 2, by evaluating this expression:
20079 @smallexample
20080 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
20081 @end smallexample
20083 @need 1250
20084 @noindent
20085 The graph looks like this:
20087 @smallexample
20088 @group
20089 20 -
20092          *
20093         **   *
20094 10 -   ****  *
20095        **** ***
20096      * *********
20097      ************
20098  2 - *************
20100      |   |    |    |
20101      1   5   10   15
20102 @end group
20103 @end smallexample
20105 @noindent
20106 (A question: is the `2' on the bottom of the vertical axis a bug or a
20107 feature?  If you think it is a bug, and should be a `1' instead, (or
20108 even a `0'), you can modify the sources.)
20110 @node Graphing words in defuns, lambda, Test print-graph, Print Whole Graph
20111 @appendixsubsec Graphing Numbers of Words and Symbols
20113 Now for the graph for which all this code was written: a graph that
20114 shows how many function definitions contain fewer than 10 words and
20115 symbols, how many contain between 10 and 19 words and symbols, how
20116 many contain between 20 and 29 words and symbols, and so on.
20118 This is a multi-step process.  First make sure you have loaded all the
20119 requisite code.
20121 @need 1500
20122 It is a good idea to reset the value of @code{top-of-ranges} in case
20123 you have set it to some different value.  You can evaluate the
20124 following:
20126 @smallexample
20127 @group
20128 (setq top-of-ranges
20129  '(10  20  30  40  50
20130    60  70  80  90 100
20131   110 120 130 140 150
20132   160 170 180 190 200
20133   210 220 230 240 250
20134   260 270 280 290 300)
20135 @end group
20136 @end smallexample
20138 @noindent
20139 Next create a list of the number of words and symbols in each range.
20141 @need 1500
20142 @noindent
20143 Evaluate the following:
20145 @smallexample
20146 @group
20147 (setq list-for-graph
20148        (defuns-per-range
20149          (sort
20150           (recursive-lengths-list-many-files
20151            (directory-files "/usr/local/emacs/lisp"
20152                             t ".+el$"))
20153           '<)
20154          top-of-ranges))
20155 @end group
20156 @end smallexample
20158 @noindent
20159 On my old machine, this took about an hour.  It looked though 303 Lisp
20160 files in my copy of Emacs version 19.23.  After all that computing,
20161 the @code{list-for-graph} had this value:
20163 @smallexample
20164 @group
20165 (537 1027 955 785 594 483 349 292 224 199 166 120 116 99
20166 90 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
20167 @end group
20168 @end smallexample
20170 @noindent
20171 This means that my copy of Emacs had 537 function definitions with
20172 fewer than 10 words or symbols in them, 1,027 function definitions
20173 with 10 to 19 words or symbols in them, 955 function definitions with
20174 20 to 29 words or symbols in them, and so on.
20176 Clearly, just by looking at this list we can see that most function
20177 definitions contain ten to thirty words and symbols.
20179 Now for printing.  We do @emph{not} want to print a graph that is
20180 1,030 lines high @dots{}  Instead, we should print a graph that is
20181 fewer than twenty-five lines high.  A graph that height can be
20182 displayed on almost any monitor, and easily printed on a sheet of paper.
20184 This means that each value in @code{list-for-graph} must be reduced to
20185 one-fiftieth its present value.
20187 Here is a short function to do just that, using two functions we have
20188 not yet seen, @code{mapcar} and @code{lambda}.
20190 @smallexample
20191 @group
20192 (defun one-fiftieth (full-range)
20193   "Return list, each number one-fiftieth of previous."
20194  (mapcar '(lambda (arg) (/ arg 50)) full-range))
20195 @end group
20196 @end smallexample
20198 @node lambda, mapcar, Graphing words in defuns, Print Whole Graph
20199 @appendixsubsec A @code{lambda} Expression: Useful Anonymity
20200 @cindex Anonymous function
20201 @findex lambda
20203 @code{lambda} is the symbol for an anonymous function, a function
20204 without a name.  Every time you use an anonymous function, you need to
20205 include its whole body.
20207 @need 1250
20208 @noindent
20209 Thus,
20211 @smallexample
20212 (lambda (arg) (/ arg 50))
20213 @end smallexample
20215 @noindent
20216 is a function definition that says `return the value resulting from
20217 dividing whatever is passed to me as @code{arg} by 50'.
20219 @need 1200
20220 Earlier, for example, we had a function @code{multiply-by-seven}; it
20221 multiplied its argument by 7.  This function is similar, except it
20222 divides its argument by 50; and, it has no name.  The anonymous
20223 equivalent of @code{multiply-by-seven} is:
20225 @smallexample
20226 (lambda (number) (* 7 number))
20227 @end smallexample
20229 @noindent
20230 (@xref{defun, ,  The @code{defun} Special Form}.)
20232 @need 1250
20233 @noindent
20234 If we want to multiply 3 by 7, we can write:
20236 @c !!! Clear print-postscript-figures if the computer formatting this
20237 @c     document is too small and cannot handle all the diagrams and figures.
20238 @c clear print-postscript-figures
20239 @c set print-postscript-figures
20240 @c lambda example diagram #1
20241 @ifnottex
20242 @smallexample
20243 @group
20244 (multiply-by-seven 3)
20245  \_______________/ ^
20246          |         |
20247       function  argument
20248 @end group
20249 @end smallexample
20250 @end ifnottex
20251 @ifset print-postscript-figures
20252 @sp 1
20253 @tex
20254 @image{lambda-1}
20255 %%%% old method of including an image
20256 % \input /usr/local/lib/tex/inputs/psfig.tex
20257 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-1.eps}}
20258 % \catcode`\@=0 %
20259 @end tex
20260 @sp 1
20261 @end ifset
20262 @ifclear print-postscript-figures
20263 @iftex
20264 @smallexample
20265 @group
20266 (multiply-by-seven 3)
20267  \_______________/ ^
20268          |         |
20269       function  argument
20270 @end group
20271 @end smallexample
20272 @end iftex
20273 @end ifclear
20275 @noindent
20276 This expression returns 21.
20278 @need 1250
20279 @noindent
20280 Similarly, we can write:
20282 @c lambda example diagram #2
20283 @ifnottex
20284 @smallexample
20285 @group
20286 ((lambda (number) (* 7 number)) 3)
20287  \____________________________/ ^
20288                |                |
20289       anonymous function     argument
20290 @end group
20291 @end smallexample
20292 @end ifnottex
20293 @ifset print-postscript-figures
20294 @sp 1
20295 @tex
20296 @image{lambda-2}
20297 %%%% old method of including an image
20298 % \input /usr/local/lib/tex/inputs/psfig.tex
20299 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-2.eps}}
20300 % \catcode`\@=0 %
20301 @end tex
20302 @sp 1
20303 @end ifset
20304 @ifclear print-postscript-figures
20305 @iftex
20306 @smallexample
20307 @group
20308 ((lambda (number) (* 7 number)) 3)
20309  \____________________________/ ^
20310                |                |
20311       anonymous function     argument
20312 @end group
20313 @end smallexample
20314 @end iftex
20315 @end ifclear
20317 @need 1250
20318 @noindent
20319 If we want to divide 100 by 50, we can write:
20321 @c lambda example diagram #3
20322 @ifnottex
20323 @smallexample
20324 @group
20325 ((lambda (arg) (/ arg 50)) 100)
20326  \______________________/  \_/
20327              |              |
20328     anonymous function   argument
20329 @end group
20330 @end smallexample
20331 @end ifnottex
20332 @ifset print-postscript-figures
20333 @sp 1
20334 @tex
20335 @image{lambda-3}
20336 %%%% old method of including an image
20337 % \input /usr/local/lib/tex/inputs/psfig.tex
20338 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-3.eps}}
20339 % \catcode`\@=0 %
20340 @end tex
20341 @sp 1
20342 @end ifset
20343 @ifclear print-postscript-figures
20344 @iftex
20345 @smallexample
20346 @group
20347 ((lambda (arg) (/ arg 50)) 100)
20348  \______________________/  \_/
20349              |              |
20350     anonymous function   argument
20351 @end group
20352 @end smallexample
20353 @end iftex
20354 @end ifclear
20356 @noindent
20357 This expression returns 2.  The 100 is passed to the function, which
20358 divides that number by 50.
20360 @xref{Lambda Expressions, , Lambda Expressions, elisp, The GNU Emacs
20361 Lisp Reference Manual}, for more about @code{lambda}.  Lisp and lambda
20362 expressions derive from the Lambda Calculus.
20364 @node mapcar, Another Bug, lambda, Print Whole Graph
20365 @appendixsubsec The @code{mapcar} Function
20366 @findex mapcar
20368 @code{mapcar} is a function that calls its first argument with each
20369 element of its second argument, in turn.  The second argument must be
20370 a sequence.
20372 The @samp{map} part of the name comes from the mathematical phrase,
20373 `mapping over a domain', meaning to apply a function to each of the
20374 elements in a domain.  The mathematical phrase is based on the
20375 metaphor of a surveyor walking, one step at a time, over an area he is
20376 mapping.  And @samp{car}, of course, comes from the Lisp notion of the
20377 first of a list.
20379 @need 1250
20380 @noindent
20381 For example,
20383 @smallexample
20384 @group
20385 (mapcar '1+ '(2 4 6))
20386      @result{} (3 5 7)
20387 @end group
20388 @end smallexample
20390 @noindent
20391 The function @code{1+} which adds one to its argument, is executed on
20392 @emph{each} element of the list, and a new list is returned.
20394 Contrast this with @code{apply}, which applies its first argument to
20395 all the remaining.
20396 (@xref{Readying a Graph, , Readying a Graph}, for a explanation of
20397 @code{apply}.)
20399 @need 1250
20400 In the definition of @code{one-fiftieth}, the first argument is the
20401 anonymous function:
20403 @smallexample
20404 (lambda (arg) (/ arg 50))
20405 @end smallexample
20407 @noindent
20408 and the second argument is @code{full-range}, which will be bound to
20409 @code{list-for-graph}.
20411 @need 1250
20412 The whole expression looks like this:
20414 @smallexample
20415 (mapcar '(lambda (arg) (/ arg 50)) full-range))
20416 @end smallexample
20418 @xref{Mapping Functions, , Mapping Functions, elisp, The GNU Emacs
20419 Lisp Reference Manual}, for more about @code{mapcar}.
20421 Using the @code{one-fiftieth} function, we can generate a list in
20422 which each element is one-fiftieth the size of the corresponding
20423 element in @code{list-for-graph}.
20425 @smallexample
20426 @group
20427 (setq fiftieth-list-for-graph
20428       (one-fiftieth list-for-graph))
20429 @end group
20430 @end smallexample
20432 @need 1250
20433 The resulting list looks like this:
20435 @smallexample
20436 @group
20437 (10 20 19 15 11 9 6 5 4 3 3 2 2
20438 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
20439 @end group
20440 @end smallexample
20442 @noindent
20443 This, we are almost ready to print!  (We also notice the loss of
20444 information: many of the higher ranges are 0, meaning that fewer than
20445 50 defuns had that many words or symbols---but not necessarily meaning
20446 that none had that many words or symbols.)
20448 @node Another Bug, Final printed graph, mapcar, Print Whole Graph
20449 @appendixsubsec Another Bug @dots{} Most Insidious
20450 @cindex Bug, most insidious type
20451 @cindex Insidious type of bug
20453 I said `almost ready to print'!  Of course, there is a bug in the
20454 @code{print-graph} function @dots{}  It has a @code{vertical-step}
20455 option, but not a @code{horizontal-step} option.  The
20456 @code{top-of-range} scale goes from 10 to 300 by tens.  But the
20457 @code{print-graph} function will print only by ones.
20459 This is a classic example of what some consider the most insidious
20460 type of bug, the bug of omission.  This is not the kind of bug you can
20461 find by studying the code, for it is not in the code; it is an omitted
20462 feature.  Your best actions are to try your program early and often;
20463 and try to arrange, as much as you can, to write code that is easy to
20464 understand and easy to change.  Try to be aware, whenever you can,
20465 that whatever you have written, @emph{will} be rewritten, if not soon,
20466 eventually.  A hard maxim to follow.
20468 It is the @code{print-X-axis-numbered-line} function that needs the
20469 work; and then the @code{print-X-axis} and the @code{print-graph}
20470 functions need to be adapted.  Not much needs to be done; there is one
20471 nicety: the numbers ought to line up under the tic marks.  This takes
20472 a little thought.
20474 @need 1250
20475 Here is the corrected @code{print-X-axis-numbered-line}:
20477 @smallexample
20478 @group
20479 (defun print-X-axis-numbered-line
20480   (number-of-X-tics X-axis-leading-spaces
20481    &optional horizontal-step)
20482   "Print line of X-axis numbers"
20483   (let ((number X-axis-label-spacing)
20484         (horizontal-step (or horizontal-step 1)))
20485 @end group
20486 @group
20487     (insert X-axis-leading-spaces)
20488     ;; @r{Delete extra leading spaces.}
20489     (delete-char
20490      (- (1-
20491          (length (number-to-string horizontal-step)))))
20492     (insert (concat
20493              (make-string
20494 @end group
20495 @group
20496               ;; @r{Insert white space.}
20497               (-  (* symbol-width
20498                      X-axis-label-spacing)
20499                   (1-
20500                    (length
20501                     (number-to-string horizontal-step)))
20502                   2)
20503               ? )
20504              (number-to-string
20505               (* number horizontal-step))))
20506 @end group
20507 @group
20508     ;; @r{Insert remaining numbers.}
20509     (setq number (+ number X-axis-label-spacing))
20510     (while (> number-of-X-tics 1)
20511       (insert (X-axis-element
20512                (* number horizontal-step)))
20513       (setq number (+ number X-axis-label-spacing))
20514       (setq number-of-X-tics (1- number-of-X-tics)))))
20515 @end group
20516 @end smallexample
20518 @need 1500
20519 If you are reading this in Info, you can see the new versions of
20520 @code{print-X-axis} @code{print-graph} and evaluate them.  If you are
20521 reading this in a printed book, you can see the changed lines here
20522 (the full text is too much to print).
20524 @iftex
20525 @smallexample
20526 @group
20527 (defun print-X-axis (numbers-list horizontal-step)
20528   @dots{}
20529     (print-X-axis-numbered-line
20530      tic-number leading-spaces horizontal-step))
20531 @end group
20532 @end smallexample
20534 @smallexample
20535 @group
20536 (defun print-graph
20537   (numbers-list
20538    &optional vertical-step horizontal-step)
20539   @dots{}
20540     (print-X-axis numbers-list horizontal-step))
20541 @end group
20542 @end smallexample
20543 @end iftex
20545 @ifnottex
20546 @smallexample
20547 @group
20548 (defun print-X-axis (numbers-list horizontal-step)
20549   "Print X axis labels to length of NUMBERS-LIST.
20550 Optionally, HORIZONTAL-STEP, a positive integer,
20551 specifies how much an X  axis label increments for
20552 each column."
20553 @end group
20554 @group
20555 ;; Value of symbol-width and full-Y-label-width
20556 ;; are passed by `print-graph'.
20557   (let* ((leading-spaces
20558           (make-string full-Y-label-width ? ))
20559        ;; symbol-width @r{is provided by} graph-body-print
20560        (tic-width (* symbol-width X-axis-label-spacing))
20561        (X-length (length numbers-list))
20562 @end group
20563 @group
20564        (X-tic
20565         (concat
20566          (make-string
20567           ;; @r{Make a string of blanks.}
20568           (-  (* symbol-width X-axis-label-spacing)
20569               (length X-axis-tic-symbol))
20570           ? )
20571 @end group
20572 @group
20573          ;; @r{Concatenate blanks with tic symbol.}
20574          X-axis-tic-symbol))
20575        (tic-number
20576         (if (zerop (% X-length tic-width))
20577             (/ X-length tic-width)
20578           (1+ (/ X-length tic-width)))))
20579 @end group
20581 @group
20582     (print-X-axis-tic-line
20583      tic-number leading-spaces X-tic)
20584     (insert "\n")
20585     (print-X-axis-numbered-line
20586      tic-number leading-spaces horizontal-step)))
20587 @end group
20588 @end smallexample
20590 @smallexample
20591 @group
20592 (defun print-graph
20593   (numbers-list &optional vertical-step horizontal-step)
20594   "Print labelled bar graph of the NUMBERS-LIST.
20595 The numbers-list consists of the Y-axis values.
20596 @end group
20598 @group
20599 Optionally, VERTICAL-STEP, a positive integer,
20600 specifies how much a Y axis label increments for
20601 each line.  For example, a step of 5 means that
20602 each row is five units.
20603 @end group
20605 @group
20606 Optionally, HORIZONTAL-STEP, a positive integer,
20607 specifies how much an X  axis label increments for
20608 each column."
20609   (let* ((symbol-width (length graph-blank))
20610          ;; @code{height} @r{is both the largest number}
20611          ;; @r{and the number with the most digits.}
20612          (height (apply 'max numbers-list))
20613 @end group
20614 @group
20615          (height-of-top-line
20616           (if (zerop (% height Y-axis-label-spacing))
20617               height
20618             ;; @r{else}
20619             (* (1+ (/ height Y-axis-label-spacing))
20620                Y-axis-label-spacing)))
20621 @end group
20622 @group
20623          (vertical-step (or vertical-step 1))
20624          (full-Y-label-width
20625           (length
20626            (concat
20627             (number-to-string
20628              (* height-of-top-line vertical-step))
20629             Y-axis-tic))))
20630 @end group
20631 @group
20632     (print-Y-axis
20633      height-of-top-line full-Y-label-width vertical-step)
20634     (graph-body-print
20635         numbers-list height-of-top-line symbol-width)
20636     (print-X-axis numbers-list horizontal-step)))
20637 @end group
20638 @end smallexample
20639 @end ifnottex
20641 @ignore
20642 Graphing Definitions Re-listed
20644 @need 1250
20645 Here are all the graphing definitions in their final form:
20647 @smallexample
20648 @group
20649 (defvar top-of-ranges
20650  '(10  20  30  40  50
20651    60  70  80  90 100
20652   110 120 130 140 150
20653   160 170 180 190 200
20654   210 220 230 240 250)
20655  "List specifying ranges for `defuns-per-range'.")
20656 @end group
20658 @group
20659 (defvar graph-symbol "*"
20660   "String used as symbol in graph, usually an asterisk.")
20661 @end group
20663 @group
20664 (defvar graph-blank " "
20665   "String used as blank in graph, usually a blank space.
20666 graph-blank must be the same number of columns wide
20667 as graph-symbol.")
20668 @end group
20670 @group
20671 (defvar Y-axis-tic " - "
20672    "String that follows number in a Y axis label.")
20673 @end group
20675 @group
20676 (defvar Y-axis-label-spacing 5
20677   "Number of lines from one Y axis label to next.")
20678 @end group
20680 @group
20681 (defvar X-axis-tic-symbol "|"
20682   "String to insert to point to a column in X axis.")
20683 @end group
20685 @group
20686 (defvar X-axis-label-spacing
20687   (if (boundp 'graph-blank)
20688       (* 5 (length graph-blank)) 5)
20689   "Number of units from one X axis label to next.")
20690 @end group
20691 @end smallexample
20693 @smallexample
20694 @group
20695 (defun count-words-in-defun ()
20696   "Return the number of words and symbols in a defun."
20697   (beginning-of-defun)
20698   (let ((count 0)
20699         (end (save-excursion (end-of-defun) (point))))
20700 @end group
20702 @group
20703     (while
20704         (and (< (point) end)
20705              (re-search-forward
20706               "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
20707               end t))
20708       (setq count (1+ count)))
20709     count))
20710 @end group
20711 @end smallexample
20713 @smallexample
20714 @group
20715 (defun lengths-list-file (filename)
20716   "Return list of definitions' lengths within FILE.
20717 The returned list is a list of numbers.
20718 Each number is the number of words or
20719 symbols in one function definition."
20720 @end group
20722 @group
20723   (message "Working on `%s' ... " filename)
20724   (save-excursion
20725     (let ((buffer (find-file-noselect filename))
20726           (lengths-list))
20727       (set-buffer buffer)
20728       (setq buffer-read-only t)
20729       (widen)
20730       (goto-char (point-min))
20731 @end group
20733 @group
20734       (while (re-search-forward "^(defun" nil t)
20735         (setq lengths-list
20736               (cons (count-words-in-defun) lengths-list)))
20737       (kill-buffer buffer)
20738       lengths-list)))
20739 @end group
20740 @end smallexample
20742 @smallexample
20743 @group
20744 (defun lengths-list-many-files (list-of-files)
20745   "Return list of lengths of defuns in LIST-OF-FILES."
20746   (let (lengths-list)
20747 ;;; @r{true-or-false-test}
20748     (while list-of-files
20749       (setq lengths-list
20750             (append
20751              lengths-list
20752 @end group
20753 @group
20754 ;;; @r{Generate a lengths' list.}
20755              (lengths-list-file
20756               (expand-file-name (car list-of-files)))))
20757 ;;; @r{Make files' list shorter.}
20758       (setq list-of-files (cdr list-of-files)))
20759 ;;; @r{Return final value of lengths' list.}
20760     lengths-list))
20761 @end group
20762 @end smallexample
20764 @smallexample
20765 @group
20766 (defun defuns-per-range (sorted-lengths top-of-ranges)
20767   "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
20768   (let ((top-of-range (car top-of-ranges))
20769         (number-within-range 0)
20770         defuns-per-range-list)
20771 @end group
20773 @group
20774     ;; @r{Outer loop.}
20775     (while top-of-ranges
20777       ;; @r{Inner loop.}
20778       (while (and
20779               ;; @r{Need number for numeric test.}
20780               (car sorted-lengths)
20781               (< (car sorted-lengths) top-of-range))
20783         ;; @r{Count number of definitions within current range.}
20784         (setq number-within-range (1+ number-within-range))
20785         (setq sorted-lengths (cdr sorted-lengths)))
20786 @end group
20788 @group
20789       ;; @r{Exit inner loop but remain within outer loop.}
20791       (setq defuns-per-range-list
20792             (cons number-within-range defuns-per-range-list))
20793       (setq number-within-range 0)      ; @r{Reset count to zero.}
20795       ;; @r{Move to next range.}
20796       (setq top-of-ranges (cdr top-of-ranges))
20797       ;; @r{Specify next top of range value.}
20798       (setq top-of-range (car top-of-ranges)))
20799 @end group
20801 @group
20802     ;; @r{Exit outer loop and count the number of defuns larger than}
20803     ;; @r{  the largest top-of-range value.}
20804     (setq defuns-per-range-list
20805           (cons
20806            (length sorted-lengths)
20807            defuns-per-range-list))
20809     ;; @r{Return a list of the number of definitions within each range,}
20810     ;; @r{  smallest to largest.}
20811     (nreverse defuns-per-range-list)))
20812 @end group
20813 @end smallexample
20815 @smallexample
20816 @group
20817 (defun column-of-graph (max-graph-height actual-height)
20818   "Return list of MAX-GRAPH-HEIGHT strings;
20819 ACTUAL-HEIGHT are graph-symbols.
20820 The graph-symbols are contiguous entries at the end
20821 of the list.
20822 The list will be inserted as one column of a graph.
20823 The strings are either graph-blank or graph-symbol."
20824 @end group
20826 @group
20827   (let ((insert-list nil)
20828         (number-of-top-blanks
20829          (- max-graph-height actual-height)))
20831     ;; @r{Fill in @code{graph-symbols}.}
20832     (while (> actual-height 0)
20833       (setq insert-list (cons graph-symbol insert-list))
20834       (setq actual-height (1- actual-height)))
20835 @end group
20837 @group
20838     ;; @r{Fill in @code{graph-blanks}.}
20839     (while (> number-of-top-blanks 0)
20840       (setq insert-list (cons graph-blank insert-list))
20841       (setq number-of-top-blanks
20842             (1- number-of-top-blanks)))
20844     ;; @r{Return whole list.}
20845     insert-list))
20846 @end group
20847 @end smallexample
20849 @smallexample
20850 @group
20851 (defun Y-axis-element (number full-Y-label-width)
20852   "Construct a NUMBERed label element.
20853 A numbered element looks like this `  5 - ',
20854 and is padded as needed so all line up with
20855 the element for the largest number."
20856 @end group
20857 @group
20858   (let* ((leading-spaces
20859          (- full-Y-label-width
20860             (length
20861              (concat (number-to-string number)
20862                      Y-axis-tic)))))
20863 @end group
20864 @group
20865     (concat
20866      (make-string leading-spaces ? )
20867      (number-to-string number)
20868      Y-axis-tic)))
20869 @end group
20870 @end smallexample
20872 @smallexample
20873 @group
20874 (defun print-Y-axis
20875   (height full-Y-label-width &optional vertical-step)
20876   "Insert Y axis by HEIGHT and FULL-Y-LABEL-WIDTH.
20877 Height must be the  maximum height of the graph.
20878 Full width is the width of the highest label element.
20879 Optionally, print according to VERTICAL-STEP."
20880 @end group
20881 @group
20882 ;; Value of height and full-Y-label-width
20883 ;; are passed by `print-graph'.
20884   (let ((start (point)))
20885     (insert-rectangle
20886      (Y-axis-column height full-Y-label-width vertical-step))
20887 @end group
20888 @group
20889     ;; @r{Place point ready for inserting graph.}
20890     (goto-char start)
20891     ;; @r{Move point forward by value of} full-Y-label-width
20892     (forward-char full-Y-label-width)))
20893 @end group
20894 @end smallexample
20896 @smallexample
20897 @group
20898 (defun print-X-axis-tic-line
20899   (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
20900   "Print tics for X axis."
20901     (insert X-axis-leading-spaces)
20902     (insert X-axis-tic-symbol)  ; @r{Under first column.}
20903 @end group
20904 @group
20905     ;; @r{Insert second tic in the right spot.}
20906     (insert (concat
20907              (make-string
20908               (-  (* symbol-width X-axis-label-spacing)
20909                   ;; @r{Insert white space up to second tic symbol.}
20910                   (* 2 (length X-axis-tic-symbol)))
20911               ? )
20912              X-axis-tic-symbol))
20913 @end group
20914 @group
20915     ;; @r{Insert remaining tics.}
20916     (while (> number-of-X-tics 1)
20917       (insert X-axis-tic-element)
20918       (setq number-of-X-tics (1- number-of-X-tics))))
20919 @end group
20920 @end smallexample
20922 @smallexample
20923 @group
20924 (defun X-axis-element (number)
20925   "Construct a numbered X axis element."
20926   (let ((leading-spaces
20927          (-  (* symbol-width X-axis-label-spacing)
20928              (length (number-to-string number)))))
20929     (concat (make-string leading-spaces ? )
20930             (number-to-string number))))
20931 @end group
20932 @end smallexample
20934 @smallexample
20935 @group
20936 (defun graph-body-print (numbers-list height symbol-width)
20937   "Print a bar graph of the NUMBERS-LIST.
20938 The numbers-list consists of the Y-axis values.
20939 HEIGHT is maximum height of graph.
20940 SYMBOL-WIDTH is number of each column."
20941 @end group
20942 @group
20943   (let (from-position)
20944     (while numbers-list
20945       (setq from-position (point))
20946       (insert-rectangle
20947        (column-of-graph height (car numbers-list)))
20948       (goto-char from-position)
20949       (forward-char symbol-width)
20950 @end group
20951 @group
20952       ;; @r{Draw graph column by column.}
20953       (sit-for 0)
20954       (setq numbers-list (cdr numbers-list)))
20955     ;; @r{Place point for X axis labels.}
20956     (forward-line height)
20957     (insert "\n")))
20958 @end group
20959 @end smallexample
20961 @smallexample
20962 @group
20963 (defun Y-axis-column
20964   (height width-of-label &optional vertical-step)
20965   "Construct list of labels for Y axis.
20966 HEIGHT is maximum height of graph.
20967 WIDTH-OF-LABEL is maximum width of label.
20968 @end group
20969 @group
20970 VERTICAL-STEP, an option, is a positive integer
20971 that specifies how much a Y axis label increments
20972 for each line.  For example, a step of 5 means
20973 that each line is five units of the graph."
20974   (let (Y-axis
20975         (number-per-line (or vertical-step 1)))
20976 @end group
20977 @group
20978     (while (> height 1)
20979       (if (zerop (% height Y-axis-label-spacing))
20980           ;; @r{Insert label.}
20981           (setq Y-axis
20982                 (cons
20983                  (Y-axis-element
20984                   (* height number-per-line)
20985                   width-of-label)
20986                  Y-axis))
20987 @end group
20988 @group
20989         ;; @r{Else, insert blanks.}
20990         (setq Y-axis
20991               (cons
20992                (make-string width-of-label ? )
20993                Y-axis)))
20994       (setq height (1- height)))
20995 @end group
20996 @group
20997     ;; @r{Insert base line.}
20998     (setq Y-axis (cons (Y-axis-element
20999                         (or vertical-step 1)
21000                         width-of-label)
21001                        Y-axis))
21002     (nreverse Y-axis)))
21003 @end group
21004 @end smallexample
21006 @smallexample
21007 @group
21008 (defun print-X-axis-numbered-line
21009   (number-of-X-tics X-axis-leading-spaces
21010    &optional horizontal-step)
21011   "Print line of X-axis numbers"
21012   (let ((number X-axis-label-spacing)
21013         (horizontal-step (or horizontal-step 1)))
21014 @end group
21015 @group
21016     (insert X-axis-leading-spaces)
21017     ;; line up number
21018     (delete-char (- (1- (length (number-to-string horizontal-step)))))
21019     (insert (concat
21020              (make-string
21021               ;; @r{Insert white space up to next number.}
21022               (-  (* symbol-width X-axis-label-spacing)
21023                   (1- (length (number-to-string horizontal-step)))
21024                   2)
21025               ? )
21026              (number-to-string (* number horizontal-step))))
21027 @end group
21028 @group
21029     ;; @r{Insert remaining numbers.}
21030     (setq number (+ number X-axis-label-spacing))
21031     (while (> number-of-X-tics 1)
21032       (insert (X-axis-element (* number horizontal-step)))
21033       (setq number (+ number X-axis-label-spacing))
21034       (setq number-of-X-tics (1- number-of-X-tics)))))
21035 @end group
21036 @end smallexample
21038 @smallexample
21039 @group
21040 (defun print-X-axis (numbers-list horizontal-step)
21041   "Print X axis labels to length of NUMBERS-LIST.
21042 Optionally, HORIZONTAL-STEP, a positive integer,
21043 specifies how much an X  axis label increments for
21044 each column."
21045 @end group
21046 @group
21047 ;; Value of symbol-width and full-Y-label-width
21048 ;; are passed by `print-graph'.
21049   (let* ((leading-spaces
21050           (make-string full-Y-label-width ? ))
21051        ;; symbol-width @r{is provided by} graph-body-print
21052        (tic-width (* symbol-width X-axis-label-spacing))
21053        (X-length (length numbers-list))
21054 @end group
21055 @group
21056        (X-tic
21057         (concat
21058          (make-string
21059           ;; @r{Make a string of blanks.}
21060           (-  (* symbol-width X-axis-label-spacing)
21061               (length X-axis-tic-symbol))
21062           ? )
21063 @end group
21064 @group
21065          ;; @r{Concatenate blanks with tic symbol.}
21066          X-axis-tic-symbol))
21067        (tic-number
21068         (if (zerop (% X-length tic-width))
21069             (/ X-length tic-width)
21070           (1+ (/ X-length tic-width)))))
21071 @end group
21073 @group
21074     (print-X-axis-tic-line
21075      tic-number leading-spaces X-tic)
21076     (insert "\n")
21077     (print-X-axis-numbered-line
21078      tic-number leading-spaces horizontal-step)))
21079 @end group
21080 @end smallexample
21082 @smallexample
21083 @group
21084 (defun one-fiftieth (full-range)
21085   "Return list, each number of which is 1/50th previous."
21086  (mapcar '(lambda (arg) (/ arg 50)) full-range))
21087 @end group
21088 @end smallexample
21090 @smallexample
21091 @group
21092 (defun print-graph
21093   (numbers-list &optional vertical-step horizontal-step)
21094   "Print labelled bar graph of the NUMBERS-LIST.
21095 The numbers-list consists of the Y-axis values.
21096 @end group
21098 @group
21099 Optionally, VERTICAL-STEP, a positive integer,
21100 specifies how much a Y axis label increments for
21101 each line.  For example, a step of 5 means that
21102 each row is five units.
21103 @end group
21105 @group
21106 Optionally, HORIZONTAL-STEP, a positive integer,
21107 specifies how much an X  axis label increments for
21108 each column."
21109   (let* ((symbol-width (length graph-blank))
21110          ;; @code{height} @r{is both the largest number}
21111          ;; @r{and the number with the most digits.}
21112          (height (apply 'max numbers-list))
21113 @end group
21114 @group
21115          (height-of-top-line
21116           (if (zerop (% height Y-axis-label-spacing))
21117               height
21118             ;; @r{else}
21119             (* (1+ (/ height Y-axis-label-spacing))
21120                Y-axis-label-spacing)))
21121 @end group
21122 @group
21123          (vertical-step (or vertical-step 1))
21124          (full-Y-label-width
21125           (length
21126            (concat
21127             (number-to-string
21128              (* height-of-top-line vertical-step))
21129             Y-axis-tic))))
21130 @end group
21131 @group
21133     (print-Y-axis
21134      height-of-top-line full-Y-label-width vertical-step)
21135     (graph-body-print
21136         numbers-list height-of-top-line symbol-width)
21137     (print-X-axis numbers-list horizontal-step)))
21138 @end group
21139 @end smallexample
21140 @end ignore
21142 @page
21143 @node Final printed graph,  , Another Bug, Print Whole Graph
21144 @appendixsubsec The Printed Graph
21146 When made and installed, you can call the @code{print-graph} command
21147 like this:
21148 @sp 1
21150 @smallexample
21151 @group
21152 (print-graph fiftieth-list-for-graph 50 10)
21153 @end group
21154 @end smallexample
21155 @sp 1
21157 @noindent
21158 Here is the graph:
21159 @sp 2
21161 @smallexample
21162 @group
21163 1000 -  *
21164         **
21165         **
21166         **
21167         **
21168  750 -  ***
21169         ***
21170         ***
21171         ***
21172         ****
21173  500 - *****
21174        ******
21175        ******
21176        ******
21177        *******
21178  250 - ********
21179        *********                     *
21180        ***********                   *
21181        *************                 *
21182   50 - ***************** *           *
21183        |   |    |    |    |    |    |    |
21184       10  50  100  150  200  250  300  350
21185 @end group
21186 @end smallexample
21188 @sp 2
21190 @noindent
21191 The largest group of functions contain 10 -- 19 words and symbols each.
21193 @node Free Software and Free Manuals, GNU Free Documentation License, Full Graph, Top
21194 @appendix Free Software and Free Manuals
21196 @strong{by Richard M. Stallman}
21197 @sp 1
21199 The biggest deficiency in free operating systems is not in the
21200 software---it is the lack of good free manuals that we can include in
21201 these systems.  Many of our most important programs do not come with
21202 full manuals.  Documentation is an essential part of any software
21203 package; when an important free software package does not come with a
21204 free manual, that is a major gap.  We have many such gaps today.
21206 Once upon a time, many years ago, I thought I would learn Perl.  I got
21207 a copy of a free manual, but I found it hard to read.  When I asked
21208 Perl users about alternatives, they told me that there were better
21209 introductory manuals---but those were not free.
21211 Why was this?  The authors of the good manuals had written them for
21212 O'Reilly Associates, which published them with restrictive terms---no
21213 copying, no modification, source files not available---which exclude
21214 them from the free software community.
21216 That wasn't the first time this sort of thing has happened, and (to
21217 our community's great loss) it was far from the last.  Proprietary
21218 manual publishers have enticed a great many authors to restrict their
21219 manuals since then.  Many times I have heard a GNU user eagerly tell me
21220 about a manual that he is writing, with which he expects to help the
21221 GNU project---and then had my hopes dashed, as he proceeded to explain
21222 that he had signed a contract with a publisher that would restrict it
21223 so that we cannot use it.
21225 Given that writing good English is a rare skill among programmers, we
21226 can ill afford to lose manuals this way.
21228 @c (texinfo)uref
21229 (The Free Software Foundation
21230 @uref{http://www.gnu.org/doc/doc.html#DescriptionsOfGNUDocumentation, ,
21231 sells printed copies} of free @uref{http://www.gnu.org/doc/doc.html,
21232 GNU manuals}, too.)
21234 Free documentation, like free software, is a matter of freedom, not
21235 price.  The problem with these manuals was not that O'Reilly Associates
21236 charged a price for printed copies---that in itself is fine.  (The Free
21237 Software Foundation sells printed copies of free GNU manuals, too.)
21238 But GNU manuals are available in source code form, while these manuals
21239 are available only on paper.  GNU manuals come with permission to copy
21240 and modify; the Perl manuals do not.  These restrictions are the
21241 problems.
21243 The criterion for a free manual is pretty much the same as for free
21244 software: it is a matter of giving all users certain
21245 freedoms.  Redistribution (including commercial redistribution) must be
21246 permitted, so that the manual can accompany every copy of the program,
21247 on-line or on paper.  Permission for modification is crucial too.
21249 As a general rule, I don't believe that it is essential for people to
21250 have permission to modify all sorts of articles and books.  The issues
21251 for writings are not necessarily the same as those for software.  For
21252 example, I don't think you or I are obliged to give permission to
21253 modify articles like this one, which describe our actions and our
21254 views.
21256 But there is a particular reason why the freedom to modify is crucial
21257 for documentation for free software.  When people exercise their right
21258 to modify the software, and add or change its features, if they are
21259 conscientious they will change the manual too---so they can provide
21260 accurate and usable documentation with the modified program.  A manual
21261 which forbids programmers to be conscientious and finish the job, or
21262 more precisely requires them to write a new manual from scratch if
21263 they change the program, does not fill our community's needs.
21265 While a blanket prohibition on modification is unacceptable, some
21266 kinds of limits on the method of modification pose no problem.  For
21267 example, requirements to preserve the original author's copyright
21268 notice, the distribution terms, or the list of authors, are ok.  It is
21269 also no problem to require modified versions to include notice that
21270 they were modified, even to have entire sections that may not be
21271 deleted or changed, as long as these sections deal with nontechnical
21272 topics.  (Some GNU manuals have them.)
21274 These kinds of restrictions are not a problem because, as a practical
21275 matter, they don't stop the conscientious programmer from adapting the
21276 manual to fit the modified program.  In other words, they don't block
21277 the free software community from making full use of the manual.
21279 However, it must be possible to modify all the technical content of
21280 the manual, and then distribute the result in all the usual media,
21281 through all the usual channels; otherwise, the restrictions do block
21282 the community, the manual is not free, and so we need another manual.
21284 Unfortunately, it is often hard to find someone to write another
21285 manual when a proprietary manual exists.  The obstacle is that many
21286 users think that a proprietary manual is good enough---so they don't
21287 see the need to write a free manual.  They do not see that the free
21288 operating system has a gap that needs filling.
21290 Why do users think that proprietary manuals are good enough? Some have
21291 not considered the issue.  I hope this article will do something to
21292 change that.
21294 Other users consider proprietary manuals acceptable for the same
21295 reason so many people consider proprietary software acceptable: they
21296 judge in purely practical terms, not using freedom as a
21297 criterion.  These people are entitled to their opinions, but since
21298 those opinions spring from values which do not include freedom, they
21299 are no guide for those of us who do value freedom.
21301 Please spread the word about this issue.  We continue to lose manuals
21302 to proprietary publishing.  If we spread the word that proprietary
21303 manuals are not sufficient, perhaps the next person who wants to help
21304 GNU by writing documentation will realize, before it is too late, that
21305 he must above all make it free.
21307 We can also encourage commercial publishers to sell free, copylefted
21308 manuals instead of proprietary ones.  One way you can help this is to
21309 check the distribution terms of a manual before you buy it, and prefer
21310 copylefted manuals to non-copylefted ones.
21312 @sp 2
21313 @noindent
21314 Note: The Free Software Foundation maintains a page on its Web site
21315 that lists free books available from other publishers:@*
21316 @uref{http://www.gnu.org/doc/other-free-books.html}
21319 @node GNU Free Documentation License, Index, Free Software and Free Manuals, Top
21320 @appendix GNU Free Documentation License
21322 @cindex FDL, GNU Free Documentation License
21323 @center Version 1.2, November 2002
21325 @display
21326 Copyright @copyright{} 2000,2001,2002 Free Software Foundation, Inc.
21327 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA
21329 Everyone is permitted to copy and distribute verbatim copies
21330 of this license document, but changing it is not allowed.
21331 @end display
21333 @enumerate 0
21334 @item
21335 PREAMBLE
21337 The purpose of this License is to make a manual, textbook, or other
21338 functional and useful document @dfn{free} in the sense of freedom: to
21339 assure everyone the effective freedom to copy and redistribute it,
21340 with or without modifying it, either commercially or noncommercially.
21341 Secondarily, this License preserves for the author and publisher a way
21342 to get credit for their work, while not being considered responsible
21343 for modifications made by others.
21345 This License is a kind of ``copyleft'', which means that derivative
21346 works of the document must themselves be free in the same sense.  It
21347 complements the GNU General Public License, which is a copyleft
21348 license designed for free software.
21350 We have designed this License in order to use it for manuals for free
21351 software, because free software needs free documentation: a free
21352 program should come with manuals providing the same freedoms that the
21353 software does.  But this License is not limited to software manuals;
21354 it can be used for any textual work, regardless of subject matter or
21355 whether it is published as a printed book.  We recommend this License
21356 principally for works whose purpose is instruction or reference.
21358 @item
21359 APPLICABILITY AND DEFINITIONS
21361 This License applies to any manual or other work, in any medium, that
21362 contains a notice placed by the copyright holder saying it can be
21363 distributed under the terms of this License.  Such a notice grants a
21364 world-wide, royalty-free license, unlimited in duration, to use that
21365 work under the conditions stated herein.  The ``Document'', below,
21366 refers to any such manual or work.  Any member of the public is a
21367 licensee, and is addressed as ``you''.  You accept the license if you
21368 copy, modify or distribute the work in a way requiring permission
21369 under copyright law.
21371 A ``Modified Version'' of the Document means any work containing the
21372 Document or a portion of it, either copied verbatim, or with
21373 modifications and/or translated into another language.
21375 A ``Secondary Section'' is a named appendix or a front-matter section
21376 of the Document that deals exclusively with the relationship of the
21377 publishers or authors of the Document to the Document's overall
21378 subject (or to related matters) and contains nothing that could fall
21379 directly within that overall subject.  (Thus, if the Document is in
21380 part a textbook of mathematics, a Secondary Section may not explain
21381 any mathematics.)  The relationship could be a matter of historical
21382 connection with the subject or with related matters, or of legal,
21383 commercial, philosophical, ethical or political position regarding
21384 them.
21386 The ``Invariant Sections'' are certain Secondary Sections whose titles
21387 are designated, as being those of Invariant Sections, in the notice
21388 that says that the Document is released under this License.  If a
21389 section does not fit the above definition of Secondary then it is not
21390 allowed to be designated as Invariant.  The Document may contain zero
21391 Invariant Sections.  If the Document does not identify any Invariant
21392 Sections then there are none.
21394 The ``Cover Texts'' are certain short passages of text that are listed,
21395 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
21396 the Document is released under this License.  A Front-Cover Text may
21397 be at most 5 words, and a Back-Cover Text may be at most 25 words.
21399 A ``Transparent'' copy of the Document means a machine-readable copy,
21400 represented in a format whose specification is available to the
21401 general public, that is suitable for revising the document
21402 straightforwardly with generic text editors or (for images composed of
21403 pixels) generic paint programs or (for drawings) some widely available
21404 drawing editor, and that is suitable for input to text formatters or
21405 for automatic translation to a variety of formats suitable for input
21406 to text formatters.  A copy made in an otherwise Transparent file
21407 format whose markup, or absence of markup, has been arranged to thwart
21408 or discourage subsequent modification by readers is not Transparent.
21409 An image format is not Transparent if used for any substantial amount
21410 of text.  A copy that is not ``Transparent'' is called ``Opaque''.
21412 Examples of suitable formats for Transparent copies include plain
21413 @sc{ascii} without markup, Texinfo input format, La@TeX{} input
21414 format, @acronym{SGML} or @acronym{XML} using a publicly available
21415 @acronym{DTD}, and standard-conforming simple @acronym{HTML},
21416 PostScript or @acronym{PDF} designed for human modification.  Examples
21417 of transparent image formats include @acronym{PNG}, @acronym{XCF} and
21418 @acronym{JPG}.  Opaque formats include proprietary formats that can be
21419 read and edited only by proprietary word processors, @acronym{SGML} or
21420 @acronym{XML} for which the @acronym{DTD} and/or processing tools are
21421 not generally available, and the machine-generated @acronym{HTML},
21422 PostScript or @acronym{PDF} produced by some word processors for
21423 output purposes only.
21425 The ``Title Page'' means, for a printed book, the title page itself,
21426 plus such following pages as are needed to hold, legibly, the material
21427 this License requires to appear in the title page.  For works in
21428 formats which do not have any title page as such, ``Title Page'' means
21429 the text near the most prominent appearance of the work's title,
21430 preceding the beginning of the body of the text.
21432 A section ``Entitled XYZ'' means a named subunit of the Document whose
21433 title either is precisely XYZ or contains XYZ in parentheses following
21434 text that translates XYZ in another language.  (Here XYZ stands for a
21435 specific section name mentioned below, such as ``Acknowledgements'',
21436 ``Dedications'', ``Endorsements'', or ``History''.)  To ``Preserve the Title''
21437 of such a section when you modify the Document means that it remains a
21438 section ``Entitled XYZ'' according to this definition.
21440 The Document may include Warranty Disclaimers next to the notice which
21441 states that this License applies to the Document.  These Warranty
21442 Disclaimers are considered to be included by reference in this
21443 License, but only as regards disclaiming warranties: any other
21444 implication that these Warranty Disclaimers may have is void and has
21445 no effect on the meaning of this License.
21447 @item
21448 VERBATIM COPYING
21450 You may copy and distribute the Document in any medium, either
21451 commercially or noncommercially, provided that this License, the
21452 copyright notices, and the license notice saying this License applies
21453 to the Document are reproduced in all copies, and that you add no other
21454 conditions whatsoever to those of this License.  You may not use
21455 technical measures to obstruct or control the reading or further
21456 copying of the copies you make or distribute.  However, you may accept
21457 compensation in exchange for copies.  If you distribute a large enough
21458 number of copies you must also follow the conditions in section 3.
21460 You may also lend copies, under the same conditions stated above, and
21461 you may publicly display copies.
21463 @item
21464 COPYING IN QUANTITY
21466 If you publish printed copies (or copies in media that commonly have
21467 printed covers) of the Document, numbering more than 100, and the
21468 Document's license notice requires Cover Texts, you must enclose the
21469 copies in covers that carry, clearly and legibly, all these Cover
21470 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
21471 the back cover.  Both covers must also clearly and legibly identify
21472 you as the publisher of these copies.  The front cover must present
21473 the full title with all words of the title equally prominent and
21474 visible.  You may add other material on the covers in addition.
21475 Copying with changes limited to the covers, as long as they preserve
21476 the title of the Document and satisfy these conditions, can be treated
21477 as verbatim copying in other respects.
21479 If the required texts for either cover are too voluminous to fit
21480 legibly, you should put the first ones listed (as many as fit
21481 reasonably) on the actual cover, and continue the rest onto adjacent
21482 pages.
21484 If you publish or distribute Opaque copies of the Document numbering
21485 more than 100, you must either include a machine-readable Transparent
21486 copy along with each Opaque copy, or state in or with each Opaque copy
21487 a computer-network location from which the general network-using
21488 public has access to download using public-standard network protocols
21489 a complete Transparent copy of the Document, free of added material.
21490 If you use the latter option, you must take reasonably prudent steps,
21491 when you begin distribution of Opaque copies in quantity, to ensure
21492 that this Transparent copy will remain thus accessible at the stated
21493 location until at least one year after the last time you distribute an
21494 Opaque copy (directly or through your agents or retailers) of that
21495 edition to the public.
21497 It is requested, but not required, that you contact the authors of the
21498 Document well before redistributing any large number of copies, to give
21499 them a chance to provide you with an updated version of the Document.
21501 @item
21502 MODIFICATIONS
21504 You may copy and distribute a Modified Version of the Document under
21505 the conditions of sections 2 and 3 above, provided that you release
21506 the Modified Version under precisely this License, with the Modified
21507 Version filling the role of the Document, thus licensing distribution
21508 and modification of the Modified Version to whoever possesses a copy
21509 of it.  In addition, you must do these things in the Modified Version:
21511 @enumerate A
21512 @item
21513 Use in the Title Page (and on the covers, if any) a title distinct
21514 from that of the Document, and from those of previous versions
21515 (which should, if there were any, be listed in the History section
21516 of the Document).  You may use the same title as a previous version
21517 if the original publisher of that version gives permission.
21519 @item
21520 List on the Title Page, as authors, one or more persons or entities
21521 responsible for authorship of the modifications in the Modified
21522 Version, together with at least five of the principal authors of the
21523 Document (all of its principal authors, if it has fewer than five),
21524 unless they release you from this requirement.
21526 @item
21527 State on the Title page the name of the publisher of the
21528 Modified Version, as the publisher.
21530 @item
21531 Preserve all the copyright notices of the Document.
21533 @item
21534 Add an appropriate copyright notice for your modifications
21535 adjacent to the other copyright notices.
21537 @item
21538 Include, immediately after the copyright notices, a license notice
21539 giving the public permission to use the Modified Version under the
21540 terms of this License, in the form shown in the Addendum below.
21542 @item
21543 Preserve in that license notice the full lists of Invariant Sections
21544 and required Cover Texts given in the Document's license notice.
21546 @item
21547 Include an unaltered copy of this License.
21549 @item
21550 Preserve the section Entitled ``History'', Preserve its Title, and add
21551 to it an item stating at least the title, year, new authors, and
21552 publisher of the Modified Version as given on the Title Page.  If
21553 there is no section Entitled ``History'' in the Document, create one
21554 stating the title, year, authors, and publisher of the Document as
21555 given on its Title Page, then add an item describing the Modified
21556 Version as stated in the previous sentence.
21558 @item
21559 Preserve the network location, if any, given in the Document for
21560 public access to a Transparent copy of the Document, and likewise
21561 the network locations given in the Document for previous versions
21562 it was based on.  These may be placed in the ``History'' section.
21563 You may omit a network location for a work that was published at
21564 least four years before the Document itself, or if the original
21565 publisher of the version it refers to gives permission.
21567 @item
21568 For any section Entitled ``Acknowledgements'' or ``Dedications'', Preserve
21569 the Title of the section, and preserve in the section all the
21570 substance and tone of each of the contributor acknowledgements and/or
21571 dedications given therein.
21573 @item
21574 Preserve all the Invariant Sections of the Document,
21575 unaltered in their text and in their titles.  Section numbers
21576 or the equivalent are not considered part of the section titles.
21578 @item
21579 Delete any section Entitled ``Endorsements''.  Such a section
21580 may not be included in the Modified Version.
21582 @item
21583 Do not retitle any existing section to be Entitled ``Endorsements'' or
21584 to conflict in title with any Invariant Section.
21586 @item
21587 Preserve any Warranty Disclaimers.
21588 @end enumerate
21590 If the Modified Version includes new front-matter sections or
21591 appendices that qualify as Secondary Sections and contain no material
21592 copied from the Document, you may at your option designate some or all
21593 of these sections as invariant.  To do this, add their titles to the
21594 list of Invariant Sections in the Modified Version's license notice.
21595 These titles must be distinct from any other section titles.
21597 You may add a section Entitled ``Endorsements'', provided it contains
21598 nothing but endorsements of your Modified Version by various
21599 parties---for example, statements of peer review or that the text has
21600 been approved by an organization as the authoritative definition of a
21601 standard.
21603 You may add a passage of up to five words as a Front-Cover Text, and a
21604 passage of up to 25 words as a Back-Cover Text, to the end of the list
21605 of Cover Texts in the Modified Version.  Only one passage of
21606 Front-Cover Text and one of Back-Cover Text may be added by (or
21607 through arrangements made by) any one entity.  If the Document already
21608 includes a cover text for the same cover, previously added by you or
21609 by arrangement made by the same entity you are acting on behalf of,
21610 you may not add another; but you may replace the old one, on explicit
21611 permission from the previous publisher that added the old one.
21613 The author(s) and publisher(s) of the Document do not by this License
21614 give permission to use their names for publicity for or to assert or
21615 imply endorsement of any Modified Version.
21617 @item
21618 COMBINING DOCUMENTS
21620 You may combine the Document with other documents released under this
21621 License, under the terms defined in section 4 above for modified
21622 versions, provided that you include in the combination all of the
21623 Invariant Sections of all of the original documents, unmodified, and
21624 list them all as Invariant Sections of your combined work in its
21625 license notice, and that you preserve all their Warranty Disclaimers.
21627 The combined work need only contain one copy of this License, and
21628 multiple identical Invariant Sections may be replaced with a single
21629 copy.  If there are multiple Invariant Sections with the same name but
21630 different contents, make the title of each such section unique by
21631 adding at the end of it, in parentheses, the name of the original
21632 author or publisher of that section if known, or else a unique number.
21633 Make the same adjustment to the section titles in the list of
21634 Invariant Sections in the license notice of the combined work.
21636 In the combination, you must combine any sections Entitled ``History''
21637 in the various original documents, forming one section Entitled
21638 ``History''; likewise combine any sections Entitled ``Acknowledgements'',
21639 and any sections Entitled ``Dedications''.  You must delete all
21640 sections Entitled ``Endorsements.''
21642 @item
21643 COLLECTIONS OF DOCUMENTS
21645 You may make a collection consisting of the Document and other documents
21646 released under this License, and replace the individual copies of this
21647 License in the various documents with a single copy that is included in
21648 the collection, provided that you follow the rules of this License for
21649 verbatim copying of each of the documents in all other respects.
21651 You may extract a single document from such a collection, and distribute
21652 it individually under this License, provided you insert a copy of this
21653 License into the extracted document, and follow this License in all
21654 other respects regarding verbatim copying of that document.
21656 @item
21657 AGGREGATION WITH INDEPENDENT WORKS
21659 A compilation of the Document or its derivatives with other separate
21660 and independent documents or works, in or on a volume of a storage or
21661 distribution medium, is called an ``aggregate'' if the copyright
21662 resulting from the compilation is not used to limit the legal rights
21663 of the compilation's users beyond what the individual works permit.
21664 When the Document is included in an aggregate, this License does not
21665 apply to the other works in the aggregate which are not themselves
21666 derivative works of the Document.
21668 If the Cover Text requirement of section 3 is applicable to these
21669 copies of the Document, then if the Document is less than one half of
21670 the entire aggregate, the Document's Cover Texts may be placed on
21671 covers that bracket the Document within the aggregate, or the
21672 electronic equivalent of covers if the Document is in electronic form.
21673 Otherwise they must appear on printed covers that bracket the whole
21674 aggregate.
21676 @item
21677 TRANSLATION
21679 Translation is considered a kind of modification, so you may
21680 distribute translations of the Document under the terms of section 4.
21681 Replacing Invariant Sections with translations requires special
21682 permission from their copyright holders, but you may include
21683 translations of some or all Invariant Sections in addition to the
21684 original versions of these Invariant Sections.  You may include a
21685 translation of this License, and all the license notices in the
21686 Document, and any Warranty Disclaimers, provided that you also include
21687 the original English version of this License and the original versions
21688 of those notices and disclaimers.  In case of a disagreement between
21689 the translation and the original version of this License or a notice
21690 or disclaimer, the original version will prevail.
21692 If a section in the Document is Entitled ``Acknowledgements'',
21693 ``Dedications'', or ``History'', the requirement (section 4) to Preserve
21694 its Title (section 1) will typically require changing the actual
21695 title.
21697 @item
21698 TERMINATION
21700 You may not copy, modify, sublicense, or distribute the Document except
21701 as expressly provided for under this License.  Any other attempt to
21702 copy, modify, sublicense or distribute the Document is void, and will
21703 automatically terminate your rights under this License.  However,
21704 parties who have received copies, or rights, from you under this
21705 License will not have their licenses terminated so long as such
21706 parties remain in full compliance.
21708 @item
21709 FUTURE REVISIONS OF THIS LICENSE
21711 The Free Software Foundation may publish new, revised versions
21712 of the GNU Free Documentation License from time to time.  Such new
21713 versions will be similar in spirit to the present version, but may
21714 differ in detail to address new problems or concerns.  See
21715 @uref{http://www.gnu.org/copyleft/}.
21717 Each version of the License is given a distinguishing version number.
21718 If the Document specifies that a particular numbered version of this
21719 License ``or any later version'' applies to it, you have the option of
21720 following the terms and conditions either of that specified version or
21721 of any later version that has been published (not as a draft) by the
21722 Free Software Foundation.  If the Document does not specify a version
21723 number of this License, you may choose any version ever published (not
21724 as a draft) by the Free Software Foundation.
21725 @end enumerate
21727 @page
21728 @appendixsubsec ADDENDUM: How to use this License for your documents
21730 To use this License in a document you have written, include a copy of
21731 the License in the document and put the following copyright and
21732 license notices just after the title page:
21734 @smallexample
21735 @group
21736 Copyright (C)  @var{year}  @var{your name}.
21737 Permission is granted to copy, distribute and/or modify this document
21738 under the terms of the GNU Free Documentation License, Version 1.2
21739 or any later version published by the Free Software Foundation;
21740 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
21741 A copy of the license is included in the section entitled ``GNU
21742 Free Documentation License''.
21743 @end group
21744 @end smallexample
21746 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
21747 replace the ``with...Texts.'' line with this:
21749 @smallexample
21750 @group
21751 with the Invariant Sections being @var{list their titles}, with
21752 the Front-Cover Texts being @var{list}, and with the Back-Cover Texts
21753 being @var{list}.
21754 @end group
21755 @end smallexample
21757 If you have Invariant Sections without Cover Texts, or some other
21758 combination of the three, merge those two alternatives to suit the
21759 situation.
21761 If your document contains nontrivial examples of program code, we
21762 recommend releasing these examples in parallel under your choice of
21763 free software license, such as the GNU General Public License,
21764 to permit their use in free software.
21766 @node Index, About the Author, GNU Free Documentation License, Top
21767 @comment  node-name,  next,  previous,  up
21768 @unnumbered Index
21770 @ignore
21771 MENU ENTRY: NODE NAME.
21772 @end ignore
21774 @printindex cp
21776 @iftex
21777 @c Place biographical information on right-hand (verso) page
21779 @tex
21780 \ifodd\pageno
21781     \par\vfill\supereject
21782     \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21783     \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21784     \page\hbox{}\page
21785 \else
21786     \par\vfill\supereject
21787     \par\vfill\supereject
21788     \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21789     \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21790     \page\hbox{}\page
21791     \page\hbox{}\page
21793 @end tex
21795 @page
21796 @w{ }
21798 @c ================ Biographical information ================
21800 @w{ }
21801 @sp 8
21802 @center About the Author
21803 @sp 1
21804 @end iftex
21806 @ifnottex
21807 @node About the Author,  , Index, Top
21808 @unnumbered About the Author
21809 @end ifnottex
21811 @quotation
21812 Robert J. Chassell has worked with GNU Emacs since 1985.  He writes
21813 and edits, teaches Emacs and Emacs Lisp, and speaks throughout the
21814 world on software freedom.  Chassell was a founding Director and
21815 Treasurer of the Free Software Foundation, Inc.  He is co-author of
21816 the @cite{Texinfo} manual, and has edited more than a dozen other
21817 books.  He graduated from Cambridge University, in England.  He has an
21818 abiding interest in social and economic history and flies his own
21819 airplane.
21820 @end quotation
21822 @page
21823 @w{ }
21825 @c Prevent page number on blank verso, so eject it first.
21826 @tex
21827 \par\vfill\supereject
21828 @end tex
21830 @iftex
21831 @headings off
21832 @evenheading @thispage @| @| @thistitle
21833 @oddheading            @| @| @thispage
21834 @end iftex
21836 @bye
21838 @ignore
21839    arch-tag: da1a2154-531f-43a8-8e33-fc7faad10acf
21840 @end ignore