(transient-mark-mode, line-number-mode, column-number-mode): Undo the
[emacs.git] / lispintro / emacs-lisp-intro.texi
blob8ea4a2ee7feb5833b73bdcd24520c188469a064a
1 \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.07
25 @set update-date 2002 Aug 23
27 @ignore
28  ## Summary of shell commands to create various output formats:
30     ## Info output
31     makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
33     ## DVI output
34     texi2dvi emacs-lisp-intro.texi
36     ## HTML output
37     makeinfo --html --no-split --verbose emacs-lisp-intro.texi
39     ## Plain text output
40     makeinfo --fill-column=70 --no-split --paragraph-indent=0 \
41     --verbose --no-headers --output=emacs-lisp-intro.txt emacs-lisp-intro.texi
43     ## DocBook output
44     makeinfo --docbook --no-split --paragraph-indent=0 \
45     --verbose emacs-lisp-intro.texi
47     ## XML output
48     makeinfo --xml --no-split --paragraph-indent=0 \
49     --verbose emacs-lisp-intro.texi
51 @end ignore
53 @c ================ Included Figures ================
55 @c Set  print-postscript-figures  if you print PostScript figures.
56 @c If you clear this, the ten figures will be printed as ASCII diagrams.
57 @c (This is not relevant to Info, since Info only handles ASCII.)
58 @c Your site may require editing changes to print PostScript; in this
59 @c case, search for `print-postscript-figures' and make appropriate changes.
62 @c ================ How to Create an Info file ================
64 @c If you have `makeinfo' installed, run the following command
66 @c     makeinfo emacs-lisp-intro.texi
68 @c or, if you want a single, large Info file, and no paragraph indents:
69 @c     makeinfo --no-split --paragraph-indent=0 --verbose emacs-lisp-intro.texi
71 @c After creating the Info file, edit your Info `dir' file, if the
72 @c `dircategory' section below does not enable your system to
73 @c install the manual automatically.
74 @c (The `dir' file is often in the `/usr/local/info/' directory.)
76 @c ================ How to Create an HTML file ================
78 @c To convert to HTML format
79 @c     makeinfo --html --no-split --verbose emacs-lisp-intro.texi
81 @c ================ How to Print a Book in Various Sizes ================
83 @c This book can be printed in any of three different sizes.
84 @c In the above header, set @-commands appropriately.
86 @c     7 by 9.25 inches:
87 @c              @smallbook
88 @c              @clear largebook
90 @c     8.5 by 11 inches:
91 @c              @c smallbook
92 @c              @set largebook
94 @c     European A4 size paper:
95 @c              @c smallbook
96 @c              @afourpaper
97 @c              @set largebook
99 @c ================ How to Typeset and Print ================
101 @c If you do not include PostScript figures, run either of the
102 @c following command sequences, or similar commands suited to your
103 @c system:
105 @c     texi2dvi emacs-lisp-intro.texi
106 @c     lpr -d emacs-lisp-intro.dvi
108 @c or else:
110 @c     tex emacs-lisp-intro.texi
111 @c     texindex emacs-lisp-intro.??
112 @c     tex emacs-lisp-intro.texi
113 @c     lpr -d emacs-lisp-intro.dvi
115 @c If you include the PostScript figures, and you have old software,
116 @c you may need to convert the .dvi file to a .ps file before
117 @c printing.  Run either of the following command sequences, or one
118 @c similar:
120 @c     dvips -f < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
122 @c or else:
124 @c     postscript -p < emacs-lisp-intro.dvi > emacs-lisp-intro.ps
127 @c (Note: if you edit the book so as to change the length of the
128 @c table of contents, you may have to change the value of `pageno' below.)
130 @c ================ End of Formatting Sections ================
132 @c For next or subsequent edition:
133 @c   create function using with-output-to-temp-buffer
134 @c   create a major mode, with keymaps
135 @c   run an asynchronous process, like grep or diff
137 @c For 8.5 by 11 inch format: do not use such a small amount of
138 @c whitespace between paragraphs as smallbook format
139 @ifset largebook
140 @tex
141 \global\parskip 6pt plus 1pt
142 @end tex
143 @end ifset
145 @c For all sized formats:  print within-book cross
146 @c reference with ``...''  rather than [...]
147 @tex
148 % Need following so comma appears after section numbers.
149 \global\def\Ysectionnumberandtype{%
150 \ifnum\secno=0 \putwordChapter\xreftie\the\chapno, \space %
151 \else \ifnum \subsecno=0 \putwordSection\xreftie\the\chapno.\the\secno, \space %
152 \else \ifnum \subsubsecno=0 %
153 \putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno, \space %
154 \else %
155 \putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno.\the\subsubsecno, \space%
156 \fi \fi \fi }
158 \global\def\Yappendixletterandtype{%
159 \ifnum\secno=0 \putwordAppendix\xreftie'char\the\appendixno{}, \space%
160 \else \ifnum \subsecno=0 \putwordSection\xreftie'char\the\appendixno.\the\secno, \space %
161 \else \ifnum \subsubsecno=0 %
162 \putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno, \space %
163 \else %
164 \putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno.\the\subsubsecno, \space %
165 \fi \fi \fi }
167 \global\def\xrefX[#1,#2,#3,#4,#5,#6]{\begingroup
168   \def\printedmanual{\ignorespaces #5}%
169   \def\printednodename{\ignorespaces #3}%
170   \setbox1=\hbox{\printedmanual}%
171   \setbox0=\hbox{\printednodename}%
172   \ifdim \wd0 = 0pt
173     % No printed node name was explicitly given.
174     \ifx\SETxref-automatic-section-title\relax %
175       % Use the actual chapter/section title appear inside
176       % the square brackets.  Use the real section title if we have it.
177       \ifdim \wd1>0pt%
178         % It is in another manual, so we don't have it.
179         \def\printednodename{\ignorespaces #1}%
180       \else
181         \ifhavexrefs
182           % We know the real title if we have the xref values.
183           \def\printednodename{\refx{#1-title}}%
184         \else
185           % Otherwise just copy the Info node name.
186           \def\printednodename{\ignorespaces #1}%
187         \fi%
188       \fi
189       \def\printednodename{#1-title}%
190     \else
191       % Use the node name inside the square brackets.
192       \def\printednodename{\ignorespaces #1}%
193     \fi
194   \fi
195   %
196   % If we use \unhbox0 and \unhbox1 to print the node names, TeX does not
197   % insert empty discretionaries after hyphens, which means that it will
198   % not find a line break at a hyphen in a node names.  Since some manuals
199   % are best written with fairly long node names, containing hyphens, this
200   % is a loss.  Therefore, we give the text of the node name again, so it
201   % is as if TeX is seeing it for the first time.
202   \ifdim \wd1 > 0pt
203     \putwordsection{} ``\printednodename'' in \cite{\printedmanual}%
204   \else
205     % _ (for example) has to be the character _ for the purposes of the
206     % control sequence corresponding to the node, but it has to expand
207     % into the usual \leavevmode...\vrule stuff for purposes of
208     % printing.  So we \turnoffactive for the \refx-snt, back on for the
209     % printing, back off for the \refx-pg.
210     {\turnoffactive \refx{#1-snt}{}}%
211 %    \space [\printednodename],\space                % <= original
212 %    \putwordsection{} ``\printednodename'',\space
213     ``\printednodename'',\space
214     \turnoffactive \putwordpage\tie\refx{#1-pg}{}%
215   \fi
216 \endgroup}
217 @end tex
219 @c ----------------------------------------------------
221 @dircategory Emacs
222 @direntry
223 * Emacs Lisp Intro: (eintr).
224                         A simple introduction to Emacs Lisp programming.
225 @end direntry
227 @copying
228 This is an introduction to @cite{Programming in Emacs Lisp}, for
229 people who are not programmers.
231 Edition @value{edition-number}, @value{update-date}
233 Copyright @copyright{} 1990, 1991, 1992, 1993, 1994, 1995, 1997, 2001, 2002 Free Software Foundation, Inc.
234 @sp 2
236 Published by the Free Software Foundation, Inc.@*
237 59 Temple Place, Suite 330@*
238 Boston, MA 02111-1307 USA@*
240 Edition @value{edition-number}, @value{update-date}
242 @c Printed copies are available for $30 each.@*
243 ISBN 1-882114-43-4
245 Permission is granted to copy, distribute and/or modify this document
246 under the terms of the GNU Free Documentation License, Version 1.1 or
247 any later version published by the Free Software Foundation; there
248 being no Invariant Section, with the Front-Cover Texts being ``A GNU
249 Manual'', and with the Back-Cover Texts as in (a) below.  A copy of
250 the license is included in the section entitled ``GNU Free
251 Documentation License''.
253 (a) The FSF's Back-Cover Text is: ``You have freedom to copy and
254 modify this GNU Manual, like GNU software.  Copies published by the
255 Free Software Foundation raise funds for GNU development.''
256 @end copying
258 @c half title; two lines here, so do not use `shorttitlepage'
259 @tex
260 {\begingroup%
261     \hbox{}\vskip 1.5in \chaprm \centerline{An Introduction to}%
262         \endgroup}%
263 {\begingroup\hbox{}\vskip 0.25in \chaprm%
264         \centerline{Programming in Emacs Lisp}%
265         \endgroup\page\hbox{}\page}
266 @end tex
268 @titlepage
269 @sp 6
270 @center @titlefont{An Introduction to}
271 @sp 2
272 @center @titlefont{Programming in Emacs Lisp}
273 @sp 2
274 @center Second Edition
275 @sp 4
276 @center by Robert J. Chassell
278 @page
279 @vskip 0pt plus 1filll
280 @insertcopying
281 @end titlepage
283 @iftex
284 @headings off
285 @evenheading @thispage @| @| @thischapter
286 @oddheading @thissection @| @| @thispage
287 @end iftex
289 @ifnothtml
291 @c Keep T.O.C. short by tightening up.
292 @ifset largebook
293 @tex
294 \global\parskip 2pt plus 1pt
295 \global\advance\baselineskip by -1pt
296 @end tex
297 @end ifset
299 @shortcontents
300 @contents
302 @ifset largebook
303 @tex
304 \global\parskip 6pt plus 1pt
305 \global\advance\baselineskip by 1pt
306 @end tex
307 @end ifset
309 @end ifnothtml
311 @c >>>> Set pageno appropriately <<<<
313 @c The first page of the Preface is a roman numeral; it is the first
314 @c right handed page after the Table of Contents; hence the following
315 @c setting must be for an odd negative number.
317 @c if largebook, there are 8 pages in Table of Contents
318 @ifset largebook
319 @iftex
320 @pageno = -9
321 @end iftex
322 @end ifset
324 @c if smallbook, there are 10 pages in Table of Contents
325 @ifclear largebook
326 @iftex
327 @pageno = -11
328 @end iftex
329 @end ifclear
331 @ifnottex
332 @node Top, Preface, (dir), (dir)
333 @top An Introduction to Programming in Emacs Lisp
335 @insertcopying
337 This master menu first lists each chapter and index; then it lists
338 every node in every chapter.
339 @end ifnottex
341 @menu
342 * Preface::                     What to look for.
343 * List Processing::             What is Lisp?
344 * Practicing Evaluation::       Running several programs.
345 * Writing Defuns::              How to write function definitions.
346 * Buffer Walk Through::         Exploring a few buffer-related functions.
347 * More Complex::                A few, even more complex functions.
348 * Narrowing & Widening::        Restricting your and Emacs attention to
349                                     a region.
350 * car cdr & cons::              Fundamental functions in Lisp.
351 * Cutting & Storing Text::      Removing text and saving it.
352 * List Implementation::         How lists are implemented in the computer.
353 * Yanking::                     Pasting stored text.
354 * Loops & Recursion::           How to repeat a process.
355 * Regexp Search::               Regular expression searches.
356 * Counting Words::              A review of repetition and regexps.
357 * Words in a defun::            Counting words in a @code{defun}.
358 * Readying a Graph::            A prototype graph printing function.
359 * Emacs Initialization::        How to write a @file{.emacs} file.
360 * Debugging::                   How to run the Emacs Lisp debuggers.
361 * Conclusion::                  Now you have the basics.
362 * the-the::                     An appendix: how to find reduplicated words.
363 * Kill Ring::                   An appendix: how the kill ring works.
364 * Full Graph::                  How to create a graph with labelled axes.
365 * GNU Free Documentation License::
366 * Index::
367 * About the Author::
369 @detailmenu
370  --- The Detailed Node Listing ---
372 Preface
374 * Why::                         Why learn Emacs Lisp?
375 * On Reading this Text::        Read, gain familiarity, pick up habits....
376 * Who You Are::                 For whom this is written.
377 * Lisp History::
378 * Note for Novices::            You can read this as a novice.
379 * Thank You::
381 List Processing
383 * Lisp Lists::                  What are lists?
384 * Run a Program::               Any list in Lisp is a program ready to run.
385 * Making Errors::               Generating an error message.
386 * Names & Definitions::         Names of symbols and function definitions.
387 * Lisp Interpreter::            What the Lisp interpreter does.
388 * Evaluation::                  Running a program.
389 * Variables::                   Returning a value from a variable.
390 * Arguments::                   Passing information to a function.
391 * set & setq::                  Setting the value of a variable.
392 * Summary::                     The major points.
393 * Error Message Exercises::
395 Lisp Lists
397 * Numbers Lists::               List have numbers, other lists, in them.
398 * Lisp Atoms::                  Elemental entities.
399 * Whitespace in Lists::         Formating lists to be readable.
400 * Typing Lists::                How GNU Emacs helps you type lists.
402 The Lisp Interpreter
404 * Complications::               Variables, Special forms, Lists within.
405 * Byte Compiling::              Specially processing code for speed.
407 Evaluation
409 * Evaluating Inner Lists::      Lists within lists...
411 Variables
413 * fill-column Example::
414 * Void Function::               The error message for a symbol
415                                   without a function.
416 * Void Variable::               The error message for a symbol without a value.
418 Arguments
420 * Data types::                  Types of data passed to a function.
421 * Args as Variable or List::    An argument can be the value
422                                   of a variable or list.
423 * Variable Number of Arguments::  Some functions may take a
424                                   variable number of arguments.
425 * Wrong Type of Argument::      Passing an argument of the wrong type
426                                   to a function.
427 * message::                     A useful function for sending messages.
429 Setting the Value of a Variable
431 * Using set::                   Setting values.
432 * Using setq::                  Setting a quoted value.
433 * Counting::                    Using @code{setq} to count.
435 Practicing Evaluation
437 * How to Evaluate::             Typing editing commands or @kbd{C-x C-e}
438                                   causes evaluation.
439 * Buffer Names::                Buffers and files are different.
440 * Getting Buffers::             Getting a buffer itself, not merely its name.
441 * Switching Buffers::           How to change to another buffer.
442 * Buffer Size & Locations::     Where point is located and the size of
443                                 the buffer.
444 * Evaluation Exercise::
446 How To Write Function Definitions
448 * Primitive Functions::
449 * defun::                       The @code{defun} special form.
450 * Install::                     Install a function definition.
451 * Interactive::                 Making a function interactive.
452 * Interactive Options::         Different options for @code{interactive}.
453 * Permanent Installation::      Installing code permanently.
454 * let::                         Creating and initializing local variables.
455 * if::                          What if?
456 * else::                        If--then--else expressions.
457 * Truth & Falsehood::           What Lisp considers false and true.
458 * save-excursion::              Keeping track of point, mark, and buffer.
459 * Review::
460 * defun Exercises::
462 Install a Function Definition
464 * Effect of installation::
465 * Change a defun::              How to change a function definition.
467 Make a Function Interactive
469 * Interactive multiply-by-seven::  An overview.
470 * multiply-by-seven in detail::  The interactive version.
472 @code{let}
474 * Prevent confusion::
475 * Parts of let Expression::
476 * Sample let Expression::
477 * Uninitialized let Variables::
479 The @code{if} Special Form
481 * if in more detail::
482 * type-of-animal in detail::    An example of an @code{if} expression.
484 Truth and Falsehood in Emacs Lisp
486 * nil explained::               @code{nil} has two meanings.
488 @code{save-excursion}
490 * Point and mark::              A review of various locations.
491 * Template for save-excursion::
493 A Few Buffer--Related Functions
495 * Finding More::                How to find more information.
496 * simplified-beginning-of-buffer::  Shows @code{goto-char},
497                                 @code{point-min}, and @code{push-mark}.
498 * mark-whole-buffer::           Almost the same as @code{beginning-of-buffer}.
499 * append-to-buffer::            Uses @code{save-excursion} and
500                                 @code{insert-buffer-substring}.
501 * Buffer Related Review::       Review.
502 * Buffer Exercises::
504 The Definition of @code{mark-whole-buffer}
506 * mark-whole-buffer overview::
507 * Body of mark-whole-buffer::   Only three lines of code.
509 The Definition of @code{append-to-buffer}
511 * append-to-buffer overview::
512 * append interactive::          A two part interactive expression.
513 * append-to-buffer body::       Incorporates a @code{let} expression.
514 * append save-excursion::       How the @code{save-excursion} works.
516 A Few More Complex Functions
518 * copy-to-buffer::              With @code{set-buffer}, @code{get-buffer-create}.
519 * insert-buffer::               Read-only, and with @code{or}.
520 * beginning-of-buffer::         Shows @code{goto-char},
521                                 @code{point-min}, and @code{push-mark}.
522 * Second Buffer Related Review::
523 * optional Exercise::
525 The Definition of @code{insert-buffer}
527 * insert-buffer code::
528 * insert-buffer interactive::   When you can read, but not write.
529 * insert-buffer body::          The body has an @code{or} and a @code{let}.
530 * if & or::                     Using an @code{if} instead of an @code{or}.
531 * Insert or::                   How the @code{or} expression works.
532 * Insert let::                  Two @code{save-excursion} expressions.
534 The Interactive Expression in @code{insert-buffer}
536 * Read-only buffer::            When a buffer cannot be modified.
537 * b for interactive::           An existing buffer or else its name.
539 Complete Definition of @code{beginning-of-buffer}
541 * Optional Arguments::
542 * beginning-of-buffer opt arg::  Example with optional argument.
543 * beginning-of-buffer complete::
545 @code{beginning-of-buffer} with an Argument
547 * Disentangle beginning-of-buffer::
548 * Large buffer case::
549 * Small buffer case::
551 Narrowing and Widening
553 * Narrowing advantages::        The advantages of narrowing
554 * save-restriction::            The @code{save-restriction} special form.
555 * what-line::                   The number of the line that point is on.
556 * narrow Exercise::
558 @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
560 * Strange Names::               An historical aside: why the strange names?
561 * car & cdr::                   Functions for extracting part of a list.
562 * cons::                        Constructing a list.
563 * nthcdr::                      Calling @code{cdr} repeatedly.
564 * nth::
565 * setcar::                      Changing the first element of a list.
566 * setcdr::                      Changing the rest of a list.
567 * cons Exercise::
569 @code{cons}
571 * Build a list::
572 * length::                      How to find the length of a list.
574 Cutting and Storing Text
576 * Storing Text::                Text is stored in a list.
577 * zap-to-char::                 Cutting out text up to a character.
578 * kill-region::                 Cutting text out of a region.
579 * Digression into C::           Minor note on C programming language macros.
580 * defvar::                      How to give a variable an initial value.
581 * copy-region-as-kill::         A definition for copying text.
582 * cons & search-fwd Review::
583 * search Exercises::
585 @code{zap-to-char}
587 * Complete zap-to-char::        The complete implementation.
588 * zap-to-char interactive::     A three part interactive expression.
589 * zap-to-char body::            A short overview.
590 * search-forward::              How to search for a string.
591 * progn::                       The @code{progn} special form.
592 * Summing up zap-to-char::      Using @code{point} and @code{search-forward}.
594 @code{kill-region}
596 * Complete kill-region::        The function definition.
597 * condition-case::              Dealing with a problem.
598 * delete-and-extract-region::   Doing the work.
600 Initializing a Variable with @code{defvar}
602 * See variable current value::
603 * defvar and asterisk::         An old-time convention.
605 @code{copy-region-as-kill}
607 * Complete copy-region-as-kill::  The complete function definition.
608 * copy-region-as-kill body::    The body of @code{copy-region-as-kill}.
610 The Body of @code{copy-region-as-kill}
612 * last-command & this-command::
613 * kill-append function::
614 * kill-new function::
616 How Lists are Implemented
618 * Lists diagrammed::
619 * Symbols as Chest::            Exploring a powerful metaphor.
620 * List Exercise::
622 Yanking Text Back
624 * Kill Ring Overview::          The kill ring is a list.
625 * kill-ring-yank-pointer::      The @code{kill-ring-yank-pointer} variable.
626 * yank nthcdr Exercises::
628 Loops and Recursion
630 * while::                       Causing a stretch of code to repeat.
631 * dolist dotimes::
632 * Recursion::                   Causing a function to call itself.
633 * Looping exercise::
635 @code{while}
637 * Looping with while::          Repeat so long as test returns true.
638 * Loop Example::                A @code{while} loop that uses a list.
639 * print-elements-of-list::      Uses @code{while}, @code{car}, @code{cdr}.
640 * Incrementing Loop::           A loop with an incrementing counter.
641 * Decrementing Loop::           A loop with a decrementing counter.
643 A Loop with an Incrementing Counter
645 * Incrementing Example::        Counting pebbles in a triangle.
646 * Inc Example parts::           The parts of the function definition.
647 * Inc Example altogether::      Putting the function definition together.
649 Loop with a Decrementing Counter
651 * Decrementing Example::        More pebbles on the beach.
652 * Dec Example parts::           The parts of the function definition.
653 * Dec Example altogether::      Putting the function definition together.
655 Save your time: @code{dolist} and @code{dotimes}
657 * dolist::
658 * dotimes::
660 Recursion
662 * Building Robots::             Same model, different serial number ...
663 * Recursive Definition Parts::  Walk until you stop ...
664 * Recursion with list::         Using a list as the test whether to recurse.
665 * Recursive triangle function::
666 * Recursion with cond::
667 * Recursive Patterns::          Often used templates.
668 * No Deferment::                Don't store up work ...
669 * No deferment solution::
671 Recursion in Place of a Counter
673 * Recursive Example arg of 1 or 2::
674 * Recursive Example arg of 3 or 4::
676 Recursive Patterns
678 * Every::
679 * Accumulate::
680 * Keep::
682 Regular Expression Searches
684 * sentence-end::                The regular expression for @code{sentence-end}.
685 * re-search-forward::           Very similar to @code{search-forward}.
686 * forward-sentence::            A straightforward example of regexp search.
687 * forward-paragraph::           A somewhat complex example.
688 * etags::                       How to create your own @file{TAGS} table.
689 * Regexp Review::
690 * re-search Exercises::
692 @code{forward-sentence}
694 * Complete forward-sentence::
695 * fwd-sentence while loops::    Two @code{while} loops.
696 * fwd-sentence re-search::      A regular expression search.
698 @code{forward-paragraph}: a Goldmine of Functions
700 * forward-paragraph in brief::  Key parts of the function definition.
701 * fwd-para let::                The @code{let*} expression.
702 * fwd-para while::              The forward motion @code{while} loop.
703 * fwd-para between paragraphs::  Movement between paragraphs.
704 * fwd-para within paragraph::   Movement within paragraphs.
705 * fwd-para no fill prefix::     When there is no fill prefix.
706 * fwd-para with fill prefix::   When there is a fill prefix.
707 * fwd-para summary::            Summary of @code{forward-paragraph} code.
709 Counting: Repetition and Regexps
711 * Why Count Words::
712 * count-words-region::          Use a regexp, but find a problem.
713 * recursive-count-words::       Start with case of no words in region.
714 * Counting Exercise::
716 The @code{count-words-region} Function
718 * Design count-words-region::   The definition using a @code{while} loop.
719 * Whitespace Bug::              The Whitespace Bug in @code{count-words-region}.
721 Counting Words in a @code{defun}
723 * Divide and Conquer::
724 * Words and Symbols::           What to count?
725 * Syntax::                      What constitutes a word or symbol?
726 * count-words-in-defun::        Very like @code{count-words}.
727 * Several defuns::              Counting several defuns in a file.
728 * Find a File::                 Do you want to look at a file?
729 * lengths-list-file::           A list of the lengths of many definitions.
730 * Several files::               Counting in definitions in different files.
731 * Several files recursively::   Recursively counting in different files.
732 * Prepare the data::            Prepare the data for display in a graph.
734 Count Words in @code{defuns} in Different Files
736 * lengths-list-many-files::     Return a list of the lengths of defuns.
737 * append::                      Attach one list to another.
739 Prepare the Data for Display in a Graph
741 * Sorting::                     Sorting lists.
742 * Files List::                  Making a list of files.
743 * Counting function definitions::
745 Readying a Graph
747 * Columns of a graph::
748 * graph-body-print::            How to print the body of a graph.
749 * recursive-graph-body-print::
750 * Printed Axes::
751 * Line Graph Exercise::
753 Your @file{.emacs} File
755 * Default Configuration::
756 * Site-wide Init::              You can write site-wide init files.
757 * defcustom::                   Emacs will write code for you.
758 * Beginning a .emacs File::     How to write a @code{.emacs file}.
759 * Text and Auto-fill::          Automatically wrap lines.
760 * Mail Aliases::                Use abbreviations for email addresses.
761 * Indent Tabs Mode::            Don't use tabs with @TeX{}
762 * Keybindings::                 Create some personal keybindings.
763 * Keymaps::                     More about key binding.
764 * Loading Files::               Load (i.e., evaluate) files automatically.
765 * Autoload::                    Make functions available.
766 * Simple Extension::            Define a function; bind it to a key.
767 * X11 Colors::                  Colors in version 19 in X.
768 * Miscellaneous::
769 * Mode Line::                   How to customize your mode line.
771 Debugging
773 * debug::                       How to use the built-in debugger.
774 * debug-on-entry::              Start debugging when you call a function.
775 * debug-on-quit::               Start debugging when you quit with @kbd{C-g}.
776 * edebug::                      How to use Edebug, a source level debugger.
777 * Debugging Exercises::
779 Handling the Kill Ring
781 * rotate-yank-pointer::         Move a pointer along a list and around.
782 * yank::                        Paste a copy of a clipped element.
783 * yank-pop::                    Insert first element pointed to.
785 The @code{rotate-yank-pointer} Function
787 * Understanding rotate-yk-ptr::
788 * rotate-yk-ptr body::          The body of @code{rotate-yank-pointer}.
790 The Body of @code{rotate-yank-pointer}
792 * Digression concerning error::  How to mislead humans, but not computers.
793 * rotate-yk-ptr else-part::     The else-part of the @code{if} expression.
794 * Remainder Function::          The remainder, @code{%}, function.
795 * rotate-yk-ptr remainder::     Using @code{%} in @code{rotate-yank-pointer}.
796 * kill-rng-yk-ptr last elt::    Pointing to the last element.
798 @code{yank}
800 * rotate-yk-ptr arg::           Pass the argument to @code{rotate-yank-pointer}.
801 * rotate-yk-ptr negative arg::  Pass a negative argument.
803 A Graph with Labelled Axes
805 * Labelled Example::
806 * print-graph Varlist::         @code{let} expression in @code{print-graph}.
807 * print-Y-axis::                Print a label for the vertical axis.
808 * print-X-axis::                Print a horizontal label.
809 * Print Whole Graph::           The function to print a complete graph.
811 The @code{print-Y-axis} Function
813 * Height of label::             What height for the Y axis?
814 * Compute a Remainder::         How to compute the remainder of a division.
815 * Y Axis Element::              Construct a line for the Y axis.
816 * Y-axis-column::               Generate a list of Y axis labels.
817 * print-Y-axis Penultimate::    A not quite final version.
819 The @code{print-X-axis} Function
821 * Similarities differences::    Much like @code{print-Y-axis}, but not exactly.
822 * X Axis Tic Marks::            Create tic marks for the horizontal axis.
824 Printing the Whole Graph
826 * The final version::           A few changes.
827 * Test print-graph::            Run a short test.
828 * Graphing words in defuns::    Executing the final code.
829 * lambda::                      How to write an anonymous function.
830 * mapcar::                      Apply a function to elements of a list.
831 * Another Bug::                 Yet another bug @dots{} most insidious.
832 * Final printed graph::         The graph itself!
834 @end detailmenu
835 @end menu
837 @node Preface, List Processing, Top, Top
838 @comment  node-name,  next,  previous,  up
839 @unnumbered Preface
841 Most of the GNU Emacs integrated environment is written in the programming
842 language called Emacs Lisp.  The code written in this programming
843 language is the software---the sets of instructions---that tell the
844 computer what to do when you give it commands.  Emacs is designed so
845 that you can write new code in Emacs Lisp and easily install it as an
846 extension to the editor.
848 (GNU Emacs is sometimes called an ``extensible editor'', but it does
849 much more than provide editing capabilities.  It is better to refer to
850 Emacs as an ``extensible computing environment''.  However, that
851 phrase is quite a mouthful.  It is easier to refer to Emacs simply as
852 an editor.  Moreover, everything you do in Emacs---find the Mayan date
853 and phases of the moon, simplify polynomials, debug code, manage
854 files, read letters, write books---all these activities are kinds of
855 editing in the most general sense of the word.)
857 @menu
858 * Why::                         Why learn Emacs Lisp?
859 * On Reading this Text::        Read, gain familiarity, pick up habits....
860 * Who You Are::                 For whom this is written.
861 * Lisp History::
862 * Note for Novices::            You can read this as a novice.
863 * Thank You::
864 @end menu
866 @node Why, On Reading this Text, Preface, Preface
867 @ifnottex
868 @unnumberedsec Why Study Emacs Lisp?
869 @end ifnottex
871 Although Emacs Lisp is usually thought of in association only with Emacs,
872 it is a full computer programming language.  You can use Emacs Lisp as
873 you would any other programming language.
875 Perhaps you want to understand programming; perhaps you want to extend
876 Emacs; or perhaps you want to become a programmer.  This introduction to
877 Emacs Lisp is designed to get you started: to guide you in learning the
878 fundamentals of programming, and more importantly, to show you how you
879 can teach yourself to go further.
881 @node On Reading this Text, Who You Are, Why, Preface
882 @comment  node-name,  next,  previous,  up
883 @unnumberedsec On Reading this Text
885 All through this document, you will see little sample programs you can
886 run inside of Emacs.  If you read this document in Info inside of GNU
887 Emacs, you can run the programs as they appear.  (This is easy to do and
888 is explained when the examples are presented.)  Alternatively, you can
889 read this introduction as a printed book while sitting beside a computer
890 running Emacs.  (This is what I like to do; I like printed books.)  If
891 you don't have a running Emacs beside you, you can still read this book,
892 but in this case, it is best to treat it as a novel or as a travel guide
893 to a country not yet visited: interesting, but not the same as being
894 there.
896 Much of this introduction is dedicated to walk-throughs or guided tours
897 of code used in GNU Emacs.  These tours are designed for two purposes:
898 first, to give you familiarity with real, working code (code you use
899 every day); and, second, to give you familiarity with the way Emacs
900 works.  It is interesting to see how a working environment is
901 implemented.
902 Also, I
903 hope that you will pick up the habit of browsing through source code.
904 You can learn from it and mine it for ideas.  Having GNU Emacs is like
905 having a dragon's cave of treasures.
907 In addition to learning about Emacs as an editor and Emacs Lisp as a
908 programming language, the examples and guided tours will give you an
909 opportunity to get acquainted with Emacs as a Lisp programming
910 environment.  GNU Emacs supports programming and provides tools that
911 you will want to become comfortable using, such as @kbd{M-.} (the key
912 which invokes the @code{find-tag} command).  You will also learn about
913 buffers and other objects that are part of the environment.
914 Learning about these features of Emacs is like learning new routes
915 around your home town.
917 @ignore
918 In addition, I have written several programs as extended examples.
919 Although these are examples, the programs are real.  I use them.
920 Other people use them.  You may use them.  Beyond the fragments of
921 programs used for illustrations, there is very little in here that is
922 `just for teaching purposes'; what you see is used.  This is a great
923 advantage of Emacs Lisp: it is easy to learn to use it for work.
924 @end ignore
926 Finally, I hope to convey some of the skills for using Emacs to
927 learn aspects of programming that you don't know.  You can often use
928 Emacs to help you understand what puzzles you or to find out how to do
929 something new.  This self-reliance is not only a pleasure, but an
930 advantage.
932 @node Who You Are, Lisp History, On Reading this Text, Preface
933 @comment  node-name,  next,  previous,  up
934 @unnumberedsec For Whom This is Written
936 This text is written as an elementary introduction for people who are
937 not programmers.  If you are a programmer, you may not be satisfied with
938 this primer.  The reason is that you may have become expert at reading
939 reference manuals and be put off by the way this text is organized.
941 An expert programmer who reviewed this text said to me:
943 @quotation
944 @i{I prefer to learn from reference manuals.  I ``dive into'' each
945 paragraph, and ``come up for air'' between paragraphs.}
947 @i{When I get to the end of a paragraph, I assume that that subject is
948 done, finished, that I know everything I need (with the
949 possible exception of the case when the next paragraph starts talking
950 about it in more detail).  I expect that a well written reference manual
951 will not have a lot of redundancy, and that it will have excellent
952 pointers to the (one) place where the information I want is.}
953 @end quotation
955 This introduction is not written for this person!
957 Firstly, I try to say everything at least three times: first, to
958 introduce it; second, to show it in context; and third, to show it in a
959 different context, or to review it.
961 Secondly, I hardly ever put all the information about a subject in one
962 place, much less in one paragraph.  To my way of thinking, that imposes
963 too heavy a burden on the reader.  Instead I try to explain only what
964 you need to know at the time.  (Sometimes I include a little extra
965 information so you won't be surprised later when the additional
966 information is formally introduced.)
968 When you read this text, you are not expected to learn everything the
969 first time.  Frequently, you need only make, as it were, a `nodding
970 acquaintance' with some of the items mentioned.  My hope is that I have
971 structured the text and given you enough hints that you will be alert to
972 what is important, and concentrate on it.
974 You will need to ``dive into'' some paragraphs; there is no other way
975 to read them.  But I have tried to keep down the number of such
976 paragraphs.  This book is intended as an approachable hill, rather than
977 as a daunting mountain.
979 This introduction to @cite{Programming in Emacs Lisp} has a companion
980 document,
981 @iftex
982 @cite{The GNU Emacs Lisp Reference Manual}.
983 @end iftex
984 @ifnottex
985 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
986 Emacs Lisp Reference Manual}.
987 @end ifnottex
988 The reference manual has more detail than this introduction.  In the
989 reference manual, all the information about one topic is concentrated
990 in one place.  You should turn to it if you are like the programmer
991 quoted above.  And, of course, after you have read this
992 @cite{Introduction}, you will find the @cite{Reference Manual} useful
993 when you are writing your own programs.
995 @node Lisp History, Note for Novices, Who You Are, Preface
996 @unnumberedsec Lisp History
997 @cindex Lisp history
999 Lisp was first developed in the late 1950s at the Massachusetts
1000 Institute of Technology for research in artificial intelligence.  The
1001 great power of the Lisp language makes it superior for other purposes as
1002 well, such as writing editor commands and integrated environments.
1004 @cindex Maclisp
1005 @cindex Common Lisp
1006 GNU Emacs Lisp is largely inspired by Maclisp, which was written at MIT
1007 in the 1960s.  It is somewhat inspired by Common Lisp, which became a
1008 standard in the 1980s.  However, Emacs Lisp is much simpler than Common
1009 Lisp.  (The standard Emacs distribution contains an optional extensions
1010 file, @file{cl.el}, that adds many Common Lisp features to Emacs Lisp.)
1012 @node Note for Novices, Thank You, Lisp History, Preface
1013 @comment  node-name,  next,  previous,  up
1014 @unnumberedsec A Note for Novices
1016 If you don't know GNU Emacs, you can still read this document
1017 profitably.  However, I recommend you learn Emacs, if only to learn to
1018 move around your computer screen.  You can teach yourself how to use
1019 Emacs with the on-line tutorial.  To use it, type @kbd{C-h t}.  (This
1020 means you press and release the @key{CTRL} key and the @kbd{h} at the
1021 same time, and then press and release @kbd{t}.)
1023 Also, I often refer to one of Emacs' standard commands by listing the
1024 keys which you press to invoke the command and then giving the name of
1025 the command in parentheses, like this: @kbd{M-C-\}
1026 (@code{indent-region}).  What this means is that the
1027 @code{indent-region} command is customarily invoked by typing
1028 @kbd{M-C-\}.  (You can, if you wish, change the keys that are typed to
1029 invoke the command; this is called @dfn{rebinding}.  @xref{Keymaps, ,
1030 Keymaps}.)  The abbreviation @kbd{M-C-\} means that you type your
1031 @key{META} key, @key{CTRL} key and @key{\} key all at the same time.
1032 (On many modern keyboards the @key{META} key is labelled
1033 @key{ALT}.)
1034 Sometimes a combination like this is called a keychord, since it is
1035 similar to the way you play a chord on a piano.  If your keyboard does
1036 not have a @key{META} key, the @key{ESC} key prefix is used in place
1037 of it.  In this case, @kbd{M-C-\} means that you press and release your
1038 @key{ESC} key and then type the @key{CTRL} key and the @key{\} key at
1039 the same time.  But usually @kbd{M-C-\} means press the @key{CTRL} key
1040 along with the key that is labelled @key{ALT} and, at the same time,
1041 press the @key{\} key.
1043 In addition to typing a lone keychord, you can prefix what you type
1044 with @kbd{C-u}, which is called the `universal argument'.  The
1045 @kbd{C-u} keychord passes an argument to the subsequent command.
1046 Thus, to indent a region of plain text by 6 spaces, mark the region,
1047 and then type @w{@kbd{C-u 6 M-C-\}}.  (If you do not specify a number,
1048 Emacs either passes the number 4 to the command or otherwise runs the
1049 command differently than it would otherwise.)  @xref{Arguments, ,
1050 Numeric Arguments, emacs, The GNU Emacs Manual}.
1052 If you are reading this in Info using GNU Emacs, you can read through
1053 this whole document just by pressing the space bar, @key{SPC}.
1054 (To learn about Info, type @kbd{C-h i} and then select Info.)
1056 A note on terminology:  when I use the word Lisp alone, I often am
1057 referring to the various dialects of Lisp in general, but when I speak
1058 of Emacs Lisp, I am referring to GNU Emacs Lisp in particular.
1060 @node Thank You,  , Note for Novices, Preface
1061 @comment  node-name,  next,  previous,  up
1062 @unnumberedsec Thank You
1064 My thanks to all who helped me with this book.  My especial thanks to
1065 @r{Jim Blandy}, @r{Noah Friedman}, @w{Jim Kingdon}, @r{Roland
1066 McGrath}, @w{Frank Ritter}, @w{Randy Smith}, @w{Richard M.@:
1067 Stallman}, and @w{Melissa Weisshaus}.  My thanks also go to both
1068 @w{Philip Johnson} and @w{David Stampe} for their patient
1069 encouragement.  My mistakes are my own.
1071 @flushright
1072 Robert J. Chassell
1073 @end flushright
1075 @c ================ Beginning of main text ================
1077 @c Start main text on right-hand (verso) page
1079 @tex
1080 \par\vfill\supereject
1081 \headings off
1082 \ifodd\pageno
1083     \par\vfill\supereject
1084 \else
1085     \par\vfill\supereject
1086     \page\hbox{}\page
1087     \par\vfill\supereject
1089 @end tex
1091 @iftex
1092 @headings off
1093 @evenheading @thispage @| @| @thischapter
1094 @oddheading @thissection @| @| @thispage
1095 @pageno = 1
1096 @end iftex
1098 @node List Processing, Practicing Evaluation, Preface, Top
1099 @comment  node-name,  next,  previous,  up
1100 @chapter List Processing
1102 To the untutored eye, Lisp is a strange programming language.  In Lisp
1103 code there are parentheses everywhere.  Some people even claim that the
1104 name stands for `Lots of Isolated Silly Parentheses'.  But the claim is
1105 unwarranted.  Lisp stands for LISt Processing, and the programming
1106 language handles @emph{lists} (and lists of lists) by putting them
1107 between parentheses.  The parentheses mark the boundaries of the list.
1108 Sometimes a list is preceded by a single apostrophe or quotation mark,
1109 @samp{'}.  Lists are the basis of Lisp.
1111 @menu
1112 * Lisp Lists::                  What are lists?
1113 * Run a Program::               Any list in Lisp is a program ready to run.
1114 * Making Errors::               Generating an error message.
1115 * Names & Definitions::         Names of symbols and function definitions.
1116 * Lisp Interpreter::            What the Lisp interpreter does.
1117 * Evaluation::                  Running a program.
1118 * Variables::                   Returning a value from a variable.
1119 * Arguments::                   Passing information to a function.
1120 * set & setq::                  Setting the value of a variable.
1121 * Summary::                     The major points.
1122 * Error Message Exercises::
1123 @end menu
1125 @node Lisp Lists, Run a Program, List Processing, List Processing
1126 @comment  node-name,  next,  previous,  up
1127 @section Lisp Lists
1128 @cindex Lisp Lists
1130 In Lisp, a list looks like this: @code{'(rose violet daisy buttercup)}.
1131 This list is preceded by a single apostrophe.  It could just as well be
1132 written as follows, which looks more like the kind of list you are likely
1133 to be familiar with:
1135 @smallexample
1136 @group
1137 '(rose
1138   violet
1139   daisy
1140   buttercup)
1141 @end group
1142 @end smallexample
1144 @noindent
1145 The elements of this list are the names of the four different flowers,
1146 separated from each other by whitespace and surrounded by parentheses,
1147 like flowers in a field with a stone wall around them.
1148 @cindex Flowers in a field
1150 @menu
1151 * Numbers Lists::               List have numbers, other lists, in them.
1152 * Lisp Atoms::                  Elemental entities.
1153 * Whitespace in Lists::         Formating lists to be readable.
1154 * Typing Lists::                How GNU Emacs helps you type lists.
1155 @end menu
1157 @node Numbers Lists, Lisp Atoms, Lisp Lists, Lisp Lists
1158 @ifnottex
1159 @unnumberedsubsec Numbers, Lists inside of Lists
1160 @end ifnottex
1162 Lists can also have numbers in them, as in this list: @code{(+ 2 2)}.
1163 This list has a plus-sign, @samp{+}, followed by two @samp{2}s, each
1164 separated by whitespace.
1166 In Lisp, both data and programs are represented the same way; that is,
1167 they are both lists of words, numbers, or other lists, separated by
1168 whitespace and surrounded by parentheses.  (Since a program looks like
1169 data, one program may easily serve as data for another; this is a very
1170 powerful feature of Lisp.)  (Incidentally, these two parenthetical
1171 remarks are @emph{not} Lisp lists, because they contain @samp{;} and
1172 @samp{.} as punctuation marks.)
1174 @need 1200
1175 Here is another list, this time with a list inside of it:
1177 @smallexample
1178 '(this list has (a list inside of it))
1179 @end smallexample
1181 The components of this list are the words @samp{this}, @samp{list},
1182 @samp{has}, and the list @samp{(a list inside of it)}.  The interior
1183 list is made up of the words @samp{a}, @samp{list}, @samp{inside},
1184 @samp{of}, @samp{it}.
1186 @node Lisp Atoms, Whitespace in Lists, Numbers Lists, Lisp Lists
1187 @comment  node-name,  next,  previous,  up
1188 @subsection Lisp Atoms
1189 @cindex Lisp Atoms
1191 In Lisp, what we have been calling words are called @dfn{atoms}.  This
1192 term comes from the historical meaning of the word atom, which means
1193 `indivisible'.  As far as Lisp is concerned, the words we have been
1194 using in the lists cannot be divided into any smaller parts and still
1195 mean the same thing as part of a program; likewise with numbers and
1196 single character symbols like @samp{+}.  On the other hand, unlike an
1197 atom, a list can be split into parts.  (@xref{car cdr & cons, ,
1198 @code{car} @code{cdr} & @code{cons} Fundamental Functions}.)
1200 In a list, atoms are separated from each other by whitespace.  They can be
1201 right next to a parenthesis.
1203 @cindex @samp{empty list} defined
1204 Technically speaking, a list in Lisp consists of parentheses surrounding
1205 atoms separated by whitespace or surrounding other lists or surrounding
1206 both atoms and other lists.  A list can have just one atom in it or
1207 have nothing in it at all.  A list with nothing in it looks like this:
1208 @code{()}, and is called the @dfn{empty list}.  Unlike anything else, an
1209 empty list is considered both an atom and a list at the same time.
1211 @cindex Symbolic expressions, introduced
1212 @cindex @samp{expression} defined
1213 @cindex @samp{form} defined
1214 The printed representation of both atoms and lists are called
1215 @dfn{symbolic expressions} or, more concisely, @dfn{s-expressions}.
1216 The word @dfn{expression} by itself can refer to either the printed
1217 representation, or to the atom or list as it is held internally in the
1218 computer.  Often, people use the term @dfn{expression}
1219 indiscriminately.  (Also, in many texts, the word @dfn{form} is used
1220 as a synonym for expression.)
1222 Incidentally, the atoms that make up our universe were named such when
1223 they were thought to be indivisible; but it has been found that physical
1224 atoms are not indivisible.  Parts can split off an atom or it can
1225 fission into two parts of roughly equal size.  Physical atoms were named
1226 prematurely, before their truer nature was found.  In Lisp, certain
1227 kinds of atom, such as an array, can be separated into parts; but the
1228 mechanism for doing this is different from the mechanism for splitting a
1229 list.  As far as list operations are concerned, the atoms of a list are
1230 unsplittable.
1232 As in English, the meanings of the component letters of a Lisp atom
1233 are different from the meaning the letters make as a word.  For
1234 example, the word for the South American sloth, the @samp{ai}, is
1235 completely different from the two words, @samp{a}, and @samp{i}.
1237 There are many kinds of atom in nature but only a few in Lisp: for
1238 example, @dfn{numbers}, such as 37, 511, or 1729, and @dfn{symbols}, such
1239 as @samp{+}, @samp{foo}, or @samp{forward-line}.  The words we have
1240 listed in the examples above are all symbols.  In everyday Lisp
1241 conversation, the word ``atom'' is not often used, because programmers
1242 usually try to be more specific about what kind of atom they are dealing
1243 with.  Lisp programming is mostly about symbols (and sometimes numbers)
1244 within lists.  (Incidentally, the preceding three word parenthetical
1245 remark is a proper list in Lisp, since it consists of atoms, which in
1246 this case are symbols, separated by whitespace and enclosed by
1247 parentheses, without any non-Lisp punctuation.)
1249 @need 1250
1250 In addition, text between double quotation marks---even sentences or
1251 paragraphs---is an atom.  Here is an example:
1252 @cindex Text between double quotation marks
1254 @smallexample
1255 '(this list includes "text between quotation marks.")
1256 @end smallexample
1258 @cindex @samp{string} defined
1259 @noindent
1260 In Lisp, all of the quoted text including the punctuation mark and the
1261 blank spaces is a single atom.  This kind of atom is called a
1262 @dfn{string} (for `string of characters') and is the sort of thing that
1263 is used for messages that a computer can print for a human to read.
1264 Strings are a different kind of atom than numbers or symbols and are
1265 used differently.
1267 @node Whitespace in Lists, Typing Lists, Lisp Atoms, Lisp Lists
1268 @comment  node-name,  next,  previous,  up
1269 @subsection Whitespace in Lists
1270 @cindex Whitespace in lists
1272 @need 1200
1273 The amount of whitespace in a list does not matter.  From the point of view
1274 of the Lisp language,
1276 @smallexample
1277 @group
1278 '(this list
1279    looks like this)
1280 @end group
1281 @end smallexample
1283 @need 800
1284 @noindent
1285 is exactly the same as this:
1287 @smallexample
1288 '(this list looks like this)
1289 @end smallexample
1291 Both examples show what to Lisp is the same list, the list made up of
1292 the symbols @samp{this}, @samp{list}, @samp{looks}, @samp{like}, and
1293 @samp{this} in that order.
1295 Extra whitespace and newlines are designed to make a list more readable
1296 by humans.  When Lisp reads the expression, it gets rid of all the extra
1297 whitespace (but it needs to have at least one space between atoms in
1298 order to tell them apart.)
1300 Odd as it seems, the examples we have seen cover almost all of what Lisp
1301 lists look like!  Every other list in Lisp looks more or less like one
1302 of these examples, except that the list may be longer and more complex.
1303 In brief, a list is between parentheses, a string is between quotation
1304 marks, a symbol looks like a word, and a number looks like a number.
1305 (For certain situations, square brackets, dots and a few other special
1306 characters may be used; however, we will go quite far without them.)
1308 @node Typing Lists,  , Whitespace in Lists, Lisp Lists
1309 @comment  node-name,  next,  previous,  up
1310 @subsection GNU Emacs Helps You Type Lists
1311 @cindex Help typing lists
1312 @cindex Formatting help
1314 When you type a Lisp expression in GNU Emacs using either Lisp
1315 Interaction mode or Emacs Lisp mode, you have available to you several
1316 commands to format the Lisp expression so it is easy to read.  For
1317 example, pressing the @key{TAB} key automatically indents the line the
1318 cursor is on by the right amount.  A command to properly indent the
1319 code in a region is customarily bound to @kbd{M-C-\}.  Indentation is
1320 designed so that you can see which elements of a list belong to which
1321 list---elements of a sub-list are indented more than the elements of
1322 the enclosing list.
1324 In addition, when you type a closing parenthesis, Emacs momentarily
1325 jumps the cursor back to the matching opening parenthesis, so you can
1326 see which one it is.  This is very useful, since every list you type
1327 in Lisp must have its closing parenthesis match its opening
1328 parenthesis.  (@xref{Major Modes, , Major Modes, emacs, The GNU Emacs
1329 Manual}, for more information about Emacs' modes.)
1331 @node Run a Program, Making Errors, Lisp Lists, List Processing
1332 @comment  node-name,  next,  previous,  up
1333 @section Run a Program
1334 @cindex Run a program
1335 @cindex Program, running one
1337 @cindex @samp{evaluate} defined
1338 A list in Lisp---any list---is a program ready to run.  If you run it
1339 (for which the Lisp jargon is @dfn{evaluate}), the computer will do one
1340 of three things: do nothing except return to you the list itself; send
1341 you an error message; or, treat the first symbol in the list as a
1342 command to do something.  (Usually, of course, it is the last of these
1343 three things that you really want!)
1345 @c use code for the single apostrophe, not samp.
1346 The single apostrophe, @code{'}, that I put in front of some of the
1347 example lists in preceding sections is called a @dfn{quote}; when it
1348 precedes a list, it tells Lisp to do nothing with the list, other than
1349 take it as it is written.  But if there is no quote preceding a list,
1350 the first item of the list is special: it is a command for the computer
1351 to obey.  (In Lisp, these commands are called @emph{functions}.)  The list
1352 @code{(+ 2 2)} shown above did not have a quote in front of it, so Lisp
1353 understands that the @code{+} is an instruction to do something with the
1354 rest of the list: add the numbers that follow.
1356 @need 1250
1357 If you are reading this inside of GNU Emacs in Info, here is how you can
1358 evaluate such a list:  place your cursor immediately after the right
1359 hand parenthesis of the following list and then type @kbd{C-x C-e}:
1361 @smallexample
1362 (+ 2 2)
1363 @end smallexample
1365 @c use code for the number four, not samp.
1366 @noindent
1367 You will see the number @code{4} appear in the echo area.  (In the
1368 jargon, what you have just done is ``evaluate the list.''  The echo area
1369 is the line at the bottom of the screen that displays or ``echoes''
1370 text.)  Now try the same thing with a quoted list:  place the cursor
1371 right after the following list and type @kbd{C-x C-e}:
1373 @smallexample
1374 '(this is a quoted list)
1375 @end smallexample
1377 @noindent
1378 You will see @code{(this is a quoted list)} appear in the echo area.
1380 @cindex Lisp interpreter, explained
1381 @cindex Interpreter, Lisp, explained
1382 In both cases, what you are doing is giving a command to the program
1383 inside of GNU Emacs called the @dfn{Lisp interpreter}---giving the
1384 interpreter a command to evaluate the expression.  The name of the Lisp
1385 interpreter comes from the word for the task done by a human who comes
1386 up with the meaning of an expression---who ``interprets'' it.
1388 You can also evaluate an atom that is not part of a list---one that is
1389 not surrounded by parentheses; again, the Lisp interpreter translates
1390 from the humanly readable expression to the language of the computer.
1391 But before discussing this (@pxref{Variables}), we will discuss what the
1392 Lisp interpreter does when you make an error.
1394 @node Making Errors, Names & Definitions, Run a Program, List Processing
1395 @comment  node-name,  next,  previous,  up
1396 @section Generate an Error Message
1397 @cindex Generate an error message
1398 @cindex Error message generation
1400 Partly so you won't worry if you do it accidentally, we will now give
1401 a command to the Lisp interpreter that generates an error message.
1402 This is a harmless activity; and indeed, we will often try to generate
1403 error messages intentionally.  Once you understand the jargon, error
1404 messages can be informative.  Instead of being called ``error''
1405 messages, they should be called ``help'' messages.  They are like
1406 signposts to a traveller in a strange country; deciphering them can be
1407 hard, but once understood, they can point the way.
1409 The error message is generated by a built-in GNU Emacs debugger.  We
1410 will `enter the debugger'.  You get out of the debugger by typing @code{q}.
1412 What we will do is evaluate a list that is not quoted and does not
1413 have a meaningful command as its first element.  Here is a list almost
1414 exactly the same as the one we just used, but without the single-quote
1415 in front of it.  Position the cursor right after it and type @kbd{C-x
1416 C-e}:
1418 @smallexample
1419 (this is an unquoted list)
1420 @end smallexample
1422 @noindent
1423 What you see depends on which version of Emacs you are running.  GNU
1424 Emacs version 21 provides more information than version 20 and before.
1425 First, the more recent result of generating an error; then the
1426 earlier, version 20 result.
1428 @need 1250
1429 @noindent
1430 In GNU Emacs version 21, a @file{*Backtrace*} window will open up and
1431 you will see the following in it:
1433 @smallexample
1434 @group
1435 ---------- Buffer: *Backtrace* ----------
1436 Debugger entered--Lisp error: (void-function this)
1437   (this is an unquoted list)
1438   eval((this is an unquoted list))
1439   eval-last-sexp-1(nil)
1440   eval-last-sexp(nil)
1441   call-interactively(eval-last-sexp)
1442 ---------- Buffer: *Backtrace* ----------
1443 @end group
1444 @end smallexample
1446 @need 1200
1447 @noindent
1448 Your cursor will be in this window (you may have to wait a few seconds
1449 before it becomes visible).  To quit the debugger and make the
1450 debugger window go away, type:
1452 @smallexample
1454 @end smallexample
1456 @noindent
1457 Please type @kbd{q} right now, so you become confident that you can
1458 get out of the debugger.  Then, type @kbd{C-x C-e} again to re-enter
1461 @cindex @samp{function} defined
1462 Based on what we already know, we can almost read this error message.
1464 You read the @file{*Backtrace*} buffer from the bottom up; it tells
1465 you what Emacs did.  When you typed @kbd{C-x C-e}, you made an
1466 interactive call to the command @code{eval-last-sexp}.  @code{eval} is
1467 an abbreviation for `evaluate' and @code{sexp} is an abbreviation for
1468 `symbolic expression'.  The command means `evaluate last symbolic
1469 expression', which is the expression just before your cursor.
1471 Each line above tells you what the Lisp interpreter evaluated next.
1472 The most recent action is at the top.  The buffer is called the
1473 @file{*Backtrace*} buffer because it enables you to track Emacs
1474 backwards.
1476 @need 800
1477 At the top of the @file{*Backtrace*} buffer, you see the line:
1479 @smallexample
1480 Debugger entered--Lisp error: (void-function this)
1481 @end smallexample
1483 @noindent
1484 The Lisp interpreter tried to evaluate the first atom of the list, the
1485 word @samp{this}.  It is this action that generated the error message
1486 @samp{void-function this}.
1488 The message contains the words @samp{void-function} and @samp{this}.
1490 @cindex @samp{function} defined
1491 The word @samp{function} was mentioned once before.  It is a very
1492 important word.  For our purposes, we can define it by saying that a
1493 @dfn{function} is a set of instructions to the computer that tell the
1494 computer to do something.
1496 Now we can begin to understand the error message: @samp{void-function
1497 this}.  The function (that is, the word @samp{this}) does not have a
1498 definition of any set of instructions for the computer to carry out.
1500 The slightly odd word, @samp{void-function}, is designed to cover the
1501 way Emacs Lisp is implemented, which is that when a symbol does not
1502 have a function definition attached to it, the place that should
1503 contain the instructions is `void'.
1505 On the other hand, since we were able to add 2 plus 2 successfully, by
1506 evaluating @code{(+ 2 2)}, we can infer that the symbol @code{+} must
1507 have a set of instructions for the computer to obey and those
1508 instructions must be to add the numbers that follow the @code{+}.
1510 @need 1250
1511 In GNU Emacs version 20, and in earlier versions, you will see only
1512 one line of error message; it will appear in the echo area and look
1513 like this:
1515 @smallexample
1516 Symbol's function definition is void:@: this
1517 @end smallexample
1519 @noindent
1520 (Also, your terminal may beep at you---some do, some don't; and others
1521 blink.  This is just a device to get your attention.)  The message goes
1522 away as soon as you type another key, even just to move the cursor.
1524 We know the meaning of the word @samp{Symbol}.  It refers to the first
1525 atom of the list, the word @samp{this}.  The word @samp{function}
1526 refers to the instructions that tell the computer what to do.
1527 (Technically, the symbol tells the computer where to find the
1528 instructions, but this is a complication we can ignore for the
1529 moment.)
1531 The error message can be understood: @samp{Symbol's function
1532 definition is void:@: this}.  The symbol (that is, the word
1533 @samp{this}) lacks instructions for the computer to carry out.
1535 @node Names & Definitions, Lisp Interpreter, Making Errors, List Processing
1536 @comment  node-name,  next,  previous,  up
1537 @section Symbol Names and Function Definitions
1538 @cindex Symbol names
1540 We can articulate another characteristic of Lisp based on what we have
1541 discussed so far---an important characteristic: a symbol, like
1542 @code{+}, is not itself the set of instructions for the computer to
1543 carry out.  Instead, the symbol is used, perhaps temporarily, as a way
1544 of locating the definition or set of instructions.  What we see is the
1545 name through which the instructions can be found.  Names of people
1546 work the same way.  I can be referred to as @samp{Bob}; however, I am
1547 not the letters @samp{B}, @samp{o}, @samp{b} but am the consciousness
1548 consistently associated with a particular life-form.  The name is not
1549 me, but it can be used to refer to me.
1551 In Lisp, one set of instructions can be attached to several names.
1552 For example, the computer instructions for adding numbers can be
1553 linked to the symbol @code{plus} as well as to the symbol @code{+}
1554 (and are in some dialects of Lisp).  Among humans, I can be referred
1555 to as @samp{Robert} as well as @samp{Bob} and by other words as well.
1557 On the other hand, a symbol can have only one function definition
1558 attached to it at a time.  Otherwise, the computer would be confused as
1559 to which definition to use.  If this were the case among people, only
1560 one person in the world could be named @samp{Bob}.  However, the function
1561 definition to which the name refers can be changed readily.
1562 (@xref{Install, , Install a Function Definition}.)
1564 Since Emacs Lisp is large, it is customary to name symbols in a way
1565 that identifies the part of Emacs to which the function belongs.
1566 Thus, all the names for functions that deal with Texinfo start with
1567 @samp{texinfo-} and those for functions that deal with reading mail
1568 start with @samp{rmail-}.
1570 @node Lisp Interpreter, Evaluation, Names & Definitions, List Processing
1571 @comment  node-name,  next,  previous,  up
1572 @section The Lisp Interpreter
1573 @cindex Lisp interpreter, what it does
1574 @cindex Interpreter, what it does
1576 Based on what we have seen, we can now start to figure out what the
1577 Lisp interpreter does when we command it to evaluate a list.
1578 First, it looks to see whether there is a quote before the list; if
1579 there is, the interpreter just gives us the list.  On the other
1580 hand, if there is no quote, the interpreter looks at the first element
1581 in the list and sees whether it has a function definition.  If it does,
1582 the interpreter carries out the instructions in the function definition.
1583 Otherwise, the interpreter prints an error message.
1585 This is how Lisp works.  Simple.  There are added complications which we
1586 will get to in a minute, but these are the fundamentals.  Of course, to
1587 write Lisp programs, you need to know how to write function definitions
1588 and attach them to names, and how to do this without confusing either
1589 yourself or the computer.
1591 @menu
1592 * Complications::               Variables, Special forms, Lists within.
1593 * Byte Compiling::              Specially processing code for speed.
1594 @end menu
1596 @node Complications, Byte Compiling, Lisp Interpreter, Lisp Interpreter
1597 @ifnottex
1598 @unnumberedsubsec Complications
1599 @end ifnottex
1601 Now, for the first complication.  In addition to lists, the Lisp
1602 interpreter can evaluate a symbol that is not quoted and does not have
1603 parentheses around it.  The Lisp interpreter will attempt to determine
1604 the symbol's value as a @dfn{variable}.  This situation is described
1605 in the section on variables.  (@xref{Variables}.)
1607 @cindex Special form
1608 The second complication occurs because some functions are unusual and do
1609 not work in the usual manner.  Those that don't are called @dfn{special
1610 forms}.  They are used for special jobs, like defining a function, and
1611 there are not many of them.  In the next few chapters, you will be
1612 introduced to several of the more important special forms.
1614 The third and final complication is this: if the function that the
1615 Lisp interpreter is looking at is not a special form, and if it is part
1616 of a list, the Lisp interpreter looks to see whether the list has a list
1617 inside of it.  If there is an inner list, the Lisp interpreter first
1618 figures out what it should do with the inside list, and then it works on
1619 the outside list.  If there is yet another list embedded inside the
1620 inner list, it works on that one first, and so on.  It always works on
1621 the innermost list first.  The interpreter works on the innermost list
1622 first, to evaluate the result of that list.  The result may be
1623 used by the enclosing expression.
1625 Otherwise, the interpreter works left to right, from one expression to
1626 the next.
1628 @node Byte Compiling,  , Complications, Lisp Interpreter
1629 @subsection Byte Compiling
1630 @cindex Byte compiling
1632 One other aspect of interpreting: the Lisp interpreter is able to
1633 interpret two kinds of entity: humanly readable code, on which we will
1634 focus exclusively, and specially processed code, called @dfn{byte
1635 compiled} code, which is not humanly readable.  Byte compiled code
1636 runs faster than humanly readable code.
1638 You can transform humanly readable code into byte compiled code by
1639 running one of the compile commands such as @code{byte-compile-file}.
1640 Byte compiled code is usually stored in a file that ends with a
1641 @file{.elc} extension rather than a @file{.el} extension.  You will
1642 see both kinds of file in the @file{emacs/lisp} directory; the files
1643 to read are those with @file{.el} extensions.
1645 As a practical matter, for most things you might do to customize or
1646 extend Emacs, you do not need to byte compile; and I will not discuss
1647 the topic here.  @xref{Byte Compilation, , Byte Compilation, elisp,
1648 The GNU Emacs Lisp Reference Manual}, for a full description of byte
1649 compilation.
1651 @node Evaluation, Variables, Lisp Interpreter, List Processing
1652 @comment  node-name,  next,  previous,  up
1653 @section Evaluation
1654 @cindex Evaluation
1656 When the Lisp interpreter works on an expression, the term for the
1657 activity is called @dfn{evaluation}.  We say that the interpreter
1658 `evaluates the expression'.  I've used this term several times before.
1659 The word comes from its use in everyday language, `to ascertain the
1660 value or amount of; to appraise', according to @cite{Webster's New
1661 Collegiate Dictionary}.
1663 After evaluating an expression, the Lisp interpreter will most likely
1664 @dfn{return} the value that the computer produces by carrying out the
1665 instructions it found in the function definition, or perhaps it will
1666 give up on that function and produce an error message.  (The interpreter
1667 may also find itself tossed, so to speak, to a different function or it
1668 may attempt to repeat continually what it is doing for ever and ever in
1669 what is called an `infinite loop'.  These actions are less common; and
1670 we can ignore them.)  Most frequently, the interpreter returns a value.
1672 @cindex @samp{side effect} defined
1673 At the same time the interpreter returns a value, it may do something
1674 else as well, such as move a cursor or copy a file; this other kind of
1675 action is called a @dfn{side effect}.  Actions that we humans think are
1676 important, such as printing results, are often ``side effects'' to the
1677 Lisp interpreter.  The jargon can sound peculiar, but it turns out that
1678 it is fairly easy to learn to use side effects.
1680 In summary, evaluating a symbolic expression most commonly causes the
1681 Lisp interpreter to return a value and perhaps carry out a side effect;
1682 or else produce an error.
1684 @menu
1685 * Evaluating Inner Lists::      Lists within lists...
1686 @end menu
1688 @node Evaluating Inner Lists,  , Evaluation, Evaluation
1689 @comment  node-name,  next,  previous,  up
1690 @subsection Evaluating Inner Lists
1691 @cindex Inner list evaluation
1692 @cindex Evaluating inner lists
1694 If evaluation applies to a list that is inside another list, the outer
1695 list may use the value returned by the first evaluation as information
1696 when the outer list is evaluated.  This explains why inner expressions
1697 are evaluated first: the values they return are used by the outer
1698 expressions.
1700 @need 1250
1701 We can investigate this process by evaluating another addition example.
1702 Place your cursor after the following expression and type @kbd{C-x C-e}:
1704 @smallexample
1705 (+ 2 (+ 3 3))
1706 @end smallexample
1708 @noindent
1709 The number 8 will appear in the echo area.
1711 What happens is that the Lisp interpreter first evaluates the inner
1712 expression, @code{(+ 3 3)}, for which the value 6 is returned; then it
1713 evaluates the outer expression as if it were written @code{(+ 2 6)}, which
1714 returns the value 8.  Since there are no more enclosing expressions to
1715 evaluate, the interpreter prints that value in the echo area.
1717 Now it is easy to understand the name of the command invoked by the
1718 keystrokes @kbd{C-x C-e}: the name is @code{eval-last-sexp}.  The
1719 letters @code{sexp} are an abbreviation for `symbolic expression', and
1720 @code{eval} is an abbreviation for `evaluate'.  The command means
1721 `evaluate last symbolic expression'.
1723 As an experiment, you can try evaluating the expression by putting the
1724 cursor at the beginning of the next line immediately following the
1725 expression, or inside the expression.
1727 @need 800
1728 Here is another copy of the expression:
1730 @smallexample
1731 (+ 2 (+ 3 3))
1732 @end smallexample
1734 @noindent
1735 If you place the cursor at the beginning of the blank line that
1736 immediately follows the expression and type @kbd{C-x C-e}, you will
1737 still get the value 8 printed in the echo area.  Now try putting the
1738 cursor inside the expression.  If you put it right after the next to
1739 last parenthesis (so it appears to sit on top of the last parenthesis),
1740 you will get a 6 printed in the echo area!  This is because the command
1741 evaluates the expression @code{(+ 3 3)}.
1743 Now put the cursor immediately after a number.  Type @kbd{C-x C-e} and
1744 you will get the number itself.  In Lisp, if you evaluate a number, you
1745 get the number itself---this is how numbers differ from symbols.  If you
1746 evaluate a list starting with a symbol like @code{+}, you will get a
1747 value returned that is the result of the computer carrying out the
1748 instructions in the function definition attached to that name.  If a
1749 symbol by itself is evaluated, something different happens, as we will
1750 see in the next section.
1752 @node Variables, Arguments, Evaluation, List Processing
1753 @comment  node-name,  next,  previous,  up
1754 @section Variables
1755 @cindex Variables
1757 In Emacs Lisp, a symbol can have a value attached to it just as it can
1758 have a function definition attached to it.  The two are different.
1759 The function definition is a set of instructions that a computer will
1760 obey.  A value, on the other hand, is something, such as number or a
1761 name, that can vary (which is why such a symbol is called a variable).
1762 The value of a symbol can be any expression in Lisp, such as a symbol,
1763 number, list, or string.  A symbol that has a value is often called a
1764 @dfn{variable}.
1766 A symbol can have both a function definition and a value attached to
1767 it at the same time.  Or it can have just one or the other.
1768 The two are separate.  This is somewhat similar
1769 to the way the name Cambridge can refer to the city in Massachusetts
1770 and have some information attached to the name as well, such as
1771 ``great programming center''.
1773 @ignore
1774 (Incidentally, in Emacs Lisp, a symbol can have two
1775 other things attached to it, too: a property list and a documentation
1776 string; these are discussed later.)
1777 @end ignore
1779 Another way to think about this is to imagine a symbol as being a chest
1780 of drawers.  The function definition is put in one drawer, the value in
1781 another, and so on.  What is put in the drawer holding the value can be
1782 changed without affecting the contents of the drawer holding the
1783 function definition, and vice-versa.
1785 @menu
1786 * fill-column Example::
1787 * Void Function::               The error message for a symbol
1788                                   without a function.
1789 * Void Variable::               The error message for a symbol without a value.
1790 @end menu
1792 @node fill-column Example, Void Function, Variables, Variables
1793 @ifnottex
1794 @unnumberedsubsec @code{fill-column}, an Example Variable
1795 @end ifnottex
1797 @findex fill-column, @r{an example variable}
1798 @cindex Example variable, @code{fill-column}
1799 @cindex Variable, example of, @code{fill-column}
1800 The variable @code{fill-column} illustrates a symbol with a value
1801 attached to it: in every GNU Emacs buffer, this symbol is set to some
1802 value, usually 72 or 70, but sometimes to some other value.  To find the
1803 value of this symbol, evaluate it by itself.  If you are reading this in
1804 Info inside of GNU Emacs, you can do this by putting the cursor after
1805 the symbol and typing @kbd{C-x C-e}:
1807 @smallexample
1808 fill-column
1809 @end smallexample
1811 @noindent
1812 After I typed @kbd{C-x C-e}, Emacs printed the number 72 in my echo
1813 area.  This is the value for which @code{fill-column} is set for me as I
1814 write this.  It may be different for you in your Info buffer.  Notice
1815 that the value returned as a variable is printed in exactly the same way
1816 as the value returned by a function carrying out its instructions.  From
1817 the point of view of the Lisp interpreter, a value returned is a value
1818 returned.  What kind of expression it came from ceases to matter once
1819 the value is known.
1821 A symbol can have any value attached to it or, to use the jargon, we can
1822 @dfn{bind} the variable to a value: to a number, such as 72; to a
1823 string, @code{"such as this"}; to a list, such as @code{(spruce pine
1824 oak)}; we can even bind a variable to a function definition.
1826 A symbol can be bound to a value in several ways.  @xref{set & setq, ,
1827 Setting the Value of a Variable}, for information about one way to do
1828 this.
1830 @node Void Function, Void Variable, fill-column Example, Variables
1831 @comment  node-name,  next,  previous,  up
1832 @subsection Error Message for a Symbol Without a Function
1833 @cindex Symbol without function error
1834 @cindex Error for symbol without function
1836 When we evaluated @code{fill-column} to find its value as a variable,
1837 we did not place parentheses around the word.  This is because we did
1838 not intend to use it as a function name.
1840 If @code{fill-column} were the first or only element of a list, the
1841 Lisp interpreter would attempt to find the function definition
1842 attached to it.  But @code{fill-column} has no function definition.
1843 Try evaluating this:
1845 @smallexample
1846 (fill-column)
1847 @end smallexample
1849 @need 1250
1850 @noindent
1851 In GNU Emacs version 21, you will create a @file{*Backtrace*} buffer
1852 that says:
1854 @smallexample
1855 @group
1856 ---------- Buffer: *Backtrace* ----------
1857 Debugger entered--Lisp error: (void-function fill-column)
1858   (fill-column)
1859   eval((fill-column))
1860   eval-last-sexp-1(nil)
1861   eval-last-sexp(nil)
1862   call-interactively(eval-last-sexp)
1863 ---------- Buffer: *Backtrace* ----------
1864 @end group
1865 @end smallexample
1867 @noindent
1868 (Remember, to quit the debugger and make the debugger window go away,
1869 type @kbd{q} in the @file{*Backtrace*} buffer.)
1871 @need 800
1872 In GNU Emacs 20 and before, you will produce an error message that says:
1874 @smallexample
1875 Symbol's function definition is void:@: fill-column
1876 @end smallexample
1878 @noindent
1879 (The message will go away away as soon as you move the cursor or type
1880 another key.)
1882 @node Void Variable,  , Void Function, Variables
1883 @comment  node-name,  next,  previous,  up
1884 @subsection Error Message for a Symbol Without a Value
1885 @cindex Symbol without value error
1886 @cindex Error for symbol without value
1888 If you attempt to evaluate a symbol that does not have a value bound to
1889 it, you will receive an error message.  You can see this by
1890 experimenting with our 2 plus 2 addition.  In the following expression,
1891 put your cursor right after the @code{+}, before the first number 2,
1892 type @kbd{C-x C-e}:
1894 @smallexample
1895 (+ 2 2)
1896 @end smallexample
1898 @need 1500
1899 @noindent
1900 In GNU Emacs 21, you will create a @file{*Backtrace*} buffer that
1901 says:
1903 @smallexample
1904 @group
1905 ---------- Buffer: *Backtrace* ----------
1906 Debugger entered--Lisp error: (void-variable +)
1907   eval(+)
1908   eval-last-sexp-1(nil)
1909   eval-last-sexp(nil)
1910   call-interactively(eval-last-sexp)
1911 ---------- Buffer: *Backtrace* ----------
1912 @end group
1913 @end smallexample
1915 @noindent
1916 (As with the other times we entered the debugger, you can quit by
1917 typing @kbd{q} in the @file{*Backtrace*} buffer.)
1919 This backtrace is different from the very first error message we saw,
1920 which said, @samp{Debugger entered--Lisp error: (void-function this)}.
1921 In this case, the function does not have a value as a variable; while
1922 in the other error message, the function (the word `this') did not
1923 have a definition.
1925 In this experiment with the @code{+}, what we did was cause the Lisp
1926 interpreter to evaluate the @code{+} and look for the value of the
1927 variable instead of the function definition.  We did this by placing the
1928 cursor right after the symbol rather than after the parenthesis of the
1929 enclosing list as we did before.  As a consequence, the Lisp interpreter
1930 evaluated the preceding s-expression, which in this case was the
1931 @code{+} by itself.
1933 Since @code{+} does not have a value bound to it, just the function
1934 definition, the error message reported that the symbol's value as a
1935 variable was void.
1937 @need 800
1938 In GNU Emacs version 20 and before, your error message will say:
1940 @example
1941 Symbol's value as variable is void:@: +
1942 @end example
1944 @noindent
1945 The meaning is the same as in GNU Emacs 21.
1947 @node Arguments, set & setq, Variables, List Processing
1948 @comment  node-name,  next,  previous,  up
1949 @section Arguments
1950 @cindex Arguments
1951 @cindex Passing information to functions
1953 To see how information is passed to functions, let's look again at
1954 our old standby, the addition of two plus two.  In Lisp, this is written
1955 as follows:
1957 @smallexample
1958 (+ 2 2)
1959 @end smallexample
1961 If you evaluate this expression, the number 4 will appear in your echo
1962 area.  What the Lisp interpreter does is add the numbers that follow
1963 the @code{+}.
1965 @cindex @samp{argument} defined
1966 The numbers added by @code{+} are called the @dfn{arguments} of the
1967 function @code{+}.  These numbers are the information that is given to
1968 or @dfn{passed} to the function.
1970 The word `argument' comes from the way it is used in mathematics and
1971 does not refer to a disputation between two people; instead it refers to
1972 the information presented to the function, in this case, to the
1973 @code{+}.  In Lisp, the arguments to a function are the atoms or lists
1974 that follow the function.  The values returned by the evaluation of
1975 these atoms or lists are passed to the function.  Different functions
1976 require different numbers of arguments; some functions require none at
1977 all.@footnote{It is curious to track the path by which the word `argument'
1978 came to have two different meanings, one in mathematics and the other in
1979 everyday English.  According to the @cite{Oxford English Dictionary},
1980 the word derives from the Latin for @samp{to make clear, prove}; thus it
1981 came to mean, by one thread of derivation, `the evidence offered as
1982 proof', which is to say, `the information offered', which led to its
1983 meaning in Lisp.  But in the other thread of derivation, it came to mean
1984 `to assert in a manner against which others may make counter
1985 assertions', which led to the meaning of the word as a disputation.
1986 (Note here that the English word has two different definitions attached
1987 to it at the same time.  By contrast, in Emacs Lisp, a symbol cannot
1988 have two different function definitions at the same time.)}
1990 @menu
1991 * Data types::                  Types of data passed to a function.
1992 * Args as Variable or List::    An argument can be the value
1993                                   of a variable or list.
1994 * Variable Number of Arguments::  Some functions may take a
1995                                   variable number of arguments.
1996 * Wrong Type of Argument::      Passing an argument of the wrong type
1997                                   to a function.
1998 * message::                     A useful function for sending messages.
1999 @end menu
2001 @node Data types, Args as Variable or List, Arguments, Arguments
2002 @comment  node-name,  next,  previous,  up
2003 @subsection Arguments' Data Types
2004 @cindex Data types
2005 @cindex Types of data
2006 @cindex Arguments' data types
2008 The type of data that should be passed to a function depends on what
2009 kind of information it uses.  The arguments to a function such as
2010 @code{+} must have values that are numbers, since @code{+} adds numbers.
2011 Other functions use different kinds of data for their arguments.
2013 @findex concat
2014 For example, the @code{concat} function links together or unites two or
2015 more strings of text to produce a string.  The arguments are strings.
2016 Concatenating the two character strings @code{abc}, @code{def} produces
2017 the single string @code{abcdef}.  This can be seen by evaluating the
2018 following:
2020 @smallexample
2021 (concat "abc" "def")
2022 @end smallexample
2024 @noindent
2025 The value produced by evaluating this expression is @code{"abcdef"}.
2027 A function such as @code{substring} uses both a string and numbers as
2028 arguments.  The function returns a part of the string, a substring of
2029 the first argument.  This function takes three arguments.  Its first
2030 argument is the string of characters, the second and third arguments are
2031 numbers that indicate the beginning and end of the substring.  The
2032 numbers are a count of the number of characters (including spaces and
2033 punctuations) from the beginning of the string.
2035 @need 800
2036 For example, if you evaluate the following:
2038 @smallexample
2039 (substring "The quick brown fox jumped." 16 19)
2040 @end smallexample
2042 @noindent
2043 you will see @code{"fox"} appear in the echo area.  The arguments are the
2044 string and the two numbers.
2046 Note that the string passed to @code{substring} is a single atom even
2047 though it is made up of several words separated by spaces.  Lisp counts
2048 everything between the two quotation marks as part of the string,
2049 including the spaces.  You can think of the @code{substring} function as
2050 a kind of `atom smasher' since it takes an otherwise indivisible atom
2051 and extracts a part.  However, @code{substring} is only able to extract
2052 a substring from an argument that is a string, not from another type of
2053 atom such as a number or symbol.
2055 @node Args as Variable or List, Variable Number of Arguments, Data types, Arguments
2056 @comment  node-name,  next,  previous,  up
2057 @subsection An Argument as the Value of a Variable or List
2059 An argument can be a symbol that returns a value when it is evaluated.
2060 For example, when the symbol @code{fill-column} by itself is evaluated,
2061 it returns a number.  This number can be used in an addition.
2063 @need 1250
2064 Position the cursor after the following expression and type @kbd{C-x
2065 C-e}:
2067 @smallexample
2068 (+ 2 fill-column)
2069 @end smallexample
2071 @noindent
2072 The value will be a number two more than what you get by evaluating
2073 @code{fill-column} alone.  For me, this is 74, because the value of
2074 @code{fill-column} is 72.
2076 As we have just seen, an argument can be a symbol that returns a value
2077 when evaluated.  In addition, an argument can be a list that returns a
2078 value when it is evaluated.  For example, in the following expression,
2079 the arguments to the function @code{concat} are the strings
2080 @w{@code{"The "}} and @w{@code{" red foxes."}} and the list
2081 @code{(number-to-string (+ 2 fill-column))}.
2083 @c For Emacs 21, need number-to-string
2084 @smallexample
2085 (concat "The " (number-to-string (+ 2 fill-column)) " red foxes.")
2086 @end smallexample
2088 @noindent
2089 If you evaluate this expression---and if, as with my Emacs,
2090 @code{fill-column} evaluates to 72---@code{"The 74 red foxes."} will
2091 appear in the echo area.  (Note that you must put spaces after the
2092 word @samp{The} and before the word @samp{red} so they will appear in
2093 the final string.  The function @code{number-to-string} converts the
2094 integer that the addition function returns to a string.
2095 @code{number-to-string} is also known as @code{int-to-string}.)
2097 @node Variable Number of Arguments, Wrong Type of Argument, Args as Variable or List, Arguments
2098 @comment  node-name,  next,  previous,  up
2099 @subsection Variable Number of Arguments
2100 @cindex Variable number of arguments
2101 @cindex Arguments, variable number of
2103 Some functions, such as @code{concat}, @code{+} or @code{*}, take any
2104 number of arguments.  (The @code{*} is the symbol for multiplication.)
2105 This can be seen by evaluating each of the following expressions in
2106 the usual way.  What you will see in the echo area is printed in this
2107 text after @samp{@result{}}, which you may read as `evaluates to'.
2109 @need 1250
2110 In the first set, the functions have no arguments:
2112 @smallexample
2113 @group
2114 (+)       @result{} 0
2116 (*)       @result{} 1
2117 @end group
2118 @end smallexample
2120 @need 1250
2121 In this set, the functions have one argument each:
2123 @smallexample
2124 @group
2125 (+ 3)     @result{} 3
2127 (* 3)     @result{} 3
2128 @end group
2129 @end smallexample
2131 @need 1250
2132 In this set, the functions have three arguments each:
2134 @smallexample
2135 @group
2136 (+ 3 4 5) @result{} 12
2138 (* 3 4 5) @result{} 60
2139 @end group
2140 @end smallexample
2142 @node Wrong Type of Argument, message, Variable Number of Arguments, Arguments
2143 @comment  node-name,  next,  previous,  up
2144 @subsection Using the Wrong Type Object as an Argument
2145 @cindex Wrong type of argument
2146 @cindex Argument, wrong type of
2148 When a function is passed an argument of the wrong type, the Lisp
2149 interpreter produces an error message.  For example, the @code{+}
2150 function expects the values of its arguments to be numbers.  As an
2151 experiment we can pass it the quoted symbol @code{hello} instead of a
2152 number.  Position the cursor after the following expression and type
2153 @kbd{C-x C-e}:
2155 @smallexample
2156 (+ 2 'hello)
2157 @end smallexample
2159 @noindent
2160 When you do this you will generate an error message.  What has happened
2161 is that @code{+} has tried to add the 2 to the value returned by
2162 @code{'hello}, but the value returned by @code{'hello} is the symbol
2163 @code{hello}, not a number.  Only numbers can be added.  So @code{+}
2164 could not carry out its addition.
2166 @need 1250
2167 In GNU Emacs version 21, you will create and enter a
2168 @file{*Backtrace*} buffer that says:
2170 @noindent
2171 @smallexample
2172 @group
2173 ---------- Buffer: *Backtrace* ----------
2174 Debugger entered--Lisp error:
2175          (wrong-type-argument number-or-marker-p hello)
2176   +(2 hello)
2177   eval((+ 2 (quote hello)))
2178   eval-last-sexp-1(nil)
2179   eval-last-sexp(nil)
2180   call-interactively(eval-last-sexp)
2181 ---------- Buffer: *Backtrace* ----------
2182 @end group
2183 @end smallexample
2185 @need 1250
2186 As usual, the error message tries to be helpful and makes sense after you
2187 learn how to read it.
2189 The first part of the error message is straightforward; it says
2190 @samp{wrong type argument}.  Next comes the mysterious jargon word
2191 @w{@samp{number-or-marker-p}}.  This word is trying to tell you what
2192 kind of argument the @code{+} expected.
2194 The symbol @code{number-or-marker-p} says that the Lisp interpreter is
2195 trying to determine whether the information presented it (the value of
2196 the argument) is a number or a marker (a special object representing a
2197 buffer position).  What it does is test to see whether the @code{+} is
2198 being given numbers to add.  It also tests to see whether the
2199 argument is something called a marker, which is a specific feature of
2200 Emacs Lisp.  (In Emacs, locations in a buffer are recorded as markers.
2201 When the mark is set with the @kbd{C-@@} or @kbd{C-@key{SPC}} command,
2202 its position is kept as a marker.  The mark can be considered a
2203 number---the number of characters the location is from the beginning
2204 of the buffer.)  In Emacs Lisp, @code{+} can be used to add the
2205 numeric value of marker positions as numbers.
2207 The @samp{p} of @code{number-or-marker-p} is the embodiment of a
2208 practice started in the early days of Lisp programming.  The @samp{p}
2209 stands for `predicate'.  In the jargon used by the early Lisp
2210 researchers, a predicate refers to a function to determine whether some
2211 property is true or false.  So the @samp{p} tells us that
2212 @code{number-or-marker-p} is the name of a function that determines
2213 whether it is true or false that the argument supplied is a number or
2214 a marker.  Other Lisp symbols that end in @samp{p} include @code{zerop},
2215 a function that tests whether its argument has the value of zero, and
2216 @code{listp}, a function that tests whether its argument is a list.
2218 Finally, the last part of the error message is the symbol @code{hello}.
2219 This is the value of the argument that was passed to @code{+}.  If the
2220 addition had been passed the correct type of object, the value passed
2221 would have been a number, such as 37, rather than a symbol like
2222 @code{hello}.  But then you would not have got the error message.
2224 @need 1250
2225 In GNU Emacs version 20 and before, the echo area displays an error
2226 message that says:
2228 @smallexample
2229 Wrong type argument:@: number-or-marker-p, hello
2230 @end smallexample
2232 This says, in different words, the same as the top line of the
2233 @file{*Backtrace*} buffer.
2235 @node message,  , Wrong Type of Argument, Arguments
2236 @comment  node-name,  next,  previous,  up
2237 @subsection The @code{message} Function
2238 @findex message
2240 Like @code{+}, the @code{message} function takes a variable number of
2241 arguments.  It is used to send messages to the user and is so useful
2242 that we will describe it here.
2244 @need 1250
2245 A message is printed in the echo area.  For example, you can print a
2246 message in your echo area by evaluating the following list:
2248 @smallexample
2249 (message "This message appears in the echo area!")
2250 @end smallexample
2252 The whole string between double quotation marks is a single argument
2253 and is printed @i{in toto}.  (Note that in this example, the message
2254 itself will appear in the echo area within double quotes; that is
2255 because you see the value returned by the @code{message} function.  In
2256 most uses of @code{message} in programs that you write, the text will
2257 be printed in the echo area as a side-effect, without the quotes.
2258 @xref{multiply-by-seven in detail, , @code{multiply-by-seven} in
2259 detail}, for an example of this.)
2261 However, if there is a @samp{%s} in the quoted string of characters, the
2262 @code{message} function does not print the @samp{%s} as such, but looks
2263 to the argument that follows the string.  It evaluates the second
2264 argument and prints the value at the location in the string where the
2265 @samp{%s} is.
2267 @need 1250
2268 You can see this by positioning the cursor after the following
2269 expression and typing @kbd{C-x C-e}:
2271 @smallexample
2272 (message "The name of this buffer is: %s." (buffer-name))
2273 @end smallexample
2275 @noindent
2276 In Info, @code{"The name of this buffer is: *info*."} will appear in the
2277 echo area.  The function @code{buffer-name} returns the name of the
2278 buffer as a string, which the @code{message} function inserts in place
2279 of @code{%s}.
2281 To print a value as an integer, use @samp{%d} in the same way as
2282 @samp{%s}.  For example, to print a message in the echo area that
2283 states the value of the @code{fill-column}, evaluate the following:
2285 @smallexample
2286 (message "The value of fill-column is %d." fill-column)
2287 @end smallexample
2289 @noindent
2290 On my system, when I evaluate this list, @code{"The value of
2291 fill-column is 72."} appears in my echo area@footnote{Actually, you
2292 can use @code{%s} to print a number.  It is non-specific.  @code{%d}
2293 prints only the part of a number left of a decimal point, and not
2294 anything that is not a number.}.
2296 If there is more than one @samp{%s} in the quoted string, the value of
2297 the first argument following the quoted string is printed at the
2298 location of the first @samp{%s} and the value of the second argument is
2299 printed at the location of the second @samp{%s}, and so on.
2301 @need 1250
2302 For example, if you evaluate the following,
2304 @smallexample
2305 @group
2306 (message "There are %d %s in the office!"
2307          (- fill-column 14) "pink elephants")
2308 @end group
2309 @end smallexample
2311 @noindent
2312 a rather whimsical message will appear in your echo area.  On my system
2313 it says, @code{"There are 58 pink elephants in the office!"}.
2315 The expression @code{(- fill-column 14)} is evaluated and the resulting
2316 number is inserted in place of the @samp{%d}; and the string in double
2317 quotes, @code{"pink elephants"}, is treated as a single argument and
2318 inserted in place of the @samp{%s}.  (That is to say, a string between
2319 double quotes evaluates to itself, like a number.)
2321 Finally, here is a somewhat complex example that not only illustrates
2322 the computation of a number, but also shows how you can use an
2323 expression within an expression to generate the text that is substituted
2324 for @samp{%s}:
2326 @smallexample
2327 @group
2328 (message "He saw %d %s"
2329          (- fill-column 34)
2330          (concat "red "
2331                  (substring
2332                   "The quick brown foxes jumped." 16 21)
2333                  " leaping."))
2334 @end group
2335 @end smallexample
2337 In this example, @code{message} has three arguments: the string,
2338 @code{"He saw %d %s"}, the expression, @code{(- fill-column 32)}, and
2339 the expression beginning with the function @code{concat}.  The value
2340 resulting from the evaluation of @code{(- fill-column 32)} is inserted
2341 in place of the @samp{%d}; and the value returned by the expression
2342 beginning with @code{concat} is inserted in place of the @samp{%s}.
2344 When I evaluate the expression, the message @code{"He saw 38 red
2345 foxes leaping."} appears in my echo area.
2347 @node set & setq, Summary, Arguments, List Processing
2348 @comment  node-name,  next,  previous,  up
2349 @section Setting the Value of a Variable
2350 @cindex Variable, setting value
2351 @cindex Setting value of variable
2353 @cindex @samp{bind} defined
2354 There are several ways by which a variable can be given a value.  One of
2355 the ways is to use either the function @code{set} or the function
2356 @code{setq}.  Another way is to use @code{let} (@pxref{let}).  (The
2357 jargon for this process is to @dfn{bind} a variable to a value.)
2359 The following sections not only describe how @code{set} and @code{setq}
2360 work but also illustrate how arguments are passed.
2362 @menu
2363 * Using set::                   Setting values.
2364 * Using setq::                  Setting a quoted value.
2365 * Counting::                    Using @code{setq} to count.
2366 @end menu
2368 @node Using set, Using setq, set & setq, set & setq
2369 @comment  node-name,  next,  previous,  up
2370 @subsection Using @code{set}
2371 @findex set
2373 To set the value of the symbol @code{flowers} to the list @code{'(rose
2374 violet daisy buttercup)}, evaluate the following expression by
2375 positioning the cursor after the expression and typing @kbd{C-x C-e}.
2377 @smallexample
2378 (set 'flowers '(rose violet daisy buttercup))
2379 @end smallexample
2381 @noindent
2382 The list @code{(rose violet daisy buttercup)} will appear in the echo
2383 area.  This is what is @emph{returned} by the @code{set} function.  As a
2384 side effect, the symbol @code{flowers} is bound to the list ; that is,
2385 the symbol @code{flowers}, which can be viewed as a variable, is given
2386 the list as its value.  (This process, by the way, illustrates how a
2387 side effect to the Lisp interpreter, setting the value, can be the
2388 primary effect that we humans are interested in.  This is because every
2389 Lisp function must return a value if it does not get an error, but it
2390 will only have a side effect if it is designed to have one.)
2392 After evaluating the @code{set} expression, you can evaluate the symbol
2393 @code{flowers} and it will return the value you just set.  Here is the
2394 symbol.  Place your cursor after it and type @kbd{C-x C-e}.
2396 @smallexample
2397 flowers
2398 @end smallexample
2400 @noindent
2401 When you evaluate @code{flowers}, the list
2402 @code{(rose violet daisy buttercup)} appears in the echo area.
2404 Incidentally, if you evaluate @code{'flowers}, the variable with a quote
2405 in front of it, what you will see in the echo area is the symbol itself,
2406 @code{flowers}.  Here is the quoted symbol, so you can try this:
2408 @smallexample
2409 'flowers
2410 @end smallexample
2412 Note also, that when you use @code{set}, you need to quote both
2413 arguments to @code{set}, unless you want them evaluated.  Since we do
2414 not want either argument evaluated, neither the variable
2415 @code{flowers} nor the list @code{(rose violet daisy buttercup)}, both
2416 are quoted.  (When you use @code{set} without quoting its first
2417 argument, the first argument is evaluated before anything else is
2418 done.  If you did this and @code{flowers} did not have a value
2419 already, you would get an error message that the @samp{Symbol's value
2420 as variable is void}; on the other hand, if @code{flowers} did return
2421 a value after it was evaluated, the @code{set} would attempt to set
2422 the value that was returned.  There are situations where this is the
2423 right thing for the function to do; but such situations are rare.)
2425 @node Using setq, Counting, Using set, set & setq
2426 @comment  node-name,  next,  previous,  up
2427 @subsection Using @code{setq}
2428 @findex setq
2430 As a practical matter, you almost always quote the first argument to
2431 @code{set}.  The combination of @code{set} and a quoted first argument
2432 is so common that it has its own name: the special form @code{setq}.
2433 This special form is just like @code{set} except that the first argument
2434 is quoted automatically, so you don't need to type the quote mark
2435 yourself.  Also, as an added convenience, @code{setq} permits you to set
2436 several different variables to different values, all in one expression.
2438 To set the value of the variable @code{carnivores} to the list
2439 @code{'(lion tiger leopard)} using @code{setq}, the following expression
2440 is used:
2442 @smallexample
2443 (setq carnivores '(lion tiger leopard))
2444 @end smallexample
2446 @noindent
2447 This is exactly the same as using @code{set} except the first argument
2448 is automatically quoted by @code{setq}.  (The @samp{q} in @code{setq}
2449 means @code{quote}.)
2451 @need 1250
2452 With @code{set}, the expression would look like this:
2454 @smallexample
2455 (set 'carnivores '(lion tiger leopard))
2456 @end smallexample
2458 Also, @code{setq} can be used to assign different values to
2459 different variables.  The first argument is bound to the value
2460 of the second argument, the third argument is bound to the value of the
2461 fourth argument, and so on.  For example, you could use the following to
2462 assign a list of trees to the symbol @code{trees} and a list of herbivores
2463 to the symbol @code{herbivores}:
2465 @smallexample
2466 @group
2467 (setq trees '(pine fir oak maple)
2468       herbivores '(gazelle antelope zebra))
2469 @end group
2470 @end smallexample
2472 @noindent
2473 (The expression could just as well have been on one line, but it might
2474 not have fit on a page; and humans find it easier to read nicely
2475 formatted lists.)
2477 Although I have been using the term `assign', there is another way of
2478 thinking about the workings of @code{set} and @code{setq}; and that is to
2479 say that @code{set} and @code{setq} make the symbol @emph{point} to the
2480 list.  This latter way of thinking is very common and in forthcoming
2481 chapters we shall come upon at least one symbol that has `pointer' as
2482 part of its name.  The name is chosen because the symbol has a value,
2483 specifically a list, attached to it; or, expressed another way,
2484 the symbol is set to ``point'' to the list.
2486 @node Counting,  , Using setq, set & setq
2487 @comment  node-name,  next,  previous,  up
2488 @subsection Counting
2489 @cindex Counting
2491 Here is an example that shows how to use @code{setq} in a counter.  You
2492 might use this to count how many times a part of your program repeats
2493 itself.  First set a variable to zero; then add one to the number each
2494 time the program repeats itself.  To do this, you need a variable that
2495 serves as a counter, and two expressions: an initial @code{setq}
2496 expression that sets the counter variable to zero; and a second
2497 @code{setq} expression that increments the counter each time it is
2498 evaluated.
2500 @smallexample
2501 @group
2502 (setq counter 0)                ; @r{Let's call this the initializer.}
2504 (setq counter (+ counter 1))    ; @r{This is the incrementer.}
2506 counter                         ; @r{This is the counter.}
2507 @end group
2508 @end smallexample
2510 @noindent
2511 (The text following the @samp{;} are comments.  @xref{Change a
2512 defun, , Change a Function Definition}.)
2514 If you evaluate the first of these expressions, the initializer,
2515 @code{(setq counter 0)}, and then evaluate the third expression,
2516 @code{counter}, the number @code{0} will appear in the echo area.  If
2517 you then evaluate the second expression, the incrementer, @code{(setq
2518 counter (+ counter 1))}, the counter will get the value 1.  So if you
2519 again evaluate @code{counter}, the number @code{1} will appear in the
2520 echo area.  Each time you evaluate the second expression, the value of
2521 the counter will be incremented.
2523 When you evaluate the incrementer, @code{(setq counter (+ counter 1))},
2524 the Lisp interpreter first evaluates the innermost list; this is the
2525 addition.  In order to evaluate this list, it must evaluate the variable
2526 @code{counter} and the number @code{1}.  When it evaluates the variable
2527 @code{counter}, it receives its current value.  It passes this value and
2528 the number @code{1} to the @code{+} which adds them together.  The sum
2529 is then returned as the value of the inner list and passed to the
2530 @code{setq} which sets the variable @code{counter} to this new value.
2531 Thus, the value of the variable, @code{counter}, is changed.
2533 @node Summary, Error Message Exercises, set & setq, List Processing
2534 @comment  node-name,  next,  previous,  up
2535 @section Summary
2537 Learning Lisp is like climbing a hill in which the first part is the
2538 steepest.  You have now climbed the most difficult part; what remains
2539 becomes easier as you progress onwards.
2541 In summary,
2543 @itemize @bullet
2545 @item
2546 Lisp programs are made up of expressions, which are lists or single atoms.
2548 @item
2549 Lists are made up of zero or more atoms or inner lists, separated by whitespace and
2550 surrounded by parentheses.  A list can be empty.
2552 @item
2553 Atoms are multi-character symbols, like @code{forward-paragraph}, single
2554 character symbols like @code{+}, strings of characters between double
2555 quotation marks, or numbers.
2557 @item
2558 A number evaluates to itself.
2560 @item
2561 A string between double quotes also evaluates to itself.
2563 @item
2564 When you evaluate a symbol by itself, its value is returned.
2566 @item
2567 When you evaluate a list, the Lisp interpreter looks at the first symbol
2568 in the list and then at the function definition bound to that symbol.
2569 Then the instructions in the function definition are carried out.
2571 @item
2572 A single-quote, @code{'}, tells the Lisp interpreter that it should
2573 return the following expression as written, and not evaluate it as it
2574 would if the quote were not there.
2576 @item
2577 Arguments are the information passed to a function.  The arguments to a
2578 function are computed by evaluating the rest of the elements of the list
2579 of which the function is the first element.
2581 @item
2582 A function always returns a value when it is evaluated (unless it gets
2583 an error); in addition, it may also carry out some action called a
2584 ``side effect''.  In many cases, a function's primary purpose is to
2585 create a side effect.
2586 @end itemize
2588 @node Error Message Exercises,  , Summary, List Processing
2589 @comment  node-name,  next,  previous,  up
2590 @section Exercises
2592 A few simple exercises:
2594 @itemize @bullet
2595 @item
2596 Generate an error message by evaluating an appropriate symbol that is
2597 not within parentheses.
2599 @item
2600 Generate an error message by evaluating an appropriate symbol that is
2601 between parentheses.
2603 @item
2604 Create a counter that increments by two rather than one.
2606 @item
2607 Write an expression that prints a message in the echo area when
2608 evaluated.
2609 @end itemize
2611 @node Practicing Evaluation, Writing Defuns, List Processing, Top
2612 @comment  node-name,  next,  previous,  up
2613 @chapter Practicing Evaluation
2614 @cindex Practicing evaluation
2615 @cindex Evaluation practice
2617 Before learning how to write a function definition in Emacs Lisp, it is
2618 useful to spend a little time evaluating various expressions that have
2619 already been written.  These expressions will be lists with the
2620 functions as their first (and often only) element.  Since some of the
2621 functions associated with buffers are both simple and interesting, we
2622 will start with those.  In this section, we will evaluate a few of
2623 these.  In another section, we will study the code of several other
2624 buffer-related functions, to see how they were written.
2626 @menu
2627 * How to Evaluate::             Typing editing commands or @kbd{C-x C-e}
2628                                   causes evaluation.
2629 * Buffer Names::                Buffers and files are different.
2630 * Getting Buffers::             Getting a buffer itself, not merely its name.
2631 * Switching Buffers::           How to change to another buffer.
2632 * Buffer Size & Locations::     Where point is located and the size of
2633                                 the buffer.
2634 * Evaluation Exercise::
2635 @end menu
2637 @node How to Evaluate, Buffer Names, Practicing Evaluation, Practicing Evaluation
2638 @ifnottex
2639 @unnumberedsec How to Evaluate
2640 @end ifnottex
2642 @i{Whenever you give an editing command} to Emacs Lisp, such as the
2643 command to move the cursor or to scroll the screen, @i{you are evaluating
2644 an expression,} the first element of which is a function.  @i{This is
2645 how Emacs works.}
2647 @cindex @samp{interactive function} defined
2648 @cindex @samp{command} defined
2649 When you type keys, you cause the Lisp interpreter to evaluate an
2650 expression and that is how you get your results.  Even typing plain text
2651 involves evaluating an Emacs Lisp function, in this case, one that uses
2652 @code{self-insert-command}, which simply inserts the character you
2653 typed.  The functions you evaluate by typing keystrokes are called
2654 @dfn{interactive} functions, or @dfn{commands}; how you make a function
2655 interactive will be illustrated in the chapter on how to write function
2656 definitions.  @xref{Interactive, , Making a Function Interactive}.
2658 In addition to typing keyboard commands, we have seen a second way to
2659 evaluate an expression: by positioning the cursor after a list and
2660 typing @kbd{C-x C-e}.  This is what we will do in the rest of this
2661 section.  There are other ways to evaluate an expression as well; these
2662 will be described as we come to them.
2664 Besides being used for practicing evaluation, the functions shown in the
2665 next few sections are important in their own right.  A study of these
2666 functions makes clear the distinction between buffers and files, how to
2667 switch to a buffer, and how to determine a location within it.
2669 @node Buffer Names, Getting Buffers, How to Evaluate, Practicing Evaluation
2670 @comment  node-name,  next,  previous,  up
2671 @section Buffer Names
2672 @findex buffer-name
2673 @findex buffer-file-name
2675 The two functions, @code{buffer-name} and @code{buffer-file-name}, show
2676 the difference between a file and a buffer.  When you evaluate the
2677 following expression, @code{(buffer-name)}, the name of the buffer
2678 appears in the echo area.  When you evaluate @code{(buffer-file-name)},
2679 the name of the file to which the buffer refers appears in the echo
2680 area.  Usually, the name returned by @code{(buffer-name)} is the same as
2681 the name of the file to which it refers, and the name returned by
2682 @code{(buffer-file-name)} is the full path-name of the file.
2684 A file and a buffer are two different entities.  A file is information
2685 recorded permanently in the computer (unless you delete it).  A buffer,
2686 on the other hand, is information inside of Emacs that will vanish at
2687 the end of the editing session (or when you kill the buffer).  Usually,
2688 a buffer contains information that you have copied from a file; we say
2689 the buffer is @dfn{visiting} that file.  This copy is what you work on
2690 and modify.  Changes to the buffer do not change the file, until you
2691 save the buffer.  When you save the buffer, the buffer is copied to the file
2692 and is thus saved permanently.
2694 @need 1250
2695 If you are reading this in Info inside of GNU Emacs, you can evaluate
2696 each of the following expressions by positioning the cursor after it and
2697 typing @kbd{C-x C-e}.
2699 @smallexample
2700 @group
2701 (buffer-name)
2703 (buffer-file-name)
2704 @end group
2705 @end smallexample
2707 @noindent
2708 When I do this, @file{"introduction.texinfo"} is the value returned by
2709 evaluating @code{(buffer-name)}, and
2710 @file{"/gnu/work/intro/introduction.texinfo"} is the value returned by
2711 evaluating @code{(buffer-file-name)}.  The former is the name of the
2712 buffer and the latter is the name of the file.  (In the expressions, the
2713 parentheses tell the Lisp interpreter to treat @code{buffer-name} and
2714 @code{buffer-file-name} as functions; without the parentheses, the
2715 interpreter would attempt to evaluate the symbols as variables.
2716 @xref{Variables}.)
2718 In spite of the distinction between files and buffers, you will often
2719 find that people refer to a file when they mean a buffer and vice-versa.
2720 Indeed, most people say, ``I am editing a file,'' rather than saying,
2721 ``I am editing a buffer which I will soon save to a file.''  It is
2722 almost always clear from context what people mean.  When dealing with
2723 computer programs, however, it is important to keep the distinction in mind,
2724 since the computer is not as smart as a person.
2726 @cindex Buffer, history of word
2727 The word `buffer', by the way, comes from the meaning of the word as a
2728 cushion that deadens the force of a collision.  In early computers, a
2729 buffer cushioned the interaction between files and the computer's
2730 central processing unit.  The drums or tapes that held a file and the
2731 central processing unit were pieces of equipment that were very
2732 different from each other, working at their own speeds, in spurts.  The
2733 buffer made it possible for them to work together effectively.
2734 Eventually, the buffer grew from being an intermediary, a temporary
2735 holding place, to being the place where work is done.  This
2736 transformation is rather like that of a small seaport that grew into a
2737 great city: once it was merely the place where cargo was warehoused
2738 temporarily before being loaded onto ships; then it became a business
2739 and cultural center in its own right.
2741 Not all buffers are associated with files.  For example, when you start
2742 an Emacs session by typing the command @code{emacs} alone, without
2743 naming any files, Emacs will start with the @file{*scratch*} buffer on
2744 the screen.  This buffer is not visiting any file.  Similarly, a
2745 @file{*Help*} buffer is not associated with any file.
2747 @cindex @code{nil}, history of word
2748 If you switch to the @file{*scratch*} buffer, type @code{(buffer-name)},
2749 position the cursor after it, and type @kbd{C-x C-e} to evaluate the
2750 expression, the name @code{"*scratch*"} is returned and will appear in
2751 the echo area.  @code{"*scratch*"} is the name of the buffer.  However,
2752 if you type @code{(buffer-file-name)} in the @file{*scratch*} buffer and
2753 evaluate that, @code{nil} will appear in the echo area.  @code{nil} is
2754 from the Latin word for `nothing'; in this case, it means that the
2755 @file{*scratch*} buffer is not associated with any file.  (In Lisp,
2756 @code{nil} is also used to mean `false' and is a synonym for the empty
2757 list, @code{()}.)
2759 Incidentally, if you are in the @file{*scratch*} buffer and want the
2760 value returned by an expression to appear in the @file{*scratch*}
2761 buffer itself rather than in the echo area, type @kbd{C-u C-x C-e}
2762 instead of @kbd{C-x C-e}.  This causes the value returned to appear
2763 after the expression.  The buffer will look like this:
2765 @smallexample
2766 (buffer-name)"*scratch*"
2767 @end smallexample
2769 @noindent
2770 You cannot do this in Info since Info is read-only and it will not allow
2771 you to change the contents of the buffer.  But you can do this in any
2772 buffer you can edit; and when you write code or documentation (such as
2773 this book), this feature is very useful.
2775 @node Getting Buffers, Switching Buffers, Buffer Names, Practicing Evaluation
2776 @comment  node-name,  next,  previous,  up
2777 @section Getting Buffers
2778 @findex current-buffer
2779 @findex other-buffer
2780 @cindex Getting a buffer
2782 The @code{buffer-name} function returns the @emph{name} of the buffer;
2783 to get the buffer @emph{itself}, a different function is needed: the
2784 @code{current-buffer} function.  If you use this function in code, what
2785 you get is the buffer itself.
2787 A name and the object or entity to which the name refers are different
2788 from each other.  You are not your name.  You are a person to whom
2789 others refer by name.  If you ask to speak to George and someone hands you
2790 a card with the letters @samp{G}, @samp{e}, @samp{o}, @samp{r},
2791 @samp{g}, and @samp{e} written on it, you might be amused, but you would
2792 not be satisfied.  You do not want to speak to the name, but to the
2793 person to whom the name refers.  A buffer is similar: the name of the
2794 scratch buffer is @file{*scratch*}, but the name is not the buffer.  To
2795 get a buffer itself, you need to use a function such as
2796 @code{current-buffer}.
2798 However, there is a slight complication: if you evaluate
2799 @code{current-buffer} in an expression on its own, as we will do here,
2800 what you see is a printed representation of the name of the buffer
2801 without the contents of the buffer.  Emacs works this way for two
2802 reasons: the buffer may be thousands of lines long---too long to be
2803 conveniently displayed; and, another buffer may have the same contents
2804 but a different name, and it is important to distinguish between them.
2806 @need 800
2807 Here is an expression containing the function:
2809 @smallexample
2810 (current-buffer)
2811 @end smallexample
2813 @noindent
2814 If you evaluate the expression in the usual way, @file{#<buffer *info*>}
2815 appears in the echo area.  The special format indicates that the
2816 buffer itself is being returned, rather than just its name.
2818 Incidentally, while you can type a number or symbol into a program, you
2819 cannot do that with the printed representation of a buffer: the only way
2820 to get a buffer itself is with a function such as @code{current-buffer}.
2822 A related function is @code{other-buffer}.  This returns the most
2823 recently selected buffer other than the one you are in currently.  If
2824 you have recently switched back and forth from the @file{*scratch*}
2825 buffer, @code{other-buffer} will return that buffer.
2827 @need 800
2828 You can see this by evaluating the expression:
2830 @smallexample
2831 (other-buffer)
2832 @end smallexample
2834 @noindent
2835 You should see @file{#<buffer *scratch*>} appear in the echo area, or
2836 the name of whatever other buffer you switched back from most
2837 recently@footnote{Actually, by default, if the buffer from which you
2838 just switched is visible to you in another window, @code{other-buffer}
2839 will choose the most recent buffer that you cannot see; this is a
2840 subtlety that I often forget.}.
2842 @node Switching Buffers, Buffer Size & Locations, Getting Buffers, Practicing Evaluation
2843 @comment  node-name,  next,  previous,  up
2844 @section Switching Buffers
2845 @findex switch-to-buffer
2846 @findex set-buffer
2847 @cindex Switching to a buffer
2849 The @code{other-buffer} function actually provides a buffer when it is
2850 used as an argument to a function that requires one.  We can see this
2851 by using @code{other-buffer} and @code{switch-to-buffer} to switch to a
2852 different buffer.
2854 But first, a brief introduction to the @code{switch-to-buffer}
2855 function.  When you switched back and forth from Info to the
2856 @file{*scratch*} buffer to evaluate @code{(buffer-name)}, you most
2857 likely typed @kbd{C-x b} and then typed @file{*scratch*}@footnote{Or
2858 rather, to save typing, you probably typed just part of the name, such
2859 as @code{*sc}, and then pressed your @kbd{TAB} key to cause it to
2860 expand to the full name; and then typed your @kbd{RET} key.} when
2861 prompted in the minibuffer for the name of the buffer to which you
2862 wanted to switch.  The keystrokes, @kbd{C-x b}, cause the Lisp
2863 interpreter to evaluate the interactive function
2864 @code{switch-to-buffer}.  As we said before, this is how Emacs works:
2865 different keystrokes call or run different functions.  For example,
2866 @kbd{C-f} calls @code{forward-char}, @kbd{M-e} calls
2867 @code{forward-sentence}, and so on.
2869 By writing @code{switch-to-buffer} in an expression, and giving it a
2870 buffer to switch to, we can switch buffers just the way @kbd{C-x b}
2871 does.
2873 @need 1000
2874 Here is the Lisp expression:
2876 @smallexample
2877 (switch-to-buffer (other-buffer))
2878 @end smallexample
2880 @noindent
2881 The symbol @code{switch-to-buffer} is the first element of the list,
2882 so the Lisp interpreter will treat it as a function and carry out the
2883 instructions that are attached to it.  But before doing that, the
2884 interpreter will note that @code{other-buffer} is inside parentheses
2885 and work on that symbol first.  @code{other-buffer} is the first (and
2886 in this case, the only) element of this list, so the Lisp interpreter
2887 calls or runs the function.  It returns another buffer.  Next, the
2888 interpreter runs @code{switch-to-buffer}, passing to it, as an
2889 argument, the other buffer, which is what Emacs will switch to.  If
2890 you are reading this in Info, try this now.  Evaluate the expression.
2891 (To get back, type @kbd{C-x b @key{RET}}.)@footnote{Remember, this
2892 expression will move you to your most recent other buffer that you
2893 cannot see.  If you really want to go to your most recently selected
2894 buffer, even if you can still see it, you need to evaluate the
2895 following more complex expression:
2897 @smallexample
2898 (switch-to-buffer (other-buffer (current-buffer) t))
2899 @end smallexample
2901 @c noindent
2902 In this case, the first argument to @code{other-buffer} tells it which
2903 buffer to skip---the current one---and the second argument tells
2904 @code{other-buffer} it is OK to switch to a visible buffer.
2905 In regular use, @code{switch-to-buffer} takes you to an invisible
2906 window since you would most likely use @kbd{C-x o} (@code{other-window})
2907 to go to another visible buffer.}
2909 In the programming examples in later sections of this document, you will
2910 see the function @code{set-buffer} more often than
2911 @code{switch-to-buffer}.  This is because of a difference between
2912 computer programs and humans: humans have eyes and expect to see the
2913 buffer on which they are working on their computer terminals.  This is
2914 so obvious, it almost goes without saying.  However, programs do not
2915 have eyes.  When a computer program works on a buffer, that buffer does
2916 not need to be visible on the screen.
2918 @code{switch-to-buffer} is designed for humans and does two different
2919 things: it switches the buffer to which Emacs' attention is directed; and
2920 it switches the buffer displayed in the window to the new buffer.
2921 @code{set-buffer}, on the other hand, does only one thing: it switches
2922 the attention of the computer program to a different buffer.  The buffer
2923 on the screen remains unchanged (of course, normally nothing happens
2924 there until the command finishes running).
2926 @cindex @samp{call} defined
2927 Also, we have just introduced another jargon term, the word @dfn{call}.
2928 When you evaluate a list in which the first symbol is a function, you
2929 are calling that function.  The use of the term comes from the notion of
2930 the function as an entity that can do something for you if you `call'
2931 it---just as a plumber is an entity who can fix a leak if you call him
2932 or her.
2934 @node Buffer Size & Locations, Evaluation Exercise, Switching Buffers, Practicing Evaluation
2935 @comment  node-name,  next,  previous,  up
2936 @section Buffer Size and the Location of Point
2937 @cindex Size of buffer
2938 @cindex Buffer size
2939 @cindex Point location
2940 @cindex Location of point
2942 Finally, let's look at several rather simple functions,
2943 @code{buffer-size}, @code{point}, @code{point-min}, and
2944 @code{point-max}.  These give information about the size of a buffer and
2945 the location of point within it.
2947 The function @code{buffer-size} tells you the size of the current
2948 buffer; that is, the function returns a count of the number of
2949 characters in the buffer.
2951 @smallexample
2952 (buffer-size)
2953 @end smallexample
2955 @noindent
2956 You can evaluate this in the usual way, by positioning the
2957 cursor after the expression and typing @kbd{C-x C-e}.
2959 @cindex @samp{point} defined
2960 In Emacs, the current  position of the cursor is called @dfn{point}.
2961 The expression @code{(point)} returns a number that tells you where the
2962 cursor is located as a count of the number of characters from the
2963 beginning of the buffer up to point.
2965 @need 1250
2966 You can see the character count for point in this buffer by evaluating
2967 the following expression in the usual way:
2969 @smallexample
2970 (point)
2971 @end smallexample
2973 @noindent
2974 As I write this, the value of @code{point} is 65724.  The @code{point}
2975 function is frequently used in some of the examples later in this
2976 book.
2978 @need 1250
2979 The value of point depends, of course, on its location within the
2980 buffer.  If you evaluate point in this spot, the number will be larger:
2982 @smallexample
2983 (point)
2984 @end smallexample
2986 @noindent
2987 For me, the value of point in this location is 66043, which means that
2988 there are 319 characters (including spaces) between the two expressions.
2990 @cindex @samp{narrowing} defined
2991 The function @code{point-min} is somewhat similar to @code{point}, but
2992 it returns the value of the minimum permissible value of point in the
2993 current buffer.  This is the number 1 unless @dfn{narrowing} is in
2994 effect.  (Narrowing is a mechanism whereby you can restrict yourself,
2995 or a program, to operations on just a part of a buffer.
2996 @xref{Narrowing & Widening, , Narrowing and Widening}.)  Likewise, the
2997 function @code{point-max} returns the value of the maximum permissible
2998 value of point in the current buffer.
3000 @node Evaluation Exercise,  , Buffer Size & Locations, Practicing Evaluation
3001 @section Exercise
3003 Find a file with which you are working and move towards its middle.
3004 Find its buffer name, file name, length, and your position in the file.
3006 @node Writing Defuns, Buffer Walk Through, Practicing Evaluation, Top
3007 @comment  node-name,  next,  previous,  up
3008 @chapter How To Write Function Definitions
3009 @cindex Definition writing
3010 @cindex Function definition writing
3011 @cindex Writing a function definition
3013 When the Lisp interpreter evaluates a list, it looks to see whether the
3014 first symbol on the list has a function definition attached to it; or,
3015 put another way, whether the symbol points to a function definition.  If
3016 it does, the computer carries out the instructions in the definition.  A
3017 symbol that has a function definition is called, simply, a function
3018 (although, properly speaking, the definition is the function and the
3019 symbol refers to it.)
3021 @menu
3022 * Primitive Functions::
3023 * defun::                       The @code{defun} special form.
3024 * Install::                     Install a function definition.
3025 * Interactive::                 Making a function interactive.
3026 * Interactive Options::         Different options for @code{interactive}.
3027 * Permanent Installation::      Installing code permanently.
3028 * let::                         Creating and initializing local variables.
3029 * if::                          What if?
3030 * else::                        If--then--else expressions.
3031 * Truth & Falsehood::           What Lisp considers false and true.
3032 * save-excursion::              Keeping track of point, mark, and buffer.
3033 * Review::
3034 * defun Exercises::
3035 @end menu
3037 @node Primitive Functions, defun, Writing Defuns, Writing Defuns
3038 @ifnottex
3039 @unnumberedsec An Aside about Primitive Functions
3040 @end ifnottex
3041 @cindex Primitive functions
3042 @cindex Functions, primitive
3044 @cindex C language primitives
3045 @cindex Primitives written in C
3046 All functions are defined in terms of other functions, except for a few
3047 @dfn{primitive} functions that are written in the C programming
3048 language.  When you write functions' definitions, you will write them in
3049 Emacs Lisp and use other functions as your building blocks.  Some of the
3050 functions you will use will themselves be written in Emacs Lisp (perhaps
3051 by you) and some will be primitives written in C.  The primitive
3052 functions are used exactly like those written in Emacs Lisp and behave
3053 like them.  They are written in C so we can easily run GNU Emacs on any
3054 computer that has sufficient power and can run C.
3056 Let me re-emphasize this: when you write code in Emacs Lisp, you do not
3057 distinguish between the use of functions written in C and the use of
3058 functions written in Emacs Lisp.  The difference is irrelevant.  I
3059 mention the distinction only because it is interesting to know.  Indeed,
3060 unless you investigate, you won't know whether an already-written
3061 function is written in Emacs Lisp or C.
3063 @node defun, Install, Primitive Functions, Writing Defuns
3064 @comment  node-name,  next,  previous,  up
3065 @section The @code{defun} Special Form
3066 @findex defun
3067 @cindex Special form of @code{defun}
3069 @cindex @samp{function definition} defined
3070 In Lisp, a symbol such as @code{mark-whole-buffer} has code attached to
3071 it that tells the computer what to do when the function is called.
3072 This code is called the @dfn{function definition} and is created by
3073 evaluating a Lisp expression that starts with the symbol @code{defun}
3074 (which is an abbreviation for @emph{define function}).  Because
3075 @code{defun} does not evaluate its arguments in the usual way, it is
3076 called a @dfn{special form}.
3078 In subsequent sections, we will look at function definitions from the
3079 Emacs source code, such as @code{mark-whole-buffer}.  In this section,
3080 we will describe a simple function definition so you can see how it
3081 looks.  This function definition uses arithmetic because it makes for a
3082 simple example.  Some people dislike examples using arithmetic; however,
3083 if you are such a person, do not despair.  Hardly any of the code we
3084 will study in the remainder of this introduction involves arithmetic or
3085 mathematics.  The examples mostly involve text in one way or another.
3087 A function definition has up to five parts following the word
3088 @code{defun}:
3090 @enumerate
3091 @item
3092 The name of the symbol to which the function definition should be
3093 attached.
3095 @item
3096 A list of the arguments that will be passed to the function.  If no
3097 arguments will be passed to the function, this is an empty list,
3098 @code{()}.
3100 @item
3101 Documentation describing the function.  (Technically optional, but
3102 strongly recommended.)
3104 @item
3105 Optionally, an expression to make the function interactive so you can
3106 use it by typing @kbd{M-x} and then the name of the function; or by
3107 typing an appropriate key or keychord.
3109 @cindex @samp{body} defined
3110 @item
3111 The code that instructs the computer what to do: the @dfn{body} of the
3112 function definition.
3113 @end enumerate
3115 It is helpful to think of the five parts of a function definition as
3116 being organized in a template, with slots for each part:
3118 @smallexample
3119 @group
3120 (defun @var{function-name} (@var{arguments}@dots{})
3121   "@var{optional-documentation}@dots{}"
3122   (interactive @var{argument-passing-info})     ; @r{optional}
3123   @var{body}@dots{})
3124 @end group
3125 @end smallexample
3127 As an example, here is the code for a function that multiplies its
3128 argument by 7.  (This example is not interactive.  @xref{Interactive,
3129 , Making a Function Interactive}, for that information.)
3131 @smallexample
3132 @group
3133 (defun multiply-by-seven (number)
3134   "Multiply NUMBER by seven."
3135   (* 7 number))
3136 @end group
3137 @end smallexample
3139 This definition begins with a parenthesis and the symbol @code{defun},
3140 followed by the name of the function.
3142 @cindex @samp{argument list} defined
3143 The name of the function is followed by a list that contains the
3144 arguments that will be passed to the function.  This list is called
3145 the @dfn{argument list}.  In this example, the list has only one
3146 element, the symbol, @code{number}.  When the function is used, the
3147 symbol will be bound to the value that is used as the argument to the
3148 function.
3150 Instead of choosing the word @code{number} for the name of the argument,
3151 I could have picked any other name.  For example, I could have chosen
3152 the word @code{multiplicand}.  I picked the word `number' because it
3153 tells what kind of value is intended for this slot; but I could just as
3154 well have chosen the word `multiplicand' to indicate the role that the
3155 value placed in this slot will play in the workings of the function.  I
3156 could have called it @code{foogle}, but that would have been a bad
3157 choice because it would not tell humans what it means.  The choice of
3158 name is up to the programmer and should be chosen to make the meaning of
3159 the function clear.
3161 Indeed, you can choose any name you wish for a symbol in an argument
3162 list, even the name of a symbol used in some other function: the name
3163 you use in an argument list is private to that particular definition.
3164 In that definition, the name refers to a different entity than any use
3165 of the same name outside the function definition.  Suppose you have a
3166 nick-name `Shorty' in your family; when your family members refer to
3167 `Shorty', they mean you.  But outside your family, in a movie, for
3168 example, the name `Shorty' refers to someone else.  Because a name in an
3169 argument list is private to the function definition, you can change the
3170 value of such a symbol inside the body of a function without changing
3171 its value outside the function.  The effect is similar to that produced
3172 by a @code{let} expression.  (@xref{let, , @code{let}}.)
3174 @ignore
3175 Note also that we discuss the word `number' in two different ways: as a
3176 symbol that appears in the code, and as the name of something that will
3177 be replaced by a something else during the evaluation of the function.
3178 In the first case, @code{number} is a symbol, not a number; it happens
3179 that within the function, it is a variable who value is the number in
3180 question, but our primary interest in it is as a symbol.  On the other
3181 hand, when we are talking about the function, our interest is that we
3182 will substitute a number for the word @var{number}.  To keep this
3183 distinction clear, we use different typography for the two
3184 circumstances.  When we talk about this function, or about how it works,
3185 we refer to this number by writing @var{number}.  In the function
3186 itself, we refer to it by writing @code{number}.
3187 @end ignore
3189 The argument list is followed by the documentation string that
3190 describes the function.  This is what you see when you type
3191 @w{@kbd{C-h f}} and the name of a function.  Incidentally, when you
3192 write a documentation string like this, you should make the first line
3193 a complete sentence since some commands, such as @code{apropos}, print
3194 only the first line of a multi-line documentation string.  Also, you
3195 should not indent the second line of a documentation string, if you
3196 have one, because that looks odd when you use @kbd{C-h f}
3197 (@code{describe-function}).  The documentation string is optional, but
3198 it is so useful, it should be included in almost every function you
3199 write.
3201 @findex * @r{(multiplication)}
3202 The third line of the example consists of the body of the function
3203 definition.  (Most functions' definitions, of course, are longer than
3204 this.)  In this function, the body is the list, @code{(* 7 number)}, which
3205 says to multiply the value of @var{number} by 7.  (In Emacs Lisp,
3206 @code{*} is the function for multiplication, just as @code{+} is the
3207 function for addition.)
3209 When you use the @code{multiply-by-seven} function, the argument
3210 @code{number} evaluates to the actual number you want used.  Here is an
3211 example that shows how @code{multiply-by-seven} is used; but don't try
3212 to evaluate this yet!
3214 @smallexample
3215 (multiply-by-seven 3)
3216 @end smallexample
3218 @noindent
3219 The symbol @code{number}, specified in the function definition in the
3220 next section, is given or ``bound to'' the value 3 in the actual use of
3221 the function.  Note that although @code{number} was inside parentheses
3222 in the function definition, the argument passed to the
3223 @code{multiply-by-seven} function is not in parentheses.  The
3224 parentheses are written in the function definition so the computer can
3225 figure out where the argument list ends and the rest of the function
3226 definition begins.
3228 If you evaluate this example, you are likely to get an error message.
3229 (Go ahead, try it!)  This is because we have written the function
3230 definition, but not yet told the computer about the definition---we have
3231 not yet installed (or `loaded') the function definition in Emacs.
3232 Installing a function is the process that tells the Lisp interpreter the
3233 definition of the function.  Installation is described in the next
3234 section.
3236 @node Install, Interactive, defun, Writing Defuns
3237 @comment  node-name,  next,  previous,  up
3238 @section Install a Function Definition
3239 @cindex Install a Function Definition
3240 @cindex Definition installation
3241 @cindex Function definition installation
3243 If you are reading this inside of Info in Emacs, you can try out the
3244 @code{multiply-by-seven} function by first evaluating the function
3245 definition and then evaluating @code{(multiply-by-seven 3)}.  A copy of
3246 the function definition follows.  Place the cursor after the last
3247 parenthesis of the function definition and type @kbd{C-x C-e}.  When you
3248 do this, @code{multiply-by-seven} will appear in the echo area.  (What
3249 this means is that when a function definition is evaluated, the value it
3250 returns is the name of the defined function.)  At the same time, this
3251 action installs the function definition.
3253 @smallexample
3254 @group
3255 (defun multiply-by-seven (number)
3256   "Multiply NUMBER by seven."
3257   (* 7 number))
3258 @end group
3259 @end smallexample
3261 @noindent
3262 By evaluating this @code{defun}, you have just installed
3263 @code{multiply-by-seven} in Emacs.  The function is now just as much a
3264 part of Emacs as @code{forward-word} or any other editing function you
3265 use.  (@code{multiply-by-seven} will stay installed until you quit
3266 Emacs.  To reload code automatically whenever you start Emacs, see
3267 @ref{Permanent Installation, , Installing Code Permanently}.)
3270 @menu
3271 * Effect of installation::
3272 * Change a defun::              How to change a function definition.
3273 @end menu
3275 @node Effect of installation, Change a defun, Install, Install
3276 @ifnottex
3277 @unnumberedsubsec The effect of installation
3278 @end ifnottex
3281 You can see the effect of installing @code{multiply-by-seven} by
3282 evaluating the following sample.  Place the cursor after the following
3283 expression and type @kbd{C-x C-e}.  The number 21 will appear in the
3284 echo area.
3286 @smallexample
3287 (multiply-by-seven 3)
3288 @end smallexample
3290 If you wish, you can read the documentation for the function by typing
3291 @kbd{C-h f} (@code{describe-function}) and then the name of the
3292 function, @code{multiply-by-seven}.  When you do this, a
3293 @file{*Help*} window will appear on your screen that says:
3295 @smallexample
3296 @group
3297 multiply-by-seven:
3298 Multiply NUMBER by seven.
3299 @end group
3300 @end smallexample
3302 @noindent
3303 (To return to a single window on your screen, type @kbd{C-x 1}.)
3305 @node Change a defun,  , Effect of installation, Install
3306 @comment  node-name,  next,  previous,  up
3307 @subsection Change a Function Definition
3308 @cindex Changing a function definition
3309 @cindex Function definition, how to change
3310 @cindex Definition, how to change
3312 If you want to change the code in @code{multiply-by-seven}, just rewrite
3313 it.  To install the new version in place of the old one, evaluate the
3314 function definition again.  This is how you modify code in Emacs.  It is
3315 very simple.
3317 As an example, you can change the @code{multiply-by-seven} function to
3318 add the number to itself seven times instead of multiplying the number
3319 by seven.  It produces the same answer, but by a different path.  At
3320 the same time, we will add a comment to the code; a comment is text
3321 that the Lisp interpreter ignores, but that a human reader may find
3322 useful or enlightening.  The comment is that this is the ``second
3323 version''.
3325 @smallexample
3326 @group
3327 (defun multiply-by-seven (number)       ; @r{Second version.}
3328   "Multiply NUMBER by seven."
3329   (+ number number number number number number number))
3330 @end group
3331 @end smallexample
3333 @cindex Comments in Lisp code
3334 The comment follows a semicolon, @samp{;}.  In Lisp, everything on a
3335 line that follows a semicolon is a comment.  The end of the line is the
3336 end of the comment.  To stretch a comment over two or more lines, begin
3337 each line with a semicolon.
3339 @xref{Beginning a .emacs File, , Beginning a @file{.emacs}
3340 File}, and @ref{Comments, , Comments, elisp, The GNU Emacs Lisp
3341 Reference Manual}, for more about comments.
3343 You can install this version of the @code{multiply-by-seven} function by
3344 evaluating it in the same way you evaluated the first function: place
3345 the cursor after the last parenthesis and type @kbd{C-x C-e}.
3347 In summary, this is how you write code in Emacs Lisp: you write a
3348 function; install it; test it; and then make fixes or enhancements and
3349 install it again.
3351 @node Interactive, Interactive Options, Install, Writing Defuns
3352 @comment  node-name,  next,  previous,  up
3353 @section Make a Function Interactive
3354 @cindex Interactive functions
3355 @findex interactive
3357 You make a function interactive by placing a list that begins with
3358 the special form @code{interactive} immediately after the
3359 documentation.  A user can invoke an interactive function by typing
3360 @kbd{M-x} and then the name of the function; or by typing the keys to
3361 which it is bound, for example, by typing @kbd{C-n} for
3362 @code{next-line} or @kbd{C-x h} for @code{mark-whole-buffer}.
3364 Interestingly, when you call an interactive function interactively,
3365 the value returned is not automatically displayed in the echo area.
3366 This is because you often call an interactive function for its side
3367 effects, such as moving forward by a word or line, and not for the
3368 value returned.  If the returned value were displayed in the echo area
3369 each time you typed a key, it would be very distracting.
3371 @menu
3372 * Interactive multiply-by-seven::  An overview.
3373 * multiply-by-seven in detail::  The interactive version.
3374 @end menu
3376 @node Interactive multiply-by-seven, multiply-by-seven in detail, Interactive, Interactive
3377 @ifnottex
3378 @unnumberedsubsec An Interactive @code{multiply-by-seven}, An Overview
3379 @end ifnottex
3381 Both the use of the special form @code{interactive} and one way to
3382 display a value in the echo area can be illustrated by creating an
3383 interactive version of @code{multiply-by-seven}.
3385 @need 1250
3386 Here is the code:
3388 @smallexample
3389 @group
3390 (defun multiply-by-seven (number)       ; @r{Interactive version.}
3391   "Multiply NUMBER by seven."
3392   (interactive "p")
3393   (message "The result is %d" (* 7 number)))
3394 @end group
3395 @end smallexample
3397 @noindent
3398 You can install this code by placing your cursor after it and typing
3399 @kbd{C-x C-e}.  The name of the function will appear in your echo area.
3400 Then, you can use this code by typing @kbd{C-u} and a number and then
3401 typing @kbd{M-x multiply-by-seven} and pressing @key{RET}.  The phrase
3402 @samp{The result is @dots{}} followed by the product will appear in the
3403 echo area.
3405 Speaking more generally, you invoke a function like this in either of two
3406 ways:
3408 @enumerate
3409 @item
3410 By typing a prefix argument that contains the number to be passed, and
3411 then typing @kbd{M-x} and the name of the function, as with
3412 @kbd{C-u 3 M-x forward-sentence}; or,
3414 @item
3415 By typing whatever key or keychord the function is bound to, as with
3416 @kbd{C-u 3 M-e}.
3417 @end enumerate
3419 @noindent
3420 Both the examples just mentioned work identically to move point forward
3421 three sentences.  (Since @code{multiply-by-seven} is not bound to a key,
3422 it could not be used as an example of key binding.)
3424 (@xref{Keybindings, , Some Keybindings}, to learn how to bind a command
3425 to a key.)
3427 A prefix argument is passed to an interactive function by typing the
3428 @key{META} key followed by a number, for example, @kbd{M-3 M-e}, or by
3429 typing @kbd{C-u} and then a number, for example, @kbd{C-u 3 M-e} (if you
3430 type @kbd{C-u} without a number, it defaults to 4).
3432 @node multiply-by-seven in detail,  , Interactive multiply-by-seven, Interactive
3433 @comment  node-name,  next,  previous,  up
3434 @subsection An Interactive @code{multiply-by-seven}
3436 Let's look at the use of the special form @code{interactive} and then at
3437 the function @code{message} in the interactive version of
3438 @code{multiply-by-seven}.  You will recall that the function definition
3439 looks like this:
3441 @smallexample
3442 @group
3443 (defun multiply-by-seven (number)       ; @r{Interactive version.}
3444   "Multiply NUMBER by seven."
3445   (interactive "p")
3446   (message "The result is %d" (* 7 number)))
3447 @end group
3448 @end smallexample
3450 In this function, the expression, @code{(interactive "p")}, is a list of
3451 two elements.  The @code{"p"} tells Emacs to pass the prefix argument to
3452 the function and use its value for the argument of the function.
3454 @need 1000
3455 The argument will be a number.  This means that the symbol
3456 @code{number} will be bound to a number in the line:
3458 @smallexample
3459 (message "The result is %d" (* 7 number))
3460 @end smallexample
3462 @need 1250
3463 @noindent
3464 For example, if your prefix argument is 5, the Lisp interpreter will
3465 evaluate the line as if it were:
3467 @smallexample
3468 (message "The result is %d" (* 7 5))
3469 @end smallexample
3471 @noindent
3472 (If you are reading this in GNU Emacs, you can evaluate this expression
3473 yourself.)  First, the interpreter will evaluate the inner list, which
3474 is @code{(* 7 5)}.  This returns a value of 35.  Next, it
3475 will evaluate the outer list, passing the values of the second and
3476 subsequent elements of the list to the function @code{message}.
3478 As we have seen, @code{message} is an Emacs Lisp function especially
3479 designed for sending a one line message to a user.  (@xref{message, , The
3480 @code{message} function}.)
3481 In summary, the @code{message} function prints its first argument in the
3482 echo area as is, except for occurrences of @samp{%d}, @samp{%s}, or
3483 @samp{%c}.  When it sees one of these control sequences, the function
3484 looks to the second and subsequent arguments and prints the value of the
3485 argument in the location in the string where the control sequence is
3486 located.
3488 In the interactive @code{multiply-by-seven} function, the control string
3489 is @samp{%d}, which requires a number, and the value returned by
3490 evaluating @code{(* 7 5)} is the number 35.  Consequently, the number 35
3491 is printed in place of the @samp{%d} and the message is @samp{The result
3492 is 35}.
3494 (Note that when you call the function @code{multiply-by-seven}, the
3495 message is printed without quotes, but when you call @code{message}, the
3496 text is printed in double quotes.  This is because the value returned by
3497 @code{message} is what appears in the echo area when you evaluate an
3498 expression whose first element is @code{message}; but when embedded in a
3499 function, @code{message} prints the text as a side effect without
3500 quotes.)
3502 @node Interactive Options, Permanent Installation, Interactive, Writing Defuns
3503 @comment  node-name,  next,  previous,  up
3504 @section Different Options for @code{interactive}
3505 @cindex Options for @code{interactive}
3506 @cindex Interactive options
3508 In the example, @code{multiply-by-seven} used @code{"p"} as the
3509 argument to @code{interactive}.  This argument told Emacs to interpret
3510 your typing either @kbd{C-u} followed by a number or @key{META}
3511 followed by a number as a command to pass that number to the function
3512 as its argument.  Emacs has more than twenty characters predefined for
3513 use with @code{interactive}.  In almost every case, one of these
3514 options will enable you to pass the right information interactively to
3515 a function.  (@xref{Interactive Codes, , Code Characters for
3516 @code{interactive}, elisp, The GNU Emacs Lisp Reference Manual}.)
3518 @need 1250
3519 For example, the character @samp{r} causes Emacs to pass the beginning
3520 and end of the region (the current values of point and mark) to the
3521 function as two separate arguments.  It is used as follows:
3523 @smallexample
3524 (interactive "r")
3525 @end smallexample
3527 On the other hand, a @samp{B} tells Emacs to ask for the name of a
3528 buffer that will be passed to the function.  When it sees a @samp{B},
3529 Emacs will ask for the name by prompting the user in the minibuffer,
3530 using a string that follows the @samp{B}, as in @code{"BAppend to
3531 buffer:@: "}.  Not only will Emacs prompt for the name, but Emacs will
3532 complete the name if you type enough of it and press @key{TAB}.
3534 A function with two or more arguments can have information passed to
3535 each argument by adding parts to the string that follows
3536 @code{interactive}.  When you do this, the information is passed to
3537 each argument in the same order it is specified in the
3538 @code{interactive} list.  In the string, each part is separated from
3539 the next part by a @samp{\n}, which is a newline.  For example, you
3540 could follow @code{"BAppend to buffer:@: "} with a @samp{\n}) and an
3541 @samp{r}.  This would cause Emacs to pass the values of point and mark
3542 to the function as well as prompt you for the buffer---three arguments
3543 in all.
3545 In this case, the function definition would look like the following,
3546 where @code{buffer}, @code{start}, and @code{end} are the symbols to
3547 which @code{interactive} binds the buffer and the current values of the
3548 beginning and ending of the region:
3550 @smallexample
3551 @group
3552 (defun @var{name-of-function} (buffer start end)
3553   "@var{documentation}@dots{}"
3554   (interactive "BAppend to buffer:@: \nr")
3555   @var{body-of-function}@dots{})
3556 @end group
3557 @end smallexample
3559 @noindent
3560 (The space after the colon in the prompt makes it look better when you
3561 are prompted.  The @code{append-to-buffer} function looks exactly like
3562 this.  @xref{append-to-buffer, , The Definition of
3563 @code{append-to-buffer}}.)
3565 If a function does not have arguments, then @code{interactive} does not
3566 require any.  Such a function contains the simple expression
3567 @code{(interactive)}.  The @code{mark-whole-buffer} function is like
3568 this.
3570 Alternatively, if the special letter-codes are not right for your
3571 application, you can pass your own arguments to @code{interactive} as
3572 a list.  @xref{interactive, , Using @code{Interactive}, elisp, The
3573 GNU Emacs Lisp Reference Manual}, for more information about this advanced
3574 technique.
3576 @node Permanent Installation, let, Interactive Options, Writing Defuns
3577 @comment  node-name,  next,  previous,  up
3578 @section Install Code Permanently
3579 @cindex Install code permanently
3580 @cindex Permanent code installation
3581 @cindex Code installation
3583 When you install a function definition by evaluating it, it will stay
3584 installed until you quit Emacs.  The next time you start a new session
3585 of Emacs, the function will not be installed unless you evaluate the
3586 function definition again.
3588 At some point, you may want to have code installed automatically
3589 whenever you start a new session of Emacs.  There are several ways of
3590 doing this:
3592 @itemize @bullet
3593 @item
3594 If you have code that is just for yourself, you can put the code for the
3595 function definition in your @file{.emacs} initialization file.  When you
3596 start Emacs, your @file{.emacs} file is automatically evaluated and all
3597 the function definitions within it are installed.
3598 @xref{Emacs Initialization, , Your @file{.emacs} File}.
3600 @item
3601 Alternatively, you can put the function definitions that you want
3602 installed in one or more files of their own and use the @code{load}
3603 function to cause Emacs to evaluate and thereby install each of the
3604 functions in the files.
3605 @xref{Loading Files, , Loading Files}.
3607 @item
3608 On the other hand, if you have code that your whole site will use, it
3609 is usual to put it in a file called @file{site-init.el} that is loaded
3610 when Emacs is built.  This makes the code available to everyone who
3611 uses your machine.  (See the @file{INSTALL} file that is part of the
3612 Emacs distribution.)
3613 @end itemize
3615 Finally, if you have code that everyone who uses Emacs may want, you
3616 can post it on a computer network or send a copy to the Free Software
3617 Foundation.  (When you do this, please license the code and its
3618 documentation under a license that permits other people to run, copy,
3619 study, modify, and redistribute the code and which protects you from
3620 having your work taken from you.)  If you send a copy of your code to
3621 the Free Software Foundation, and properly protect yourself and
3622 others, it may be included in the next release of Emacs.  In large
3623 part, this is how Emacs has grown over the past years, by donations.
3625 @node let, if, Permanent Installation, Writing Defuns
3626 @comment  node-name,  next,  previous,  up
3627 @section @code{let}
3628 @findex let
3630 The @code{let} expression is a special form in Lisp that you will need
3631 to use in most function definitions.
3633 @code{let} is used to attach or bind a symbol to a value in such a way
3634 that the Lisp interpreter will not confuse the variable with a
3635 variable of the same name that is not part of the function.
3637 To understand why the @code{let} special form is necessary, consider
3638 the situation in which you own a home that you generally refer to as
3639 `the house', as in the sentence, ``The house needs painting.''  If you
3640 are visiting a friend and your host refers to `the house', he is
3641 likely to be referring to @emph{his} house, not yours, that is, to a
3642 different house.
3644 If your friend is referring to his house and you think he is referring
3645 to your house, you may be in for some confusion.  The same thing could
3646 happen in Lisp if a variable that is used inside of one function has
3647 the same name as a variable that is used inside of another function,
3648 and the two are not intended to refer to the same value.  The
3649 @code{let} special form prevents this kind of confusion.
3651 @menu
3652 * Prevent confusion::
3653 * Parts of let Expression::
3654 * Sample let Expression::
3655 * Uninitialized let Variables::
3656 @end menu
3658 @node Prevent confusion, Parts of let Expression, let, let
3659 @ifnottex
3660 @unnumberedsubsec @code{let} Prevents Confusion
3661 @end ifnottex
3663 @cindex @samp{local variable} defined
3664 The @code{let} special form prevents confusion.  @code{let} creates a
3665 name for a @dfn{local variable} that overshadows any use of the same
3666 name outside the @code{let} expression.  This is like understanding
3667 that whenever your host refers to `the house', he means his house, not
3668 yours.  (Symbols used in argument lists work the same way.
3669 @xref{defun, , The @code{defun} Special Form}.)
3671 Local variables created by a @code{let} expression retain their value
3672 @emph{only} within the @code{let} expression itself (and within
3673 expressions called within the @code{let} expression); the local
3674 variables have no effect outside the @code{let} expression.
3676 Another way to think about @code{let} is that it is like a @code{setq}
3677 that is temporary and local.  The values set by @code{let} are
3678 automatically undone when the @code{let} is finished.  The setting
3679 only affects expressions that are inside the bounds of the @code{let}
3680 expression.  In computer science jargon, we would say ``the binding of
3681 a symbol is visible only in functions called in the @code{let} form;
3682 in Emacs Lisp, scoping is dynamic, not lexical.''
3684 @code{let} can create more than one variable at once.  Also,
3685 @code{let} gives each variable it creates an initial value, either a
3686 value specified by you, or @code{nil}.  (In the jargon, this is called
3687 `binding the variable to the value'.)  After @code{let} has created
3688 and bound the variables, it executes the code in the body of the
3689 @code{let}, and returns the value of the last expression in the body,
3690 as the value of the whole @code{let} expression.  (`Execute' is a jargon
3691 term that means to evaluate a list; it comes from the use of the word
3692 meaning `to give practical effect to' (@cite{Oxford English
3693 Dictionary}).  Since you evaluate an expression to perform an action,
3694 `execute' has evolved as a synonym to `evaluate'.)
3696 @node Parts of let Expression, Sample let Expression, Prevent confusion, let
3697 @comment  node-name,  next,  previous,  up
3698 @subsection The Parts of a @code{let} Expression
3699 @cindex @code{let} expression, parts of
3700 @cindex Parts of @code{let} expression
3702 @cindex @samp{varlist} defined
3703 A @code{let} expression is a list of three parts.  The first part is
3704 the symbol @code{let}.  The second part is a list, called a
3705 @dfn{varlist}, each element of which is either a symbol by itself or a
3706 two-element list, the first element of which is a symbol.  The third
3707 part of the @code{let} expression is the body of the @code{let}.  The
3708 body usually consists of one or more lists.
3710 @need 800
3711 A template for a @code{let} expression looks like this:
3713 @smallexample
3714 (let @var{varlist} @var{body}@dots{})
3715 @end smallexample
3717 @noindent
3718 The symbols in the varlist are the variables that are given initial
3719 values by the @code{let} special form.  Symbols by themselves are given
3720 the initial value of @code{nil}; and each symbol that is the first
3721 element of a two-element list is bound to the value that is returned
3722 when the Lisp interpreter evaluates the second element.
3724 Thus, a varlist might look like this: @code{(thread (needles 3))}.  In
3725 this case, in a @code{let} expression, Emacs binds the symbol
3726 @code{thread} to an initial value of @code{nil}, and binds the symbol
3727 @code{needles} to an initial value of 3.
3729 When you write a @code{let} expression, what you do is put the
3730 appropriate expressions in the slots of the @code{let} expression
3731 template.
3733 If the varlist is composed of two-element lists, as is often the case,
3734 the template for the @code{let} expression looks like this:
3736 @smallexample
3737 @group
3738 (let ((@var{variable} @var{value})
3739       (@var{variable} @var{value})
3740       @dots{})
3741   @var{body}@dots{})
3742 @end group
3743 @end smallexample
3745 @node Sample let Expression, Uninitialized let Variables, Parts of let Expression, let
3746 @comment  node-name,  next,  previous,  up
3747 @subsection Sample @code{let} Expression
3748 @cindex Sample @code{let} expression
3749 @cindex @code{let} expression sample
3751 The following expression creates and gives initial values
3752 to the two variables @code{zebra} and @code{tiger}.  The body of the
3753 @code{let} expression is a list which calls the @code{message} function.
3755 @smallexample
3756 @group
3757 (let ((zebra 'stripes)
3758       (tiger 'fierce))
3759   (message "One kind of animal has %s and another is %s."
3760            zebra tiger))
3761 @end group
3762 @end smallexample
3764 Here, the varlist is @code{((zebra 'stripes) (tiger 'fierce))}.
3766 The two variables are @code{zebra} and @code{tiger}.  Each variable is
3767 the first element of a two-element list and each value is the second
3768 element of its two-element list.  In the varlist, Emacs binds the
3769 variable @code{zebra} to the value @code{stripes}, and binds the
3770 variable @code{tiger} to the value @code{fierce}.  In this example,
3771 both values are symbols preceded by a quote.  The values could just as
3772 well have been another list or a string.  The body of the @code{let}
3773 follows after the list holding the variables.  In this example, the body
3774 is a list that uses the @code{message} function to print a string in
3775 the echo area.
3777 @need 1500
3778 You may evaluate the example in the usual fashion, by placing the
3779 cursor after the last parenthesis and typing @kbd{C-x C-e}.  When you do
3780 this, the following will appear in the echo area:
3782 @smallexample
3783 "One kind of animal has stripes and another is fierce."
3784 @end smallexample
3786 As we have seen before, the @code{message} function prints its first
3787 argument, except for @samp{%s}.  In this example, the value of the variable
3788 @code{zebra} is printed at the location of the first @samp{%s} and the
3789 value of the variable @code{tiger} is printed at the location of the
3790 second @samp{%s}.
3792 @node Uninitialized let Variables,  , Sample let Expression, let
3793 @comment  node-name,  next,  previous,  up
3794 @subsection Uninitialized Variables in a @code{let} Statement
3795 @cindex Uninitialized @code{let} variables
3796 @cindex @code{let} variables uninitialized
3798 If you do not bind the variables in a @code{let} statement to specific
3799 initial values, they will automatically be bound to an initial value of
3800 @code{nil}, as in the following expression:
3802 @smallexample
3803 @group
3804 (let ((birch 3)
3805       pine
3806       fir
3807       (oak 'some))
3808   (message
3809    "Here are %d variables with %s, %s, and %s value."
3810    birch pine fir oak))
3811 @end group
3812 @end smallexample
3814 @noindent
3815 Here, the varlist is @code{((birch 3) pine fir (oak 'some))}.
3817 @need 1250
3818 If you evaluate this expression in the usual way, the following will
3819 appear in your echo area:
3821 @smallexample
3822 "Here are 3 variables with nil, nil, and some value."
3823 @end smallexample
3825 @noindent
3826 In this example, Emacs binds the symbol @code{birch} to the number 3,
3827 binds the symbols @code{pine} and @code{fir} to @code{nil}, and binds
3828 the symbol @code{oak} to the value @code{some}.
3830 Note that in the first part of the @code{let}, the variables @code{pine}
3831 and @code{fir} stand alone as atoms that are not surrounded by
3832 parentheses; this is because they are being bound to @code{nil}, the
3833 empty list.  But @code{oak} is bound to @code{some} and so is a part of
3834 the list @code{(oak 'some)}.  Similarly, @code{birch} is bound to the
3835 number 3 and so is in a list with that number.  (Since a number
3836 evaluates to itself, the number does not need to be quoted.  Also, the
3837 number is printed in the message using a @samp{%d} rather than a
3838 @samp{%s}.)  The four variables as a group are put into a list to
3839 delimit them from the body of the @code{let}.
3841 @node if, else, let, Writing Defuns
3842 @comment  node-name,  next,  previous,  up
3843 @section The @code{if} Special Form
3844 @findex if
3845 @cindex Conditional with @code{if}
3847 A third special form, in addition to @code{defun} and @code{let}, is the
3848 conditional @code{if}.  This form is used to instruct the computer to
3849 make decisions.  You can write function definitions without using
3850 @code{if}, but it is used often enough, and is important enough, to be
3851 included here.  It is used, for example, in the code for the
3852 function @code{beginning-of-buffer}.
3854 The basic idea behind an @code{if}, is that ``@emph{if} a test is true,
3855 @emph{then} an expression is evaluated.''  If the test is not true, the
3856 expression is not evaluated.  For example, you might make a decision
3857 such as, ``if it is warm and sunny, then go to the beach!''
3859 @menu
3860 * if in more detail::
3861 * type-of-animal in detail::    An example of an @code{if} expression.
3862 @end menu
3864 @node if in more detail, type-of-animal in detail, if, if
3865 @ifnottex
3866 @unnumberedsubsec @code{if} in more detail
3867 @end ifnottex
3869 @cindex @samp{if-part} defined
3870 @cindex @samp{then-part} defined
3871 An @code{if} expression written in Lisp does not use the word `then';
3872 the test and the action are the second and third elements of the list
3873 whose first element is @code{if}.  Nonetheless, the test part of an
3874 @code{if} expression is often called the @dfn{if-part} and the second
3875 argument is often called the @dfn{then-part}.
3877 Also, when an @code{if} expression is written, the true-or-false-test
3878 is usually written on the same line as the symbol @code{if}, but the
3879 action to carry out if the test is true, the ``then-part'', is written
3880 on the second and subsequent lines.  This makes the @code{if}
3881 expression easier to read.
3883 @smallexample
3884 @group
3885 (if @var{true-or-false-test}
3886     @var{action-to-carry-out-if-test-is-true})
3887 @end group
3888 @end smallexample
3890 @noindent
3891 The true-or-false-test will be an expression that
3892 is evaluated by the Lisp interpreter.
3894 Here is an example that you can evaluate in the usual manner.  The test
3895 is whether the number 5 is greater than the number 4.  Since it is, the
3896 message @samp{5 is greater than 4!} will be printed.
3898 @smallexample
3899 @group
3900 (if (> 5 4)                             ; @r{if-part}
3901     (message "5 is greater than 4!"))   ; @r{then-part}
3902 @end group
3903 @end smallexample
3905 @noindent
3906 (The function @code{>} tests whether its first argument is greater than
3907 its second argument and returns true if it is.)
3908 @findex > (greater than)
3910 Of course, in actual use, the test in an @code{if} expression will not
3911 be fixed for all time as it is by the expression @code{(> 5 4)}.
3912 Instead, at least one of the variables used in the test will be bound to
3913 a value that is not known ahead of time.  (If the value were known ahead
3914 of time, we would not need to run the test!)
3916 For example, the value may be bound to an argument of a function
3917 definition.  In the following function definition, the character of the
3918 animal is a value that is passed to the function.  If the value bound to
3919 @code{characteristic} is @code{fierce}, then the message, @samp{It's a
3920 tiger!} will be printed; otherwise, @code{nil} will be returned.
3922 @smallexample
3923 @group
3924 (defun type-of-animal (characteristic)
3925   "Print message in echo area depending on CHARACTERISTIC.
3926 If the CHARACTERISTIC is the symbol `fierce',
3927 then warn of a tiger."
3928   (if (equal characteristic 'fierce)
3929       (message "It's a tiger!")))
3930 @end group
3931 @end smallexample
3933 @need 1500
3934 @noindent
3935 If you are reading this inside of GNU Emacs, you can evaluate the
3936 function definition in the usual way to install it in Emacs, and then you
3937 can evaluate the following two expressions to see the results:
3939 @smallexample
3940 @group
3941 (type-of-animal 'fierce)
3943 (type-of-animal 'zebra)
3945 @end group
3946 @end smallexample
3948 @c Following sentences rewritten to prevent overfull hbox.
3949 @noindent
3950 When you evaluate @code{(type-of-animal 'fierce)}, you will see the
3951 following message printed in the echo area: @code{"It's a tiger!"}; and
3952 when you evaluate @code{(type-of-animal 'zebra)} you will see @code{nil}
3953 printed in the echo area.
3955 @node type-of-animal in detail,  , if in more detail, if
3956 @comment  node-name,  next,  previous,  up
3957 @subsection The @code{type-of-animal} Function in Detail
3959 Let's look at the @code{type-of-animal} function in detail.
3961 The function definition for @code{type-of-animal} was written by filling
3962 the slots of two templates, one for a function definition as a whole, and
3963 a second for an @code{if} expression.
3965 @need 1250
3966 The template for every function that is not interactive is:
3968 @smallexample
3969 @group
3970 (defun @var{name-of-function} (@var{argument-list})
3971   "@var{documentation}@dots{}"
3972   @var{body}@dots{})
3973 @end group
3974 @end smallexample
3976 @need 800
3977 The parts of the function that match this template look like this:
3979 @smallexample
3980 @group
3981 (defun type-of-animal (characteristic)
3982   "Print message in echo area depending on CHARACTERISTIC.
3983 If the CHARACTERISTIC is the symbol `fierce',
3984 then warn of a tiger."
3985   @var{body: the} @code{if} @var{expression})
3986 @end group
3987 @end smallexample
3989 The name of function is @code{type-of-animal}; it is passed the value
3990 of one argument.  The argument list is followed by a multi-line
3991 documentation string.  The documentation string is included in the
3992 example because it is a good habit to write documentation string for
3993 every function definition.  The body of the function definition
3994 consists of the @code{if} expression.
3996 @need 800
3997 The template for an @code{if} expression looks like this:
3999 @smallexample
4000 @group
4001 (if @var{true-or-false-test}
4002     @var{action-to-carry-out-if-the-test-returns-true})
4003 @end group
4004 @end smallexample
4006 @need 1250
4007 In the @code{type-of-animal} function, the code for the @code{if}
4008 looks like this:
4010 @smallexample
4011 @group
4012 (if (equal characteristic 'fierce)
4013     (message "It's a tiger!")))
4014 @end group
4015 @end smallexample
4017 @need 800
4018 Here, the true-or-false-test is the expression:
4020 @smallexample
4021 (equal characteristic 'fierce)
4022 @end smallexample
4024 @noindent
4025 In Lisp, @code{equal} is a function that determines whether its first
4026 argument is equal to its second argument.  The second argument is the
4027 quoted symbol @code{'fierce} and the first argument is the value of the
4028 symbol @code{characteristic}---in other words, the argument passed to
4029 this function.
4031 In the first exercise of @code{type-of-animal}, the argument
4032 @code{fierce} is passed to @code{type-of-animal}.  Since @code{fierce}
4033 is equal to @code{fierce}, the expression, @code{(equal characteristic
4034 'fierce)}, returns a value of true.  When this happens, the @code{if}
4035 evaluates the second argument or then-part of the @code{if}:
4036 @code{(message "It's tiger!")}.
4038 On the other hand, in the second exercise of @code{type-of-animal}, the
4039 argument @code{zebra} is passed to @code{type-of-animal}.  @code{zebra}
4040 is not equal to @code{fierce}, so the then-part is not evaluated and
4041 @code{nil} is returned by the @code{if} expression.
4043 @node else, Truth & Falsehood, if, Writing Defuns
4044 @comment  node-name,  next,  previous,  up
4045 @section If--then--else Expressions
4046 @cindex Else
4048 An @code{if} expression may have an optional third argument, called
4049 the @dfn{else-part}, for the case when the true-or-false-test returns
4050 false.  When this happens, the second argument or then-part of the
4051 overall @code{if} expression is @emph{not} evaluated, but the third or
4052 else-part @emph{is} evaluated.  You might think of this as the cloudy
4053 day alternative for the decision `if it is warm and sunny, then go to
4054 the beach, else read a book!''.
4056 The word ``else'' is not written in the Lisp code; the else-part of an
4057 @code{if} expression comes after the then-part.  In the written Lisp, the
4058 else-part is usually written to start on a line of its own and is
4059 indented less than the then-part:
4061 @smallexample
4062 @group
4063 (if @var{true-or-false-test}
4064     @var{action-to-carry-out-if-the-test-returns-true}
4065   @var{action-to-carry-out-if-the-test-returns-false})
4066 @end group
4067 @end smallexample
4069 For example, the following @code{if} expression prints the message @samp{4
4070 is not greater than 5!} when you evaluate it in the usual way:
4072 @smallexample
4073 @group
4074 (if (> 4 5)                             ; @r{if-part}
4075     (message "5 is greater than 4!")    ; @r{then-part}
4076   (message "4 is not greater than 5!")) ; @r{else-part}
4077 @end group
4078 @end smallexample
4080 @noindent
4081 Note that the different levels of indentation make it easy to
4082 distinguish the then-part from the else-part.  (GNU Emacs has several
4083 commands that automatically indent @code{if} expressions correctly.
4084 @xref{Typing Lists, , GNU Emacs Helps You Type Lists}.)
4086 We can extend the @code{type-of-animal} function to include an
4087 else-part by simply incorporating an additional part to the @code{if}
4088 expression.
4090 @need 1500
4091 You can see the consequences of doing this if you evaluate the following
4092 version of the @code{type-of-animal} function definition to install it
4093 and then evaluate the two subsequent expressions to pass different
4094 arguments to the function.
4096 @smallexample
4097 @group
4098 (defun type-of-animal (characteristic)  ; @r{Second version.}
4099   "Print message in echo area depending on CHARACTERISTIC.
4100 If the CHARACTERISTIC is the symbol `fierce',
4101 then warn of a tiger;
4102 else say it's not fierce."
4103   (if (equal characteristic 'fierce)
4104       (message "It's a tiger!")
4105     (message "It's not fierce!")))
4106 @end group
4107 @end smallexample
4108 @sp 1
4110 @smallexample
4111 @group
4112 (type-of-animal 'fierce)
4114 (type-of-animal 'zebra)
4116 @end group
4117 @end smallexample
4119 @c Following sentence rewritten to prevent overfull hbox.
4120 @noindent
4121 When you evaluate @code{(type-of-animal 'fierce)}, you will see the
4122 following message printed in the echo area: @code{"It's a tiger!"}; but
4123 when you evaluate @code{(type-of-animal 'zebra)}, you will see
4124 @code{"It's not fierce!"}.
4126 (Of course, if the @var{characteristic} were @code{ferocious}, the
4127 message @code{"It's not fierce!"} would be printed; and it would be
4128 misleading!  When you write code, you need to take into account the
4129 possibility that some such argument will be tested by the @code{if} and
4130 write your program accordingly.)
4132 @node Truth & Falsehood, save-excursion, else, Writing Defuns
4133 @comment  node-name,  next,  previous,  up
4134 @section Truth and Falsehood in Emacs Lisp
4135 @cindex Truth and falsehood in Emacs Lisp
4136 @cindex Falsehood and truth in Emacs Lisp
4137 @findex nil
4139 There is an important aspect to the truth test in an @code{if}
4140 expression.  So far, we have spoken of `true' and `false' as values of
4141 predicates as if they were new kinds of Emacs Lisp objects.  In fact,
4142 `false' is just our old friend @code{nil}.  Anything else---anything
4143 at all---is `true'.
4145 The expression that tests for truth is interpreted as @dfn{true}
4146 if the result of evaluating it is a value that is not @code{nil}.  In
4147 other words, the result of the test is considered true if the value
4148 returned is a number such as 47, a string such as @code{"hello"}, or a
4149 symbol (other than @code{nil}) such as @code{flowers}, or a list, or
4150 even a buffer!
4152 @menu
4153 * nil explained::               @code{nil} has two meanings.
4154 @end menu
4156 @node nil explained,  , Truth & Falsehood, Truth & Falsehood
4157 @ifnottex
4158 @unnumberedsubsec An explanation of @code{nil}
4159 @end ifnottex
4161 Before illustrating a test for truth, we need an explanation of @code{nil}.
4163 In Emacs Lisp, the symbol @code{nil} has two meanings.  First, it means the
4164 empty list.  Second, it means false and is the value returned when a
4165 true-or-false-test tests false.  @code{nil} can be written as an empty
4166 list, @code{()}, or as @code{nil}.  As far as the Lisp interpreter is
4167 concerned, @code{()} and @code{nil} are the same.  Humans, however, tend
4168 to use @code{nil} for false and @code{()} for the empty list.
4170 In Emacs Lisp, any value that is not @code{nil}---is not the empty
4171 list---is considered true.  This means that if an evaluation returns
4172 something that is not an empty list, an @code{if} expression will test
4173 true.  For example, if a number is put in the slot for the test, it
4174 will be evaluated and will return itself, since that is what numbers
4175 do when evaluated.  In this conditional, the @code{if} expression will
4176 test true.  The expression tests false only when @code{nil}, an empty
4177 list, is returned by evaluating the expression.
4179 You can see this by evaluating the two expressions in the following examples.
4181 In the first example, the number 4 is evaluated as the test in the
4182 @code{if} expression and returns itself; consequently, the then-part
4183 of the expression is evaluated and returned: @samp{true} appears in
4184 the echo area.  In the second example, the @code{nil} indicates false;
4185 consequently, the else-part of the expression is evaluated and
4186 returned: @samp{false} appears in the echo area.
4188 @smallexample
4189 @group
4190 (if 4
4191     'true
4192   'false)
4193 @end group
4195 @group
4196 (if nil
4197     'true
4198   'false)
4199 @end group
4200 @end smallexample
4202 @need 1250
4203 Incidentally, if some other useful value is not available for a test that
4204 returns true, then the Lisp interpreter will return the symbol @code{t}
4205 for true.  For example, the expression @code{(> 5 4)} returns @code{t}
4206 when evaluated, as you can see by evaluating it in the usual way:
4208 @smallexample
4209 (> 5 4)
4210 @end smallexample
4212 @need 1250
4213 @noindent
4214 On the other hand, this function returns @code{nil} if the test is false.
4216 @smallexample
4217 (> 4 5)
4218 @end smallexample
4220 @node save-excursion, Review, Truth & Falsehood, Writing Defuns
4221 @comment  node-name,  next,  previous,  up
4222 @section @code{save-excursion}
4223 @findex save-excursion
4224 @cindex Region, what it is
4225 @cindex Preserving point, mark, and buffer
4226 @cindex Point, mark, buffer preservation
4227 @findex point
4228 @findex mark
4230 The @code{save-excursion} function is the fourth and final special form
4231 that we will discuss in this chapter.
4233 In Emacs Lisp programs used for editing, the @code{save-excursion}
4234 function is very common.  It saves the location of point and mark,
4235 executes the body of the function, and then restores point and mark to
4236 their previous positions if their locations were changed.  Its primary
4237 purpose is to keep the user from being surprised and disturbed by
4238 unexpected movement of point or mark.
4240 @menu
4241 * Point and mark::              A review of various locations.
4242 * Template for save-excursion::
4243 @end menu
4245 @node Point and mark, Template for save-excursion, save-excursion, save-excursion
4246 @ifnottex
4247 @unnumberedsubsec Point and Mark
4248 @end ifnottex
4250 Before discussing @code{save-excursion}, however, it may be useful
4251 first to review what point and mark are in GNU Emacs.  @dfn{Point} is
4252 the current location of the cursor.  Wherever the cursor
4253 is, that is point.  More precisely, on terminals where the cursor
4254 appears to be on top of a character, point is immediately before the
4255 character.  In Emacs Lisp, point is an integer.  The first character in
4256 a buffer is number one, the second is number two, and so on.  The
4257 function @code{point} returns the current position of the cursor as a
4258 number.  Each buffer has its own value for point.
4260 The @dfn{mark} is another position in the buffer; its value can be set
4261 with a command such as @kbd{C-@key{SPC}} (@code{set-mark-command}).  If
4262 a mark has been set, you can use the command @kbd{C-x C-x}
4263 (@code{exchange-point-and-mark}) to cause the cursor to jump to the mark
4264 and set the mark to be the previous position of point.  In addition, if
4265 you set another mark, the position of the previous mark is saved in the
4266 mark ring.  Many mark positions can be saved this way.  You can jump the
4267 cursor to a saved mark by typing @kbd{C-u C-@key{SPC}} one or more
4268 times.
4270 The part of the buffer between point and mark is called @dfn{the
4271 region}.  Numerous commands work on the region, including
4272 @code{center-region}, @code{count-lines-region}, @code{kill-region}, and
4273 @code{print-region}.
4275 The @code{save-excursion} special form saves the locations of point and
4276 mark and restores those positions after the code within the body of the
4277 special form is evaluated by the Lisp interpreter.  Thus, if point were
4278 in the beginning of a piece of text and some code moved point to the end
4279 of the buffer, the @code{save-excursion} would put point back to where
4280 it was before, after the expressions in the body of the function were
4281 evaluated.
4283 In Emacs, a function frequently moves point as part of its internal
4284 workings even though a user would not expect this.  For example,
4285 @code{count-lines-region} moves point.  To prevent the user from being
4286 bothered by jumps that are both unexpected and (from the user's point of
4287 view) unnecessary, @code{save-excursion} is often used to keep point and
4288 mark in the location expected by the user.  The use of
4289 @code{save-excursion} is good housekeeping.
4291 To make sure the house stays clean, @code{save-excursion} restores the
4292 values of point and mark even if something goes wrong in the code inside
4293 of it (or, to be more precise and to use the proper jargon, ``in case of
4294 abnormal exit'').  This feature is very helpful.
4296 In addition to recording the values of point and mark,
4297 @code{save-excursion} keeps track of the current buffer, and restores
4298 it, too.  This means you can write code that will change the buffer and
4299 have @code{save-excursion} switch you back to the original buffer.  This
4300 is how @code{save-excursion} is used in @code{append-to-buffer}.
4301 (@xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
4303 @node Template for save-excursion,  , Point and mark, save-excursion
4304 @comment  node-name,  next,  previous,  up
4305 @subsection Template for a @code{save-excursion} Expression
4307 @need 800
4308 The template for code using @code{save-excursion} is simple:
4310 @smallexample
4311 @group
4312 (save-excursion
4313   @var{body}@dots{})
4314 @end group
4315 @end smallexample
4317 @noindent
4318 The body of the function is one or more expressions that will be
4319 evaluated in sequence by the Lisp interpreter.  If there is more than
4320 one expression in the body, the value of the last one will be returned
4321 as the value of the @code{save-excursion} function.  The other
4322 expressions in the body are evaluated only for their side effects; and
4323 @code{save-excursion} itself is used only for its side effect (which
4324 is restoring the positions of point and mark).
4326 @need 1250
4327 In more detail, the template for a @code{save-excursion} expression
4328 looks like this:
4330 @smallexample
4331 @group
4332 (save-excursion
4333   @var{first-expression-in-body}
4334   @var{second-expression-in-body}
4335   @var{third-expression-in-body}
4336    @dots{}
4337   @var{last-expression-in-body})
4338 @end group
4339 @end smallexample
4341 @noindent
4342 An expression, of course, may be a symbol on its own or a list.
4344 In Emacs Lisp code, a @code{save-excursion} expression often occurs
4345 within the body of a @code{let} expression.  It looks like this:
4347 @smallexample
4348 @group
4349 (let @var{varlist}
4350   (save-excursion
4351     @var{body}@dots{}))
4352 @end group
4353 @end smallexample
4355 @node Review, defun Exercises, save-excursion, Writing Defuns
4356 @comment  node-name,  next,  previous,  up
4357 @section Review
4359 In the last few chapters we have introduced a fair number of functions
4360 and special forms.  Here they are described in brief, along with a few
4361 similar functions that have not been mentioned yet.
4363 @table @code
4364 @item eval-last-sexp
4365 Evaluate the last symbolic expression before the current location of
4366 point.  The value is printed in the echo area unless the function is
4367 invoked with an argument; in that case, the output is printed in the
4368 current buffer.  This command is normally bound to @kbd{C-x C-e}.
4370 @item defun
4371 Define function.  This special form has up to five parts: the name,
4372 a template for the arguments that will be passed to the function,
4373 documentation, an optional interactive declaration, and the body of the
4374 definition.
4376 @need 1250
4377 For example:
4379 @smallexample
4380 @group
4381 (defun back-to-indentation ()
4382   "Move point to first visible character on line."
4383   (interactive)
4384   (beginning-of-line 1)
4385   (skip-chars-forward " \t"))
4386 @end group
4387 @end smallexample
4389 @item interactive
4390 Declare to the interpreter that the function can be used
4391 interactively.  This special form may be followed by a string with one
4392 or more parts that pass the information to the arguments of the
4393 function, in sequence.  These parts may also tell the interpreter to
4394 prompt for information.  Parts of the string are separated by
4395 newlines, @samp{\n}.
4397 Common code characters are:
4399 @table @code
4400 @item b
4401 The name of an existing buffer.
4403 @item f
4404 The name of an existing file.
4406 @item p
4407 The numeric prefix argument.  (Note that this `p' is lower case.)
4409 @item r
4410 Point and the mark, as two numeric arguments, smallest first.  This
4411 is the only code letter that specifies two successive arguments
4412 rather than one.
4413 @end table
4415 @xref{Interactive Codes, , Code Characters for @samp{interactive},
4416 elisp, The GNU Emacs Lisp Reference Manual}, for a complete list of
4417 code characters.
4419 @item let
4420 Declare that a list of variables is for use within the body of the
4421 @code{let} and give them an initial value, either @code{nil} or a
4422 specified value; then evaluate the rest of the expressions in the body
4423 of the @code{let} and return the value of the last one.  Inside the
4424 body of the @code{let}, the Lisp interpreter does not see the values of
4425 the variables of the same names that are bound outside of the
4426 @code{let}.
4428 @need 1250
4429 For example,
4431 @smallexample
4432 @group
4433 (let ((foo (buffer-name))
4434       (bar (buffer-size)))
4435   (message
4436    "This buffer is %s and has %d characters."
4437    foo bar))
4438 @end group
4439 @end smallexample
4441 @item save-excursion
4442 Record the values of point and mark and the current buffer before
4443 evaluating the body of this special form.  Restore the values of point
4444 and mark and buffer afterward.
4446 @need 1250
4447 For example,
4449 @smallexample
4450 @group
4451 (message "We are %d characters into this buffer."
4452          (- (point)
4453             (save-excursion
4454               (goto-char (point-min)) (point))))
4455 @end group
4456 @end smallexample
4458 @item if
4459 Evaluate the first argument to the function; if it is true, evaluate
4460 the second argument; else evaluate the third argument, if there is one.
4462 The @code{if} special form is called a @dfn{conditional}.  There are
4463 other conditionals in Emacs Lisp, but @code{if} is perhaps the most
4464 commonly used.
4466 @need 1250
4467 For example,
4469 @smallexample
4470 @group
4471 (if (string-equal
4472      (number-to-string 21)
4473      (substring (emacs-version) 10 12))
4474     (message "This is version 21 Emacs")
4475   (message "This is not version 21 Emacs"))
4476 @end group
4477 @end smallexample
4479 @item equal
4480 @itemx eq
4481 Test whether two objects are the same.  @code{equal} uses one meaning
4482 of the word `same' and @code{eq} uses another:  @code{equal} returns
4483 true if the two objects have a similar structure and contents, such as
4484 two copies of the same book.  On the other hand, @code{eq}, returns
4485 true if both arguments are actually the same object.
4486 @findex equal
4487 @findex eq
4489 @need 1250
4490 @item <
4491 @itemx >
4492 @itemx <=
4493 @itemx >=
4494 The @code{<} function tests whether its first argument is smaller than
4495 its second argument.  A corresponding function, @code{>}, tests whether
4496 the first argument is greater than the second.  Likewise, @code{<=}
4497 tests whether the first argument is less than or equal to the second and
4498 @code{>=} tests whether the first argument is greater than or equal to
4499 the second.  In all cases, both arguments must be numbers or markers
4500 (markers indicate positions in buffers).
4502 @item string<
4503 @itemx string-lessp
4504 @itemx string=
4505 @itemx string-equal
4506 The @code{string-lessp} function tests whether its first argument is
4507 smaller than the second argument.  A shorter, alternative name for the
4508 same function (a @code{defalias}) is @code{string<}.
4510 The arguments to @code{string-lessp} must be strings or symbols; the
4511 ordering is lexicographic, so case is significant.  The print names of
4512 symbols are used instead of the symbols themselves.
4514 @cindex @samp{empty string} defined
4515 An empty string, @samp{""}, a string with no characters in it, is
4516 smaller than any string of characters.
4518 @code{string-equal} provides the corresponding test for equality.  Its
4519 shorter, alternative name is @code{string=}.  There are no string test
4520 functions that correspond to @var{>}, @code{>=}, or @code{<=}.
4522 @item message
4523 Print a message in the echo area. The first argument is a string that
4524 can contain @samp{%s}, @samp{%d}, or @samp{%c} to print the value of
4525 arguments that follow the string.  The argument used by @samp{%s} must
4526 be a string or a symbol; the argument used by @samp{%d} must be a
4527 number.  The argument used by @samp{%c} must be an ascii code number;
4528 it will be printed as the character with that @sc{ascii} code.
4530 @item setq
4531 @itemx set
4532 The @code{setq} function sets the value of its first argument to the
4533 value of the second argument.  The first argument is automatically
4534 quoted by @code{setq}.  It does the same for succeeding pairs of
4535 arguments.  Another function, @code{set}, takes only two arguments and
4536 evaluates both of them before setting the value returned by its first
4537 argument to the value returned by its second argument.
4539 @item buffer-name
4540 Without an argument, return the name of the buffer, as a string.
4542 @itemx buffer-file-name
4543 Without an argument, return the name of the file the buffer is
4544 visiting.
4546 @item current-buffer
4547 Return the buffer in which Emacs is active; it may not be
4548 the buffer that is visible on the screen.
4550 @item other-buffer
4551 Return the most recently selected buffer (other than the buffer passed
4552 to @code{other-buffer} as an argument and other than the current
4553 buffer).
4555 @item switch-to-buffer
4556 Select a buffer for Emacs to be active in and display it in the current
4557 window so users can look at it.  Usually bound to @kbd{C-x b}.
4559 @item set-buffer
4560 Switch Emacs' attention to a buffer on which programs will run.  Don't
4561 alter what the window is showing.
4563 @item buffer-size
4564 Return the number of characters in the current buffer.
4566 @item point
4567 Return the value of the current position of the cursor, as an
4568 integer counting the number of characters from the beginning of the
4569 buffer.
4571 @item point-min
4572 Return the minimum permissible value of point in
4573 the current buffer.  This is 1, unless narrowing is in effect.
4575 @item point-max
4576 Return the value of the maximum permissible value of point in the
4577 current buffer.  This is the end of the buffer, unless narrowing is in
4578 effect.
4579 @end table
4581 @need 1500
4582 @node defun Exercises,  , Review, Writing Defuns
4583 @section Exercises
4585 @itemize @bullet
4586 @item
4587 Write a non-interactive function that doubles the value of its
4588 argument, a number.  Make that function interactive.
4590 @item
4591 Write a function that tests whether the current value of
4592 @code{fill-column} is greater than the argument passed to the function,
4593 and if so, prints an appropriate message.
4594 @end itemize
4596 @node Buffer Walk Through, More Complex, Writing Defuns, Top
4597 @comment  node-name,  next,  previous,  up
4598 @chapter A Few Buffer--Related Functions
4600 In this chapter we study in detail several of the functions used in GNU
4601 Emacs.  This is called a ``walk-through''.  These functions are used as
4602 examples of Lisp code, but are not imaginary examples; with the
4603 exception of the first, simplified function definition, these functions
4604 show the actual code used in GNU Emacs.  You can learn a great deal from
4605 these definitions.  The functions described here are all related to
4606 buffers.  Later, we will study other functions.
4608 @menu
4609 * Finding More::                How to find more information.
4610 * simplified-beginning-of-buffer::  Shows @code{goto-char},
4611                                 @code{point-min}, and @code{push-mark}.
4612 * mark-whole-buffer::           Almost the same as @code{beginning-of-buffer}.
4613 * append-to-buffer::            Uses @code{save-excursion} and
4614                                 @code{insert-buffer-substring}.
4615 * Buffer Related Review::       Review.
4616 * Buffer Exercises::
4617 @end menu
4619 @node Finding More, simplified-beginning-of-buffer, Buffer Walk Through, Buffer Walk Through
4620 @section Finding More Information
4622 @findex describe-function, @r{introduced}
4623 @cindex Find function documentation
4624 In this walk-through, I will describe each new function as we come to
4625 it, sometimes in detail and sometimes briefly.  If you are interested,
4626 you can get the full documentation of any Emacs Lisp function at any
4627 time by typing @kbd{C-h f} and then the name of the function (and then
4628 @key{RET}).  Similarly, you can get the full documentation for a
4629 variable by typing @kbd{C-h v} and then the name of the variable (and
4630 then @key{RET}).
4632 @cindex Find source of function
4633 In versions 20 and higher, when a function is written in Emacs Lisp,
4634 @code{describe-function} will also tell you the location of the
4635 function definition.  If you move point over the file name and press
4636 the @key{RET} key, which is this case means @code{help-follow} rather
4637 than `return' or `enter', Emacs will take you directly to the function
4638 definition.
4640 More generally, if you want to see a function in its original source
4641 file, you can use the @code{find-tags} function to jump to it.
4642 @code{find-tags} works with a wide variety of languages, not just
4643 Lisp, and C, and it works with non-programming text as well.  For
4644 example, @code{find-tags} will jump to the various nodes in the
4645 Texinfo source file of this document.
4647 The @code{find-tags} function depends on `tags tables' that record
4648 the locations of the functions, variables, and other items to which
4649 @code{find-tags} jumps.
4651 To use the @code{find-tags} command, type @kbd{M-.}  (i.e., type the
4652 @key{META} key and the period key at the same time, or else type the
4653 @key{ESC} key and then type the period key), and then, at the prompt,
4654 type in the name of the function whose source code you want to see,
4655 such as @code{mark-whole-buffer}, and then type @key{RET}.  Emacs will
4656 switch buffers and display the source code for the function on your
4657 screen.  To switch back to your current buffer, type @kbd{C-x b
4658 @key{RET}}.  (On some keyboards, the @key{META} key is labelled
4659 @key{ALT}.)
4661 @c !!! 21.0.100 tags table location in this paragraph
4662 @cindex TAGS table, specifying
4663 @findex find-tags
4664 Depending on how the initial default values of your copy of Emacs are
4665 set, you may also need to specify the location of your `tags table',
4666 which is a file called @file{TAGS}.  For example, if you are
4667 interested in Emacs sources, the tags table you will most likely want,
4668 if it has already been created for you, will be in a subdirectory of
4669 the @file{/usr/local/share/emacs/} directory; thus you would use the
4670 @code{M-x visit-tags-table} command and specify a pathname such as
4671 @file{/usr/local/share/emacs/21.0.100/lisp/TAGS} or
4672 @file{/usr/local/src/emacs/lisp/TAGS}.  If the tags table has
4673 not already been created, you will have to create it yourself.
4675 @need 1250
4676 To create a @file{TAGS} file in a specific directory, switch to that
4677 directory in Emacs using @kbd{M-x cd} command, or list the directory
4678 with @kbd{C-x d} (@code{dired}).  Then run the compile command, with
4679 @w{@code{etags *.el}} as the command to execute
4681 @smallexample
4682 M-x compile RET etags *.el RET
4683 @end smallexample
4685 For more information, see @ref{etags, , Create Your Own @file{TAGS} File}.
4687 After you become more familiar with Emacs Lisp, you will find that you will
4688 frequently use @code{find-tags} to navigate your way around source code;
4689 and you will create your own @file{TAGS} tables.
4691 @cindex Library, as term for `file'
4692 Incidentally, the files that contain Lisp code are conventionally
4693 called @dfn{libraries}.  The metaphor is derived from that of a
4694 specialized library, such as a law library or an engineering library,
4695 rather than a general library.  Each library, or file, contains
4696 functions that relate to a particular topic or activity, such as
4697 @file{abbrev.el} for handling abbreviations and other typing
4698 shortcuts, and @file{help.el} for on-line help.  (Sometimes several
4699 libraries provide code for a single activity, as the various
4700 @file{rmail@dots{}} files provide code for reading electronic mail.)
4701 In @cite{The GNU Emacs Manual}, you will see sentences such as ``The
4702 @kbd{C-h p} command lets you search the standard Emacs Lisp libraries
4703 by topic keywords.''
4705 @node simplified-beginning-of-buffer, mark-whole-buffer, Finding More, Buffer Walk Through
4706 @comment  node-name,  next,  previous,  up
4707 @section A Simplified @code{beginning-of-buffer} Definition
4708 @findex simplified-beginning-of-buffer
4710 The @code{beginning-of-buffer} command is a good function to start with
4711 since you are likely to be familiar with it and it is easy to
4712 understand.  Used as an interactive command, @code{beginning-of-buffer}
4713 moves the cursor to the beginning of the buffer, leaving the mark at the
4714 previous position.  It is generally bound to @kbd{M-<}.
4716 In this section, we will discuss a shortened version of the function
4717 that shows how it is most frequently used.  This shortened function
4718 works as written, but it does not contain the code for a complex option.
4719 In another section, we will describe the entire function.
4720 (@xref{beginning-of-buffer, , Complete Definition of
4721 @code{beginning-of-buffer}}.)
4723 Before looking at the code, let's consider what the function
4724 definition has to contain: it must include an expression that makes
4725 the function interactive so it can be called by typing @kbd{M-x
4726 beginning-of-buffer} or by typing a keychord such as @kbd{M-<}; it
4727 must include code to leave a mark at the original position in the
4728 buffer; and it must include code to move the cursor to the beginning
4729 of the buffer.
4731 @need 1250
4732 Here is the complete text of the shortened version of the function:
4734 @smallexample
4735 @group
4736 (defun simplified-beginning-of-buffer ()
4737   "Move point to the beginning of the buffer;
4738 leave mark at previous position."
4739   (interactive)
4740   (push-mark)
4741   (goto-char (point-min)))
4742 @end group
4743 @end smallexample
4745 Like all function definitions, this definition has five parts following
4746 the special form @code{defun}:
4748 @enumerate
4749 @item
4750 The name: in this example, @code{simplified-beginning-of-buffer}.
4752 @item
4753 A list of the arguments: in this example, an empty list, @code{()},
4755 @item
4756 The documentation string.
4758 @item
4759 The interactive expression.
4761 @item
4762 The body.
4763 @end enumerate
4765 @noindent
4766 In this function definition, the argument list is empty; this means that
4767 this function does not require any arguments.  (When we look at the
4768 definition for the complete function, we will see that it may be passed
4769 an optional argument.)
4771 The interactive expression tells Emacs that the function is intended to
4772 be used interactively.  In this example, @code{interactive} does not have
4773 an argument because @code{simplified-beginning-of-buffer} does not
4774 require one.
4776 @need 800
4777 The body of the function consists of the two lines:
4779 @smallexample
4780 @group
4781 (push-mark)
4782 (goto-char (point-min))
4783 @end group
4784 @end smallexample
4786 The first of these lines is the expression, @code{(push-mark)}.  When
4787 this expression is evaluated by the Lisp interpreter, it sets a mark at
4788 the current position of the cursor, wherever that may be.  The position
4789 of this mark is saved in the mark ring.
4791 The next line is @code{(goto-char (point-min))}.  This expression
4792 jumps the cursor to the minimum point in the buffer, that is, to the
4793 beginning of the buffer (or to the beginning of the accessible portion
4794 of the buffer if it is narrowed.  @xref{Narrowing & Widening, ,
4795 Narrowing and Widening}.)
4797 The @code{push-mark} command sets a mark at the place where the cursor
4798 was located before it was moved to the beginning of the buffer by the
4799 @code{(goto-char (point-min))} expression.  Consequently, you can, if
4800 you wish, go back to where you were originally by typing @kbd{C-x C-x}.
4802 That is all there is to the function definition!
4804 @findex describe-function
4805 When you are reading code such as this and come upon an unfamiliar
4806 function, such as @code{goto-char}, you can find out what it does by
4807 using the @code{describe-function} command.  To use this command, type
4808 @kbd{C-h f} and then type in the name of the function and press
4809 @key{RET}.  The @code{describe-function} command will print the
4810 function's documentation string in a @file{*Help*} window.  For
4811 example, the documentation for @code{goto-char} is:
4813 @smallexample
4814 @group
4815 One arg, a number.  Set point to that number.
4816 Beginning of buffer is position (point-min),
4817 end is (point-max).
4818 @end group
4819 @end smallexample
4821 @noindent
4822 (The prompt for @code{describe-function} will offer you the symbol
4823 under or preceding the cursor, so you can save typing by positioning
4824 the cursor right over or after the function and then typing @kbd{C-h f
4825 @key{RET}}.)
4827 The @code{end-of-buffer} function definition is written in the same way as
4828 the @code{beginning-of-buffer} definition except that the body of the
4829 function contains the expression @code{(goto-char (point-max))} in place
4830 of @code{(goto-char (point-min))}.
4832 @node mark-whole-buffer, append-to-buffer, simplified-beginning-of-buffer, Buffer Walk Through
4833 @comment  node-name,  next,  previous,  up
4834 @section The Definition of @code{mark-whole-buffer}
4835 @findex mark-whole-buffer
4837 The @code{mark-whole-buffer} function is no harder to understand than the
4838 @code{simplified-beginning-of-buffer} function.  In this case, however,
4839 we will look at the complete function, not a shortened version.
4841 The @code{mark-whole-buffer} function is not as commonly used as the
4842 @code{beginning-of-buffer} function, but is useful nonetheless: it
4843 marks a whole buffer as a region by putting point at the beginning and
4844 a mark at the end of the buffer.  It is generally bound to @kbd{C-x
4848 @menu
4849 * mark-whole-buffer overview::
4850 * Body of mark-whole-buffer::   Only three lines of code.
4851 @end menu
4854 @node mark-whole-buffer overview, Body of mark-whole-buffer, mark-whole-buffer, mark-whole-buffer
4855 @ifnottex
4856 @unnumberedsubsec An overview of @code{mark-whole-buffer}
4857 @end ifnottex
4859 @need 1250
4860 In GNU Emacs 20, the code for the complete function looks like this:
4862 @smallexample
4863 @group
4864 (defun mark-whole-buffer ()
4865   "Put point at beginning and mark at end of buffer."
4866   (interactive)
4867   (push-mark (point))
4868   (push-mark (point-max))
4869   (goto-char (point-min)))
4870 @end group
4871 @end smallexample
4873 @need 1250
4874 Like all other functions, the @code{mark-whole-buffer} function fits
4875 into the template for a function definition.  The template looks like
4876 this:
4878 @smallexample
4879 @group
4880 (defun @var{name-of-function} (@var{argument-list})
4881   "@var{documentation}@dots{}"
4882   (@var{interactive-expression}@dots{})
4883   @var{body}@dots{})
4884 @end group
4885 @end smallexample
4887 Here is how the function works: the name of the function is
4888 @code{mark-whole-buffer}; it is followed by an empty argument list,
4889 @samp{()}, which means that the function does not require arguments.
4890 The documentation comes next.
4892 The next line is an @code{(interactive)} expression that tells Emacs
4893 that the function will be used interactively.  These details are similar
4894 to the @code{simplified-beginning-of-buffer} function described in the
4895 previous section.
4897 @node Body of mark-whole-buffer,  , mark-whole-buffer overview, mark-whole-buffer
4898 @comment  node-name,  next,  previous,  up
4899 @subsection Body of @code{mark-whole-buffer}
4901 The body of the @code{mark-whole-buffer} function consists of three
4902 lines of code:
4904 @smallexample
4905 @group
4906 (push-mark (point))
4907 (push-mark (point-max))
4908 (goto-char (point-min))
4909 @end group
4910 @end smallexample
4912 The first of these lines is the expression, @code{(push-mark (point))}.
4914 This line does exactly the same job as the first line of the body of
4915 the @code{simplified-beginning-of-buffer} function, which is written
4916 @code{(push-mark)}.  In both cases, the Lisp interpreter sets a mark
4917 at the current position of the cursor.
4919 I don't know why the expression in @code{mark-whole-buffer} is written
4920 @code{(push-mark (point))} and the expression in
4921 @code{beginning-of-buffer} is written @code{(push-mark)}.  Perhaps
4922 whoever wrote the code did not know that the arguments for
4923 @code{push-mark} are optional and that if @code{push-mark} is not
4924 passed an argument, the function automatically sets mark at the
4925 location of point by default.  Or perhaps the expression was written
4926 so as to parallel the structure of the next line.  In any case, the
4927 line causes Emacs to determine the position of point and set a mark
4928 there.
4930 The next line of @code{mark-whole-buffer} is @code{(push-mark (point-max)}.
4931 This expression sets a mark at the point in the buffer
4932 that has the highest number.  This will be the end of the buffer (or,
4933 if the buffer is narrowed, the end of the accessible portion of the
4934 buffer.  @xref{Narrowing & Widening, , Narrowing and Widening}, for
4935 more about narrowing.)  After this mark has been set, the previous
4936 mark, the one set at point, is no longer set, but Emacs remembers its
4937 position, just as all other recent marks are always remembered.  This
4938 means that you can, if you wish, go back to that position by typing
4939 @kbd{C-u C-@key{SPC}} twice.
4941 (In GNU Emacs 21, the @code{(push-mark (point-max)} is slightly more
4942 complicated than shown here.  The line reads
4944 @smallexample
4945 (push-mark (point-max) nil t)
4946 @end smallexample
4948 @noindent
4949 (The expression works nearly the same as before.  It sets a mark at
4950 the highest numbered place in the buffer that it can.  However, in
4951 this version, @code{push-mark} has two additional arguments.  The
4952 second argument to @code{push-mark} is @code{nil}.  This tells the
4953 function it @emph{should} display a message that says `Mark set' when
4954 it pushes the mark.  The third argument is @code{t}.  This tells
4955 @code{push-mark} to activate the mark when Transient Mark mode is
4956 turned on.  Transient Mark mode highlights the currently active
4957 region.  It is usually turned off.)
4959 Finally, the last line of the function is @code{(goto-char
4960 (point-min)))}.  This is written exactly the same way as it is written
4961 in @code{beginning-of-buffer}.  The expression moves the cursor to
4962 the minimum point in the buffer, that is, to the beginning of the buffer
4963 (or to the beginning of the accessible portion of the buffer).  As a
4964 result of this, point is placed at the beginning of the buffer and mark
4965 is set at the end of the buffer.  The whole buffer is, therefore, the
4966 region.
4968 @node append-to-buffer, Buffer Related Review, mark-whole-buffer, Buffer Walk Through
4969 @comment  node-name,  next,  previous,  up
4970 @section The Definition of @code{append-to-buffer}
4971 @findex append-to-buffer
4973 The @code{append-to-buffer} command is very nearly as simple as the
4974 @code{mark-whole-buffer} command.  What it does is copy the region (that
4975 is, the part of the buffer between point and mark) from the current
4976 buffer to a specified buffer.
4978 @menu
4979 * append-to-buffer overview::
4980 * append interactive::          A two part interactive expression.
4981 * append-to-buffer body::       Incorporates a @code{let} expression.
4982 * append save-excursion::       How the @code{save-excursion} works.
4983 @end menu
4985 @node append-to-buffer overview, append interactive, append-to-buffer, append-to-buffer
4986 @ifnottex
4987 @unnumberedsubsec An Overview of @code{append-to-buffer}
4988 @end ifnottex
4990 @findex insert-buffer-substring
4991 The @code{append-to-buffer} command uses the
4992 @code{insert-buffer-substring} function to copy the region.
4993 @code{insert-buffer-substring} is described by its name: it takes a
4994 string of characters from part of a buffer, a ``substring'', and
4995 inserts them into another buffer.  Most of @code{append-to-buffer} is
4996 concerned with setting up the conditions for
4997 @code{insert-buffer-substring} to work: the code must specify both the
4998 buffer to which the text will go and the region that will be copied.
4999 Here is the complete text of the function:
5001 @smallexample
5002 @group
5003 (defun append-to-buffer (buffer start end)
5004   "Append to specified buffer the text of the region.
5005 It is inserted into that buffer before its point.
5006 @end group
5008 @group
5009 When calling from a program, give three arguments:
5010 a buffer or the name of one, and two character numbers
5011 specifying the portion of the current buffer to be copied."
5012   (interactive "BAppend to buffer:@: \nr")
5013   (let ((oldbuf (current-buffer)))
5014     (save-excursion
5015       (set-buffer (get-buffer-create buffer))
5016       (insert-buffer-substring oldbuf start end))))
5017 @end group
5018 @end smallexample
5020 The function can be understood by looking at it as a series of
5021 filled-in templates.
5023 The outermost template is for the function definition.  In this
5024 function, it looks like this (with several slots filled in):
5026 @smallexample
5027 @group
5028 (defun append-to-buffer (buffer start end)
5029   "@var{documentation}@dots{}"
5030   (interactive "BAppend to buffer:@: \nr")
5031   @var{body}@dots{})
5032 @end group
5033 @end smallexample
5035 The first line of the function includes its name and three arguments.
5036 The arguments are the @code{buffer} to which the text will be copied, and
5037 the @code{start} and @code{end} of the region in the current buffer that
5038 will be copied.
5040 The next part of the function is the documentation, which is clear and
5041 complete.
5043 @node append interactive, append-to-buffer body, append-to-buffer overview, append-to-buffer
5044 @comment  node-name,  next,  previous,  up
5045 @subsection The @code{append-to-buffer} Interactive Expression
5047 Since the @code{append-to-buffer} function will be used interactively,
5048 the function must have an @code{interactive} expression.  (For a
5049 review of @code{interactive}, see @ref{Interactive, , Making a
5050 Function Interactive}.)  The expression reads as follows:
5052 @smallexample
5053 (interactive "BAppend to buffer:@: \nr")
5054 @end smallexample
5056 @noindent
5057 This expression has an argument inside of quotation marks and that
5058 argument has two parts, separated by @samp{\n}.
5060 The first part is @samp{BAppend to buffer:@: }.  Here, the @samp{B}
5061 tells Emacs to ask for the name of the buffer that will be passed to the
5062 function.  Emacs will ask for the name by prompting the user in the
5063 minibuffer, using the string following the @samp{B}, which is the string
5064 @samp{Append to buffer:@: }.  Emacs then binds the variable @code{buffer}
5065 in the function's argument list to the specified buffer.
5067 The newline, @samp{\n}, separates the first part of the argument from
5068 the second part.  It is followed by an @samp{r} that tells Emacs to bind
5069 the two arguments that follow the symbol @code{buffer} in the function's
5070 argument list (that is, @code{start} and @code{end}) to the values of
5071 point and mark.
5073 @node append-to-buffer body, append save-excursion, append interactive, append-to-buffer
5074 @comment  node-name,  next,  previous,  up
5075 @subsection The Body of @code{append-to-buffer}
5077 The body of the @code{append-to-buffer} function begins with @code{let}.
5079 As we have seen before (@pxref{let, , @code{let}}), the purpose of a
5080 @code{let} expression is to create and give initial values to one or
5081 more variables that will only be used within the body of the
5082 @code{let}.  This means that such a variable will not be confused with
5083 any variable of the same name outside the @code{let} expression.
5085 We can see how the @code{let} expression fits into the function as a
5086 whole by showing a template for @code{append-to-buffer} with the
5087 @code{let} expression in outline:
5089 @smallexample
5090 @group
5091 (defun append-to-buffer (buffer start end)
5092   "@var{documentation}@dots{}"
5093   (interactive "BAppend to buffer:@: \nr")
5094   (let ((@var{variable} @var{value}))
5095         @var{body}@dots{})
5096 @end group
5097 @end smallexample
5099 The @code{let} expression has three elements:
5101 @enumerate
5102 @item
5103 The symbol @code{let};
5105 @item
5106 A varlist containing, in this case, a single two-element list,
5107 @code{(@var{variable} @var{value})};
5109 @item
5110 The body of the @code{let} expression.
5111 @end enumerate
5113 @need 800
5114 In the @code{append-to-buffer} function, the varlist looks like this:
5116 @smallexample
5117 (oldbuf (current-buffer))
5118 @end smallexample
5120 @noindent
5121 In this part of the @code{let} expression, the one variable,
5122 @code{oldbuf}, is bound to the value returned by the
5123 @code{(current-buffer)} expression.  The variable, @code{oldbuf}, is
5124 used to keep track of the buffer in which you are working and from
5125 which you will copy.
5127 The element or elements of a varlist are surrounded by a set of
5128 parentheses so the Lisp interpreter can distinguish the varlist from
5129 the body of the @code{let}.  As a consequence, the two-element list
5130 within the varlist is surrounded by a circumscribing set of parentheses.
5131 The line looks like this:
5133 @smallexample
5134 @group
5135 (let ((oldbuf (current-buffer)))
5136   @dots{} )
5137 @end group
5138 @end smallexample
5140 @noindent
5141 The two parentheses before @code{oldbuf} might surprise you if you did
5142 not realize that the first parenthesis before @code{oldbuf} marks the
5143 boundary of the varlist and the second parenthesis marks the beginning
5144 of the two-element list, @code{(oldbuf (current-buffer))}.
5146 @node append save-excursion,  , append-to-buffer body, append-to-buffer
5147 @comment  node-name,  next,  previous,  up
5148 @subsection @code{save-excursion} in @code{append-to-buffer}
5150 The body of the @code{let} expression in @code{append-to-buffer}
5151 consists of a @code{save-excursion} expression.
5153 The @code{save-excursion} function saves the locations of point and
5154 mark, and restores them to those positions after the expressions in the
5155 body of the @code{save-excursion} complete execution.  In addition,
5156 @code{save-excursion} keeps track of the original buffer, and
5157 restores it.  This is how @code{save-excursion} is used in
5158 @code{append-to-buffer}.
5160 @need 1500
5161 @cindex Indentation for formatting
5162 @cindex Formatting convention
5163 Incidentally, it is worth noting here that a Lisp function is normally
5164 formatted so that everything that is enclosed in a multi-line spread is
5165 indented more to the right than the first symbol.  In this function
5166 definition, the @code{let} is indented more than the @code{defun}, and
5167 the @code{save-excursion} is indented more than the @code{let}, like
5168 this:
5170 @smallexample
5171 @group
5172 (defun @dots{}
5173   @dots{}
5174   @dots{}
5175   (let@dots{}
5176     (save-excursion
5177       @dots{}
5178 @end group
5179 @end smallexample
5181 @need 1500
5182 @noindent
5183 This formatting convention makes it easy to see that the two lines in
5184 the body of the @code{save-excursion} are enclosed by the parentheses
5185 associated with @code{save-excursion}, just as the
5186 @code{save-excursion} itself is enclosed by the parentheses associated
5187 with the @code{let}:
5189 @smallexample
5190 @group
5191 (let ((oldbuf (current-buffer)))
5192   (save-excursion
5193     (set-buffer (get-buffer-create buffer))
5194     (insert-buffer-substring oldbuf start end))))
5195 @end group
5196 @end smallexample
5198 @need 1200
5199 The use of the @code{save-excursion} function can be viewed as a process
5200 of filling in the slots of a template:
5202 @smallexample
5203 @group
5204 (save-excursion
5205   @var{first-expression-in-body}
5206   @var{second-expression-in-body}
5207    @dots{}
5208   @var{last-expression-in-body})
5209 @end group
5210 @end smallexample
5212 @need 1200
5213 @noindent
5214 In this function, the body of the @code{save-excursion} contains only
5215 two expressions.  The body looks like this:
5217 @smallexample
5218 @group
5219 (set-buffer (get-buffer-create buffer))
5220 (insert-buffer-substring oldbuf start end)
5221 @end group
5222 @end smallexample
5224 When the @code{append-to-buffer} function is evaluated, the two
5225 expressions in the body of the @code{save-excursion} are evaluated in
5226 sequence.  The value of the last expression is returned as the value of
5227 the @code{save-excursion} function; the other expression is evaluated
5228 only for its side effects.
5230 The first line in the body of the @code{save-excursion} uses the
5231 @code{set-buffer} function to change the current buffer to the one
5232 specified in the first argument to @code{append-to-buffer}.  (Changing
5233 the buffer is the side effect; as we have said before, in Lisp, a side
5234 effect is often the primary thing we want.)  The second line does the
5235 primary work of the function.
5237 The @code{set-buffer} function changes Emacs' attention to the buffer to
5238 which the text will be copied and from which @code{save-excursion} will
5239 return.
5241 @need 800
5242 The line looks like this:
5244 @smallexample
5245 (set-buffer (get-buffer-create buffer))
5246 @end smallexample
5248 The innermost expression of this list is @code{(get-buffer-create
5249 buffer)}.  This expression uses the @code{get-buffer-create} function,
5250 which either gets the named buffer, or if it does not exist, creates one
5251 with the given name.  This means you can use @code{append-to-buffer} to
5252 put text into a buffer that did not previously exist.
5254 @code{get-buffer-create} also keeps @code{set-buffer} from getting an
5255 unnecessary error: @code{set-buffer} needs a buffer to go to; if you
5256 were to specify a buffer that does not exist, Emacs would baulk.
5257 Since @code{get-buffer-create} will create a buffer if none exists,
5258 @code{set-buffer} is always provided with a buffer.
5260 @need 1250
5261 The last line of @code{append-to-buffer} does the work of appending
5262 the text:
5264 @smallexample
5265 (insert-buffer-substring oldbuf start end)
5266 @end smallexample
5268 @noindent
5269 The @code{insert-buffer-substring} function copies a string @emph{from}
5270 the buffer specified as its first argument and inserts the string into
5271 the present buffer.  In this case, the argument to
5272 @code{insert-buffer-substring} is the value of the variable created and
5273 bound by the @code{let}, namely the value of @code{oldbuf}, which was
5274 the current buffer when you gave the @code{append-to-buffer} command.
5276 After @code{insert-buffer-substring} has done its work,
5277 @code{save-excursion} will restore the action to the original buffer and
5278 @code{append-to-buffer} will have done its job.
5280 @need 800
5281 Written in skeletal form, the workings of the body look like this:
5283 @smallexample
5284 @group
5285 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5286   (save-excursion                       ; @r{Keep track of buffer.}
5287     @var{change-buffer}
5288     @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})
5290   @var{change-back-to-original-buffer-when-finished}
5291 @var{let-the-local-meaning-of-}@code{oldbuf}@var{-disappear-when-finished}
5293 @end group
5294 @end smallexample
5296 In summary, @code{append-to-buffer} works as follows: it saves the value
5297 of the current buffer in the variable called @code{oldbuf}.  It gets the
5298 new buffer, creating one if need be, and switches Emacs to it.  Using
5299 the value of @code{oldbuf}, it inserts the region of text from the old
5300 buffer into the new buffer; and then using @code{save-excursion}, it
5301 brings you back to your original buffer.
5303 In looking at @code{append-to-buffer}, you have explored a fairly
5304 complex function.  It shows how to use @code{let} and
5305 @code{save-excursion}, and how to change to and come back from another
5306 buffer.  Many function definitions use @code{let},
5307 @code{save-excursion}, and @code{set-buffer} this way.
5309 @node Buffer Related Review, Buffer Exercises, append-to-buffer, Buffer Walk Through
5310 @comment  node-name,  next,  previous,  up
5311 @section Review
5313 Here is a brief summary of the various functions discussed in this chapter.
5315 @table @code
5316 @item describe-function
5317 @itemx describe-variable
5318 Print the documentation for a function or variable.
5319 Conventionally bound to @kbd{C-h f} and @kbd{C-h v}.
5321 @item find-tag
5322 Find the file containing the source for a function or variable and
5323 switch buffers to it, positioning point at the beginning of the item.
5324 Conventionally bound to @kbd{M-.} (that's a period following the
5325 @key{META} key).
5327 @item save-excursion
5328 Save the location of point and mark and restore their values after the
5329 arguments to @code{save-excursion} have been evaluated.  Also, remember
5330 the current buffer and return to it.
5332 @item push-mark
5333 Set mark at a location and record the value of the previous mark on the
5334 mark ring.  The mark is a location in the buffer that will keep its
5335 relative position even if text is added to or removed from the buffer.
5337 @item goto-char
5338 Set point to the location specified by the value of the argument, which
5339 can be a number, a marker,  or an expression that returns the number of
5340 a position, such as @code{(point-min)}.
5342 @item insert-buffer-substring
5343 Copy a region of text from a buffer that is passed to the function as
5344 an argument and insert the region into the current buffer.
5346 @item mark-whole-buffer
5347 Mark the whole buffer as a region.  Normally bound to @kbd{C-x h}.
5349 @item set-buffer
5350 Switch the attention of Emacs to another buffer, but do not change the
5351 window being displayed.  Used when the program rather than a human is
5352 to work on a different buffer.
5354 @item get-buffer-create
5355 @itemx get-buffer
5356 Find a named buffer or create one if a buffer of that name does not
5357 exist.  The @code{get-buffer} function returns @code{nil} if the named
5358 buffer does not exist.
5359 @end table
5361 @need 1500
5362 @node Buffer Exercises,  , Buffer Related Review, Buffer Walk Through
5363 @section Exercises
5365 @itemize @bullet
5366 @item
5367 Write your own @code{simplified-end-of-buffer} function definition;
5368 then test it to see whether it works.
5370 @item
5371 Use @code{if} and @code{get-buffer} to write a function that prints a
5372 message telling you whether a buffer exists.
5374 @item
5375 Using @code{find-tag}, find the source for the @code{copy-to-buffer}
5376 function.
5377 @end itemize
5379 @node More Complex, Narrowing & Widening, Buffer Walk Through, Top
5380 @comment  node-name,  next,  previous,  up
5381 @chapter A Few More Complex Functions
5383 In this chapter, we build on what we have learned in previous chapters
5384 by looking at more complex functions.  The @code{copy-to-buffer}
5385 function illustrates use of two @code{save-excursion} expressions in
5386 one definition, while the @code{insert-buffer} function illustrates
5387 use of an asterisk in an @code{interactive} expression, use of
5388 @code{or}, and the important distinction between a name and the object
5389 to which the name refers.
5391 @menu
5392 * copy-to-buffer::              With @code{set-buffer}, @code{get-buffer-create}.
5393 * insert-buffer::               Read-only, and with @code{or}.
5394 * beginning-of-buffer::         Shows @code{goto-char},
5395                                 @code{point-min}, and @code{push-mark}.
5396 * Second Buffer Related Review::
5397 * optional Exercise::
5398 @end menu
5400 @node copy-to-buffer, insert-buffer, More Complex, More Complex
5401 @comment  node-name,  next,  previous,  up
5402 @section The Definition of @code{copy-to-buffer}
5403 @findex copy-to-buffer
5405 After understanding how @code{append-to-buffer} works, it is easy to
5406 understand @code{copy-to-buffer}.  This function copies text into a
5407 buffer, but instead of adding to the second buffer, it replaces the
5408 previous text in the second buffer.  The code for the
5409 @code{copy-to-buffer} function is almost the same as the code for
5410 @code{append-to-buffer}, except that @code{erase-buffer} and a second
5411 @code{save-excursion} are used.  (@xref{append-to-buffer, , The
5412 Definition of @code{append-to-buffer}}, for the description of
5413 @code{append-to-buffer}.)
5415 @need 800
5416 The body of @code{copy-to-buffer} looks like this
5418 @smallexample
5419 @group
5420 @dots{}
5421 (interactive "BCopy to buffer:@: \nr")
5422   (let ((oldbuf (current-buffer)))
5423     (save-excursion
5424       (set-buffer (get-buffer-create buffer))
5425       (erase-buffer)
5426       (save-excursion
5427         (insert-buffer-substring oldbuf start end)))))
5428 @end group
5429 @end smallexample
5431 This code is similar to the code in @code{append-to-buffer}: it is
5432 only after changing to the buffer to which the text will be copied
5433 that the definition for this function diverges from the definition for
5434 @code{append-to-buffer}: the @code{copy-to-buffer} function erases the
5435 buffer's former contents.  (This is what is meant by `replacement'; to
5436 replace text, Emacs erases the previous text and then inserts new
5437 text.)  After erasing the previous contents of the buffer,
5438 @code{save-excursion} is used for a second time and the new text is
5439 inserted.
5441 Why is @code{save-excursion} used twice?  Consider again what the
5442 function does.
5444 @need 1250
5445 In outline, the body of @code{copy-to-buffer} looks like this:
5447 @smallexample
5448 @group
5449 (let (@var{bind-}@code{oldbuf}@var{-to-value-of-}@code{current-buffer})
5450   (save-excursion         ; @r{First use of @code{save-excursion}.}
5451     @var{change-buffer}
5452       (erase-buffer)
5453       (save-excursion     ; @r{Second use of @code{save-excursion}.}
5454         @var{insert-substring-from-}@code{oldbuf}@var{-into-buffer})))
5455 @end group
5456 @end smallexample
5458 The first use of @code{save-excursion} returns Emacs to the buffer from
5459 which the text is being copied.  That is clear, and is just like its use
5460 in @code{append-to-buffer}.  Why the second use?  The reason is that
5461 @code{insert-buffer-substring} always leaves point at the @emph{end} of
5462 the region being inserted.  The second @code{save-excursion} causes
5463 Emacs to leave point at the beginning of the text being inserted.  In
5464 most circumstances, users prefer to find point at the beginning of
5465 inserted text.  (Of course, the @code{copy-to-buffer} function returns
5466 the user to the original buffer when done---but if the user @emph{then}
5467 switches to the copied-to buffer, point will go to the beginning of the
5468 text.  Thus, this use of a second @code{save-excursion} is a little
5469 nicety.)
5471 @node insert-buffer, beginning-of-buffer, copy-to-buffer, More Complex
5472 @comment  node-name,  next,  previous,  up
5473 @section The Definition of @code{insert-buffer}
5474 @findex insert-buffer
5476 @code{insert-buffer} is yet another buffer-related function.  This
5477 command copies another buffer @emph{into} the current buffer.  It is the
5478 reverse of @code{append-to-buffer} or @code{copy-to-buffer}, since they
5479 copy a region of text @emph{from} the current buffer to another buffer.
5481 In addition, this code illustrates the use of @code{interactive} with a
5482 buffer that might be @dfn{read-only} and the important distinction
5483 between the name of an object and the object actually referred to.
5485 @menu
5486 * insert-buffer code::
5487 * insert-buffer interactive::   When you can read, but not write.
5488 * insert-buffer body::          The body has an @code{or} and a @code{let}.
5489 * if & or::                     Using an @code{if} instead of an @code{or}.
5490 * Insert or::                   How the @code{or} expression works.
5491 * Insert let::                  Two @code{save-excursion} expressions.
5492 @end menu
5494 @node insert-buffer code, insert-buffer interactive, insert-buffer, insert-buffer
5495 @ifnottex
5496 @unnumberedsubsec The Code for @code{insert-buffer}
5497 @end ifnottex
5499 @need 800
5500 Here is the code:
5502 @smallexample
5503 @group
5504 (defun insert-buffer (buffer)
5505   "Insert after point the contents of BUFFER.
5506 Puts mark after the inserted text.
5507 BUFFER may be a buffer or a buffer name."
5508   (interactive "*bInsert buffer:@: ")
5509 @end group
5510 @group
5511   (or (bufferp buffer)
5512       (setq buffer (get-buffer buffer)))
5513   (let (start end newmark)
5514     (save-excursion
5515       (save-excursion
5516         (set-buffer buffer)
5517         (setq start (point-min) end (point-max)))
5518 @end group
5519 @group
5520       (insert-buffer-substring buffer start end)
5521       (setq newmark (point)))
5522     (push-mark newmark)))
5523 @end group
5524 @end smallexample
5526 @need 1200
5527 As with other function definitions, you can use a template to see an
5528 outline of the function:
5530 @smallexample
5531 @group
5532 (defun insert-buffer (buffer)
5533   "@var{documentation}@dots{}"
5534   (interactive "*bInsert buffer:@: ")
5535   @var{body}@dots{})
5536 @end group
5537 @end smallexample
5539 @node insert-buffer interactive, insert-buffer body, insert-buffer code, insert-buffer
5540 @comment  node-name,  next,  previous,  up
5541 @subsection The Interactive Expression in @code{insert-buffer}
5542 @findex interactive, @r{example use of}
5544 In @code{insert-buffer}, the argument to the @code{interactive}
5545 declaration has two parts, an asterisk, @samp{*}, and @samp{bInsert
5546 buffer:@: }.
5548 @menu
5549 * Read-only buffer::            When a buffer cannot be modified.
5550 * b for interactive::           An existing buffer or else its name.
5551 @end menu
5553 @node Read-only buffer, b for interactive, insert-buffer interactive, insert-buffer interactive
5554 @comment  node-name,  next,  previous,  up
5555 @unnumberedsubsubsec A Read-only Buffer
5556 @cindex Read-only buffer
5557 @cindex Asterisk for read-only buffer
5558 @findex * @r{for read-only buffer}
5560 The asterisk is for the situation when the current buffer is a
5561 read-only buffer---a buffer that cannot be modified.  If
5562 @code{insert-buffer} is called when the current buffer is read-only, a
5563 message to this effect is printed in the echo area and the terminal
5564 may beep or blink at you; you will not be permitted to insert anything
5565 into current buffer.  The asterisk does not need to be followed by a
5566 newline to separate it from the next argument.
5568 @node b for interactive,  , Read-only buffer, insert-buffer interactive
5569 @comment  node-name,  next,  previous,  up
5570 @unnumberedsubsubsec @samp{b} in an Interactive Expression
5572 The next argument in the interactive expression starts with a lower
5573 case @samp{b}.  (This is different from the code for
5574 @code{append-to-buffer}, which uses an upper-case @samp{B}.
5575 @xref{append-to-buffer, , The Definition of @code{append-to-buffer}}.)
5576 The lower-case @samp{b} tells the Lisp interpreter that the argument
5577 for @code{insert-buffer} should be an existing buffer or else its
5578 name.  (The upper-case @samp{B} option provides for the possibility
5579 that the buffer does not exist.)  Emacs will prompt you for the name
5580 of the buffer, offering you a default buffer, with name completion
5581 enabled.  If the buffer does not exist, you receive a message that
5582 says ``No match''; your terminal may beep at you as well.
5584 @node insert-buffer body, if & or, insert-buffer interactive, insert-buffer
5585 @comment  node-name,  next,  previous,  up
5586 @subsection The Body of the @code{insert-buffer} Function
5588 The body of the @code{insert-buffer} function has two major parts: an
5589 @code{or} expression and a @code{let} expression.  The purpose of the
5590 @code{or} expression is to ensure that the argument @code{buffer} is
5591 bound to a buffer and not just the name of a buffer.  The body of the
5592 @code{let} expression contains the code which copies the other buffer
5593 into the current buffer.
5595 @need 1250
5596 In outline, the two expressions fit into the @code{insert-buffer}
5597 function like this:
5599 @smallexample
5600 @group
5601 (defun insert-buffer (buffer)
5602   "@var{documentation}@dots{}"
5603   (interactive "*bInsert buffer:@: ")
5604   (or @dots{}
5605       @dots{}
5606 @end group
5607 @group
5608   (let (@var{varlist})
5609       @var{body-of-}@code{let}@dots{} )
5610 @end group
5611 @end smallexample
5613 To understand how the @code{or} expression ensures that the argument
5614 @code{buffer} is bound to a buffer and not to the name of a buffer, it
5615 is first necessary to understand the @code{or} function.
5617 Before doing this, let me rewrite this part of the function using
5618 @code{if} so that you can see what is done in a manner that will be familiar.
5620 @node if & or, Insert or, insert-buffer body, insert-buffer
5621 @comment  node-name,  next,  previous,  up
5622 @subsection @code{insert-buffer} With an @code{if} Instead of an @code{or}
5624 The job to be done is to make sure the value of @code{buffer} is a
5625 buffer itself and not the name of a buffer.  If the value is the name,
5626 then the buffer itself must be got.
5628 You can imagine yourself at a conference where an usher is wandering
5629 around holding a list with your name on it and looking for you: the
5630 usher is ``bound'' to your name, not to you; but when the usher finds
5631 you and takes your arm, the usher becomes ``bound'' to you.
5633 @need 800
5634 In Lisp, you might describe this situation like this:
5636 @smallexample
5637 @group
5638 (if (not (holding-on-to-guest))
5639     (find-and-take-arm-of-guest))
5640 @end group
5641 @end smallexample
5643 We want to do the same thing with a buffer---if we do not have the
5644 buffer itself, we want to get it.
5646 @need 1200
5647 Using a predicate called @code{bufferp} that tells us whether we have a
5648 buffer (rather than its name), we can write the code like this:
5650 @smallexample
5651 @group
5652 (if (not (bufferp buffer))              ; @r{if-part}
5653     (setq buffer (get-buffer buffer)))  ; @r{then-part}
5654 @end group
5655 @end smallexample
5657 @noindent
5658 Here, the true-or-false-test of the @code{if} expression is
5659 @w{@code{(not (bufferp buffer))}}; and the then-part is the expression
5660 @w{@code{(setq buffer (get-buffer buffer))}}.
5662 In the test, the function @code{bufferp} returns true if its argument is
5663 a buffer---but false if its argument is the name of the buffer.  (The
5664 last character of the function name @code{bufferp} is the character
5665 @samp{p}; as we saw earlier, such use of @samp{p} is a convention that
5666 indicates that the function is a predicate, which is a term that means
5667 that the function will determine whether some property is true or false.
5668 @xref{Wrong Type of Argument, , Using the Wrong Type Object as an
5669 Argument}.)
5671 @need 1200
5672 The function @code{not} precedes the expression @code{(bufferp buffer)},
5673 so the true-or-false-test looks like this:
5675 @smallexample
5676 (not (bufferp buffer))
5677 @end smallexample
5679 @noindent
5680 @code{not} is a function that returns true if its argument is false
5681 and false if its argument is true.  So if @code{(bufferp buffer)}
5682 returns true, the @code{not} expression returns false and vice-versa:
5683 what is ``not true'' is false and what is ``not false'' is true.
5685 Using this test, the @code{if} expression works as follows: when the
5686 value of the variable @code{buffer} is actually a buffer rather then
5687 its name, the true-or-false-test returns false and the @code{if}
5688 expression does not evaluate the then-part.  This is fine, since we do
5689 not need to do anything to the variable @code{buffer} if it really is
5690 a buffer.
5692 On the other hand, when the value of @code{buffer} is not a buffer
5693 itself, but the name of a buffer, the true-or-false-test returns true
5694 and the then-part of the expression is evaluated.  In this case, the
5695 then-part is @code{(setq buffer (get-buffer buffer))}.  This
5696 expression uses the @code{get-buffer} function to return an actual
5697 buffer itself, given its name.  The @code{setq} then sets the variable
5698 @code{buffer} to the value of the buffer itself, replacing its previous
5699 value (which was the name of the buffer).
5701 @node Insert or, Insert let, if & or, insert-buffer
5702 @comment  node-name,  next,  previous,  up
5703 @subsection The @code{or} in the Body
5705 The purpose of the @code{or} expression in the @code{insert-buffer}
5706 function is to ensure that the argument @code{buffer} is bound to a
5707 buffer and not just to the name of a buffer.  The previous section shows
5708 how the job could have been done using an @code{if} expression.
5709 However, the @code{insert-buffer} function actually uses @code{or}.
5710 To understand this, it is necessary to understand how @code{or} works.
5712 @findex or
5713 An @code{or} function can have any number of arguments.  It evaluates
5714 each argument in turn and returns the value of the first of its
5715 arguments that is not @code{nil}.  Also, and this is a crucial feature
5716 of @code{or}, it does not evaluate any subsequent arguments after
5717 returning the first non-@code{nil} value.
5719 @need 800
5720 The @code{or} expression looks like this:
5722 @smallexample
5723 @group
5724 (or (bufferp buffer)
5725     (setq buffer (get-buffer buffer)))
5726 @end group
5727 @end smallexample
5729 @noindent
5730 The first argument to @code{or} is the expression @code{(bufferp buffer)}.
5731 This expression returns true (a non-@code{nil} value) if the buffer is
5732 actually a buffer, and not just the name of a buffer.  In the @code{or}
5733 expression, if this is the case, the @code{or} expression returns this
5734 true value and does not evaluate the next expression---and this is fine
5735 with us, since we do not want to do anything to the value of
5736 @code{buffer} if it really is a buffer.
5738 On the other hand, if the value of @code{(bufferp buffer)} is @code{nil},
5739 which it will be if the value of @code{buffer} is the name of a buffer,
5740 the Lisp interpreter evaluates the next element of the @code{or}
5741 expression.  This is the expression @code{(setq buffer (get-buffer
5742 buffer))}.  This expression returns a non-@code{nil} value, which
5743 is the value to which it sets the variable @code{buffer}---and this
5744 value is a buffer itself, not the name of a buffer.
5746 The result of all this is that the symbol @code{buffer} is always
5747 bound to a buffer itself rather than to the name of a buffer.  All
5748 this is necessary because the @code{set-buffer} function in a
5749 following line only works with a buffer itself, not with the name to a
5750 buffer.
5752 @need 1250
5753 Incidentally, using @code{or}, the situation with the usher would be
5754 written like this:
5756 @smallexample
5757 (or (holding-on-to-guest) (find-and-take-arm-of-guest))
5758 @end smallexample
5760 @node Insert let,  , Insert or, insert-buffer
5761 @comment  node-name,  next,  previous,  up
5762 @subsection The @code{let} Expression in @code{insert-buffer}
5764 After ensuring that the variable @code{buffer} refers to a buffer itself
5765 and not just to the name of a buffer, the @code{insert-buffer function}
5766 continues with a @code{let} expression.  This specifies three local
5767 variables, @code{start}, @code{end}, and @code{newmark} and binds them
5768 to the initial value @code{nil}.  These variables are used inside the
5769 remainder of the @code{let} and temporarily hide any other occurrence of
5770 variables of the same name in Emacs until the end of the @code{let}.
5772 @need 1200
5773 The body of the @code{let} contains two @code{save-excursion}
5774 expressions.  First, we will look at the inner @code{save-excursion}
5775 expression in detail.  The expression looks like this:
5777 @smallexample
5778 @group
5779 (save-excursion
5780   (set-buffer buffer)
5781   (setq start (point-min) end (point-max)))
5782 @end group
5783 @end smallexample
5785 @noindent
5786 The expression @code{(set-buffer buffer)} changes Emacs' attention
5787 from the current buffer to the one from which the text will copied.
5788 In that buffer, the variables @code{start} and @code{end} are set to
5789 the beginning and end of the buffer, using the commands
5790 @code{point-min} and @code{point-max}.  Note that we have here an
5791 illustration of how @code{setq} is able to set two variables in the
5792 same expression.  The first argument of @code{setq} is set to the
5793 value of its second, and its third argument is set to the value of its
5794 fourth.
5796 After the body of the inner @code{save-excursion} is evaluated, the
5797 @code{save-excursion} restores the original buffer, but @code{start} and
5798 @code{end} remain set to the values of the beginning and end of the
5799 buffer from which the text will be copied.
5801 @need 1250
5802 The outer @code{save-excursion} expression looks like this:
5804 @smallexample
5805 @group
5806 (save-excursion
5807   (@var{inner-}@code{save-excursion}@var{-expression}
5808      (@var{go-to-new-buffer-and-set-}@code{start}@var{-and-}@code{end})
5809   (insert-buffer-substring buffer start end)
5810   (setq newmark (point)))
5811 @end group
5812 @end smallexample
5814 @noindent
5815 The @code{insert-buffer-substring} function copies the text
5816 @emph{into} the current buffer @emph{from} the region indicated by
5817 @code{start} and @code{end} in @code{buffer}.  Since the whole of the
5818 second buffer lies between @code{start} and @code{end}, the whole of
5819 the second buffer is copied into the buffer you are editing.  Next,
5820 the value of point, which will be at the end of the inserted text, is
5821 recorded in the variable @code{newmark}.
5823 After the body of the outer @code{save-excursion} is evaluated, point
5824 and mark are relocated to their original places.
5826 However, it is convenient to locate a mark at the end of the newly
5827 inserted text and locate point at its beginning.  The @code{newmark}
5828 variable records the end of the inserted text.  In the last line of
5829 the @code{let} expression, the @code{(push-mark newmark)} expression
5830 function sets a mark to this location.  (The previous location of the
5831 mark is still accessible; it is recorded on the mark ring and you can
5832 go back to it with @kbd{C-u C-@key{SPC}}.)  Meanwhile, point is
5833 located at the beginning of the inserted text, which is where it was
5834 before you called the insert function.
5836 @need 1250
5837 The whole @code{let} expression looks like this:
5839 @smallexample
5840 @group
5841 (let (start end newmark)
5842   (save-excursion
5843     (save-excursion
5844       (set-buffer buffer)
5845       (setq start (point-min) end (point-max)))
5846     (insert-buffer-substring buffer start end)
5847     (setq newmark (point)))
5848   (push-mark newmark))
5849 @end group
5850 @end smallexample
5852 Like the @code{append-to-buffer} function, the @code{insert-buffer}
5853 function uses @code{let}, @code{save-excursion}, and
5854 @code{set-buffer}.  In addition, the function illustrates one way to
5855 use @code{or}.  All these functions are building blocks that we will
5856 find and use again and again.
5858 @node beginning-of-buffer, Second Buffer Related Review, insert-buffer, More Complex
5859 @comment  node-name,  next,  previous,  up
5860 @section Complete Definition of @code{beginning-of-buffer}
5861 @findex beginning-of-buffer
5863 The basic structure of the @code{beginning-of-buffer} function has
5864 already been discussed.  (@xref{simplified-beginning-of-buffer, , A
5865 Simplified @code{beginning-of-buffer} Definition}.)
5866 This section describes the complex part of the definition.
5868 As previously described, when invoked without an argument,
5869 @code{beginning-of-buffer} moves the cursor to the beginning of the
5870 buffer, leaving the mark at the previous position.  However, when the
5871 command is invoked with a number between one and ten, the function
5872 considers that number to be a fraction of the length of the buffer,
5873 measured in tenths, and Emacs moves the cursor that fraction of the way
5874 from the beginning of the buffer.  Thus, you can either call this
5875 function with the key command @kbd{M-<}, which will move the cursor to
5876 the beginning of the buffer, or with a key command such as @kbd{C-u 7
5877 M-<} which will move the cursor to a point 70% of the way through the
5878 buffer.  If a number bigger than ten is used for the argument, it moves
5879 to the end of the buffer.
5881 The @code{beginning-of-buffer} function can be called with or without an
5882 argument.  The use of the argument is optional.
5884 @menu
5885 * Optional Arguments::
5886 * beginning-of-buffer opt arg::  Example with optional argument.
5887 * beginning-of-buffer complete::
5888 @end menu
5890 @node Optional Arguments, beginning-of-buffer opt arg, beginning-of-buffer, beginning-of-buffer
5891 @subsection Optional Arguments
5893 Unless told otherwise, Lisp expects that a function with an argument in
5894 its function definition will be called with a value for that argument.
5895 If that does not happen, you get an error and a message that says
5896 @samp{Wrong number of arguments}.
5898 @cindex Optional arguments
5899 @cindex Keyword
5900 @findex optional
5901 However, optional arguments are a feature of Lisp: a @dfn{keyword} may
5902 be used to tell the Lisp interpreter that an argument is optional.
5903 The keyword is @code{&optional}.  (The @samp{&} in front of
5904 @samp{optional} is part of the keyword.)  In a function definition, if
5905 an argument follows the keyword @code{&optional}, a value does not
5906 need to be passed to that argument when the function is called.
5908 @need 1200
5909 The first line of the function definition of @code{beginning-of-buffer}
5910 therefore looks like this:
5912 @smallexample
5913 (defun beginning-of-buffer (&optional arg)
5914 @end smallexample
5916 @need 1250
5917 In outline, the whole function looks like this:
5919 @smallexample
5920 @group
5921 (defun beginning-of-buffer (&optional arg)
5922   "@var{documentation}@dots{}"
5923   (interactive "P")
5924   (push-mark)
5925   (goto-char
5926     (@var{if-there-is-an-argument}
5927         @var{figure-out-where-to-go}
5928       @var{else-go-to}
5929       (point-min))))
5930 @end group
5931 @end smallexample
5933 The function is similar to the @code{simplified-beginning-of-buffer}
5934 function except that the @code{interactive} expression has @code{"P"}
5935 as an argument and the @code{goto-char} function is followed by an
5936 if-then-else expression that figures out where to put the cursor if
5937 there is an argument.
5939 The @code{"P"} in the @code{interactive} expression tells Emacs to pass
5940 a prefix argument, if there is one, to the function.  A prefix argument
5941 is made by typing the @key{META} key followed by a number, or by typing
5942 @kbd{C-u} and then a number (if you don't type a number, @kbd{C-u}
5943 defaults to 4).
5945 The true-or-false-test of the @code{if} expression is simple: it is
5946 simply the argument @code{arg}.  If @code{arg} has a value that is not
5947 @code{nil}, which will be the case if @code{beginning-of-buffer} is
5948 called with an argument, then this true-or-false-test will return true
5949 and the then-part of the @code{if} expression will be evaluated.  On the
5950 other hand, if @code{beginning-of-buffer} is not called with an
5951 argument, the value of @code{arg} will be @code{nil} and the else-part
5952 of the @code{if} expression will be evaluated.  The else-part is simply
5953 @code{point-min}, and when this is the outcome, the whole
5954 @code{goto-char} expression is @code{(goto-char (point-min))}, which is
5955 how we saw the @code{beginning-of-buffer} function in its simplified
5956 form.
5958 @node beginning-of-buffer opt arg, beginning-of-buffer complete, Optional Arguments, beginning-of-buffer
5959 @subsection @code{beginning-of-buffer} with an Argument
5961 When @code{beginning-of-buffer} is called with an argument, an
5962 expression is evaluated which calculates what value to pass to
5963 @code{goto-char}.  This expression is rather complicated at first sight.
5964 It includes an inner @code{if} expression and much arithmetic.  It looks
5965 like this:
5967 @smallexample
5968 @group
5969 (if (> (buffer-size) 10000)
5970     ;; @r{Avoid overflow for large buffer sizes!}
5971     (* (prefix-numeric-value arg) (/ (buffer-size) 10))
5972   (/
5973    (+ 10
5974       (*
5975        (buffer-size) (prefix-numeric-value arg))) 10))
5976 @end group
5977 @end smallexample
5979 @menu
5980 * Disentangle beginning-of-buffer::
5981 * Large buffer case::
5982 * Small buffer case::
5983 @end menu
5985 @node Disentangle beginning-of-buffer, Large buffer case, beginning-of-buffer opt arg, beginning-of-buffer opt arg
5986 @ifnottex
5987 @unnumberedsubsubsec Disentangle @code{beginning-of-buffer}
5988 @end ifnottex
5990 Like other complex-looking expressions, the conditional expression
5991 within @code{beginning-of-buffer} can be disentangled by looking at it
5992 as parts of a template, in this case, the template for an if-then-else
5993 expression.  In skeletal form, the expression looks like this:
5995 @smallexample
5996 @group
5997 (if (@var{buffer-is-large}
5998     @var{divide-buffer-size-by-10-and-multiply-by-arg}
5999   @var{else-use-alternate-calculation}
6000 @end group
6001 @end smallexample
6003 The true-or-false-test of this inner @code{if} expression checks the
6004 size of the buffer.  The reason for this is that the old Version 18
6005 Emacs used numbers that are no bigger than eight million or so
6006 and in the computation that followed, the programmer feared that Emacs
6007 might try to use over-large numbers if the buffer were large.  The
6008 term `overflow', mentioned in the comment, means numbers that are over
6009 large.  Version 21 Emacs uses larger numbers, but this code has not
6010 been touched, if only because people now look at buffers that are far,
6011 far larger than ever before.
6013 There are two cases:  if the buffer is large and if it is not.
6015 @node Large buffer case, Small buffer case, Disentangle beginning-of-buffer, beginning-of-buffer opt arg
6016 @comment  node-name,  next,  previous,  up
6017 @unnumberedsubsubsec What happens in a large buffer
6019 In @code{beginning-of-buffer}, the inner @code{if} expression tests
6020 whether the size of the buffer is greater than 10,000 characters.  To do
6021 this, it uses the @code{>} function and the @code{buffer-size} function.
6023 @need 800
6024 The line looks like this:
6026 @smallexample
6027 (if (> (buffer-size) 10000)
6028 @end smallexample
6030 @need 1200
6031 @noindent
6032 When the buffer is large, the then-part of the @code{if} expression is
6033 evaluated.  It reads like this (after formatting for easy reading):
6035 @smallexample
6036 @group
6038   (prefix-numeric-value arg)
6039   (/ (buffer-size) 10))
6040 @end group
6041 @end smallexample
6043 @noindent
6044 This expression is a multiplication, with two arguments to the function
6045 @code{*}.
6047 The first argument is @code{(prefix-numeric-value arg)}.  When
6048 @code{"P"} is used as the argument for @code{interactive}, the value
6049 passed to the function as its argument is passed a ``raw prefix
6050 argument'', and not a number.  (It is a number in a list.)  To perform
6051 the arithmetic, a conversion is necessary, and
6052 @code{prefix-numeric-value} does the job.
6054 @findex / @r{(division)}
6055 @cindex Division
6056 The second argument is @code{(/ (buffer-size) 10)}.  This expression
6057 divides the numeric value of the buffer by ten.  This produces a number
6058 that tells how many characters make up one tenth of the buffer size.
6059 (In Lisp, @code{/} is used for division, just as @code{*} is
6060 used for multiplication.)
6062 @need 1200
6063 In the multiplication expression as a whole, this amount is multiplied
6064 by the value of the prefix argument---the multiplication looks like this:
6066 @smallexample
6067 @group
6068 (* @var{numeric-value-of-prefix-arg}
6069    @var{number-of-characters-in-one-tenth-of-the-buffer})
6070 @end group
6071 @end smallexample
6073 @noindent
6074 If, for example, the prefix argument is @samp{7}, the one-tenth value
6075 will be multiplied by 7 to give a position 70% of the way through the
6076 buffer.
6078 @need 1200
6079 The result of all this is that if the buffer is large, the
6080 @code{goto-char} expression reads like this:
6082 @smallexample
6083 @group
6084 (goto-char (* (prefix-numeric-value arg)
6085               (/ (buffer-size) 10)))
6086 @end group
6087 @end smallexample
6089 This puts the cursor where we want it.
6091 @node Small buffer case,  , Large buffer case, beginning-of-buffer opt arg
6092 @comment  node-name,  next,  previous,  up
6093 @unnumberedsubsubsec What happens in a small buffer
6095 If the buffer contains fewer than 10,000 characters, a slightly
6096 different computation is performed.  You might think this is not
6097 necessary, since the first computation could do the job.  However, in
6098 a small buffer, the first method may not put the cursor on exactly the
6099 desired line; the second method does a better job.
6101 @need 800
6102 The code looks like this:
6104 @c Keep this on one line.
6105 @smallexample
6106 (/ (+ 10 (* (buffer-size) (prefix-numeric-value arg))) 10))
6107 @end smallexample
6109 @need 1200
6110 @noindent
6111 This is code in which you figure out what happens by discovering how the
6112 functions are embedded in parentheses.  It is easier to read if you
6113 reformat it with each expression indented more deeply than its
6114 enclosing expression:
6116 @smallexample
6117 @group
6118   (/
6119    (+ 10
6120       (*
6121        (buffer-size)
6122        (prefix-numeric-value arg)))
6123    10))
6124 @end group
6125 @end smallexample
6127 @need 1200
6128 @noindent
6129 Looking at parentheses, we see that the innermost operation is
6130 @code{(prefix-numeric-value arg)}, which converts the raw argument to a
6131 number.  This number is multiplied by the buffer size in the following
6132 expression:
6134 @smallexample
6135 (* (buffer-size) (prefix-numeric-value arg)
6136 @end smallexample
6138 @noindent
6139 This multiplication creates a number that may be larger than the size of
6140 the buffer---seven times larger if the argument is 7, for example.  Ten
6141 is then added to this number and finally the large number is divided by
6142 ten to provide a value that is one character larger than the percentage
6143 position in the buffer.
6145 The number that results from all this is passed to @code{goto-char} and
6146 the cursor is moved to that point.
6148 @node beginning-of-buffer complete,  , beginning-of-buffer opt arg, beginning-of-buffer
6149 @comment  node-name,  next,  previous,  up
6150 @subsection The Complete @code{beginning-of-buffer}
6152 @need 800
6153 Here is the complete text of the @code{beginning-of-buffer} function:
6155 @smallexample
6156 @group
6157 (defun beginning-of-buffer (&optional arg)
6158   "Move point to the beginning of the buffer;
6159 leave mark at previous position.
6160 With arg N, put point N/10 of the way
6161 from the true beginning.
6162 Don't use this in Lisp programs!
6163 \(goto-char (point-min)) is faster
6164 and does not set the mark."
6165   (interactive "P")
6166   (push-mark)
6167 @end group
6168 @group
6169   (goto-char
6170    (if arg
6171        (if (> (buffer-size) 10000)
6172            ;; @r{Avoid overflow for large buffer sizes!}
6173            (* (prefix-numeric-value arg)
6174               (/ (buffer-size) 10))
6175 @end group
6176 @group
6177          (/ (+ 10 (* (buffer-size)
6178                      (prefix-numeric-value arg)))
6179             10))
6180      (point-min)))
6181   (if arg (forward-line 1)))
6182 @end group
6183 @end smallexample
6185 @noindent
6186 Except for two small points, the previous discussion shows how this
6187 function works.  The first point deals with a detail in the
6188 documentation string, and the second point concerns the last line of
6189 the function.
6191 @need 800
6192 In the documentation string, there is reference to an expression:
6194 @smallexample
6195 \(goto-char (point-min))
6196 @end smallexample
6198 @noindent
6199 A @samp{\} is used before the first parenthesis of this expression.
6200 This @samp{\} tells the Lisp interpreter that the expression should be
6201 printed as shown in the documentation rather than evaluated as a
6202 symbolic expression, which is what it looks like.
6204 @need 1200
6205 Finally, the last line of the @code{beginning-of-buffer} command says to
6206 move point to the beginning of the next line if the command is
6207 invoked with an argument:
6209 @smallexample
6210 (if arg (forward-line 1)))
6211 @end smallexample
6213 @noindent
6214 This puts the cursor at the beginning of the first line after the
6215 appropriate tenths position in the buffer.  This is a flourish that
6216 means that the cursor is always located @emph{at least} the requested
6217 tenths of the way through the buffer, which is a nicety that is,
6218 perhaps, not necessary, but which, if it did not occur, would be sure to
6219 draw complaints.
6221 @node Second Buffer Related Review, optional Exercise, beginning-of-buffer, More Complex
6222 @comment  node-name,  next,  previous,  up
6223 @section Review
6225 Here is a brief summary of some of the topics covered in this chapter.
6227 @table @code
6228 @item or
6229 Evaluate each argument in sequence, and return the value of the first
6230 argument that is not @code{nil}; if none return a value that is not
6231 @code{nil}, return @code{nil}.  In brief, return the first true value
6232 of the arguments; return a true value if one @emph{or} any of the
6233 other are true.
6235 @item and
6236 Evaluate each argument in sequence, and if any are @code{nil}, return
6237 @code{nil}; if none are @code{nil}, return the value of the last
6238 argument.  In brief, return a true value only if all the arguments are
6239 true; return a true value if one @emph{and} each of the others is
6240 true.
6242 @item &optional
6243 A keyword used to indicate that an argument to a function definition
6244 is optional; this means that the function can be evaluated without the
6245 argument, if desired.
6247 @item prefix-numeric-value
6248 Convert the `raw prefix argument' produced by @code{(interactive
6249 "P")} to a numeric value.
6251 @item forward-line
6252 Move point forward to the beginning of the next line, or if the argument
6253 is greater than one, forward that many lines.  If it can't move as far
6254 forward as it is supposed to, @code{forward-line} goes forward as far as
6255 it can and then returns a count of the number of additional lines it was
6256 supposed to move but couldn't.
6258 @item erase-buffer
6259 Delete the entire contents of the current buffer.
6261 @item bufferp
6262 Return @code{t} if its argument is a buffer; otherwise return @code{nil}.
6263 @end table
6265 @node optional Exercise,  , Second Buffer Related Review, More Complex
6266 @section @code{optional} Argument Exercise
6268 Write an interactive function with an optional argument that tests
6269 whether its argument, a number, is greater or less than the value of
6270 @code{fill-column}, and tells you which, in a message.  However, if you
6271 do not pass an argument to the function, use 56 as a default value.
6273 @node Narrowing & Widening, car cdr & cons, More Complex, Top
6274 @comment  node-name,  next,  previous,  up
6275 @chapter Narrowing and Widening
6276 @cindex Focusing attention (narrowing)
6277 @cindex Narrowing
6278 @cindex Widening
6280 Narrowing is a feature of Emacs that makes it possible for you to focus
6281 on a specific part of a buffer, and work without accidentally changing
6282 other parts.  Narrowing is normally disabled since it can confuse
6283 novices.
6285 @menu
6286 * Narrowing advantages::        The advantages of narrowing
6287 * save-restriction::            The @code{save-restriction} special form.
6288 * what-line::                   The number of the line that point is on.
6289 * narrow Exercise::
6290 @end menu
6292 @node Narrowing advantages, save-restriction, Narrowing & Widening, Narrowing & Widening
6293 @ifnottex
6294 @unnumberedsec The Advantages of Narrowing
6295 @end ifnottex
6297 With narrowing, the rest of a buffer is made invisible, as if it weren't
6298 there.  This is an advantage if, for example, you want to replace a word
6299 in one part of a buffer but not in another: you narrow to the part you want
6300 and the replacement is carried out only in that section, not in the rest
6301 of the buffer.  Searches will only work within a narrowed region, not
6302 outside of one, so if you are fixing a part of a document, you can keep
6303 yourself from accidentally finding parts you do not need to fix by
6304 narrowing just to the region you want.
6305 (The key binding for @code{narrow-to-region} is @kbd{C-x n n}.)
6307 However, narrowing does make the rest of the buffer invisible, which
6308 can scare people who inadvertently invoke narrowing and think they
6309 have deleted a part of their file.  Moreover, the @code{undo} command
6310 (which is usually bound to @kbd{C-x u}) does not turn off narrowing
6311 (nor should it), so people can become quite desperate if they do not
6312 know that they can return the rest of a buffer to visibility with the
6313 @code{widen} command.
6314 (The key binding for @code{widen} is @kbd{C-x n w}.)
6316 Narrowing is just as useful to the Lisp interpreter as to a human.
6317 Often, an Emacs Lisp function is designed to work on just part of a
6318 buffer; or conversely, an Emacs Lisp function needs to work on all of a
6319 buffer that has been narrowed.  The @code{what-line} function, for
6320 example, removes the narrowing from a buffer, if it has any narrowing
6321 and when it has finished its job, restores the narrowing to what it was.
6322 On the other hand, the @code{count-lines} function, which is called by
6323 @code{what-line}, uses narrowing to restrict itself to just that portion
6324 of the buffer in which it is interested and then restores the previous
6325 situation.
6327 @node save-restriction, what-line, Narrowing advantages, Narrowing & Widening
6328 @comment  node-name,  next,  previous,  up
6329 @section The @code{save-restriction} Special Form
6330 @findex save-restriction
6332 In Emacs Lisp, you can use the @code{save-restriction} special form to
6333 keep track of whatever narrowing is in effect, if any.  When the Lisp
6334 interpreter meets with @code{save-restriction}, it executes the code
6335 in the body of the @code{save-restriction} expression, and then undoes
6336 any changes to narrowing that the code caused.  If, for example, the
6337 buffer is narrowed and the code that follows @code{save-restriction}
6338 gets rid of the narrowing, @code{save-restriction} returns the buffer
6339 to its narrowed region afterwards.  In the @code{what-line} command,
6340 any narrowing the buffer may have is undone by the @code{widen}
6341 command that immediately follows the @code{save-restriction} command.
6342 Any original narrowing is restored just before the completion of the
6343 function.
6345 @need 1250
6346 The template for a @code{save-restriction} expression is simple:
6348 @smallexample
6349 @group
6350 (save-restriction
6351   @var{body}@dots{} )
6352 @end group
6353 @end smallexample
6355 @noindent
6356 The body of the @code{save-restriction} is one or more expressions that
6357 will be evaluated in sequence by the Lisp interpreter.
6359 Finally, a point to note: when you use both @code{save-excursion} and
6360 @code{save-restriction}, one right after the other, you should use
6361 @code{save-excursion} outermost.  If you write them in reverse order,
6362 you may fail to record narrowing in the buffer to which Emacs switches
6363 after calling @code{save-excursion}.  Thus, when written together,
6364 @code{save-excursion} and @code{save-restriction} should be written
6365 like this:
6367 @smallexample
6368 @group
6369 (save-excursion
6370   (save-restriction
6371     @var{body}@dots{}))
6372 @end group
6373 @end smallexample
6375 In other circumstances, when not written together, the
6376 @code{save-excursion} and @code{save-restriction} special forms must
6377 be written in the order appropriate to the function.
6379 @need 1250
6380 For example,
6382 @smallexample
6383 @group
6384   (save-restriction
6385     (widen)
6386     (save-excursion
6387     @var{body}@dots{}))
6388 @end group
6389 @end smallexample
6391 @node what-line, narrow Exercise, save-restriction, Narrowing & Widening
6392 @comment  node-name,  next,  previous,  up
6393 @section @code{what-line}
6394 @findex what-line
6395 @cindex Widening, example of
6397 The @code{what-line} command tells you the number of the line in which
6398 the cursor is located.  The function illustrates the use of the
6399 @code{save-restriction} and @code{save-excursion} commands.  Here is the
6400 text of the function in full:
6402 @smallexample
6403 @group
6404 (defun what-line ()
6405   "Print the current line number (in the buffer) of point."
6406   (interactive)
6407   (save-restriction
6408     (widen)
6409     (save-excursion
6410       (beginning-of-line)
6411       (message "Line %d"
6412                (1+ (count-lines 1 (point)))))))
6413 @end group
6414 @end smallexample
6416 The function has a documentation line and is interactive, as you would
6417 expect.  The next two lines use the functions @code{save-restriction} and
6418 @code{widen}.
6420 The @code{save-restriction} special form notes whatever narrowing is in
6421 effect, if any, in the current buffer and restores that narrowing after
6422 the code in the body of the @code{save-restriction} has been evaluated.
6424 The @code{save-restriction} special form is followed by @code{widen}.
6425 This function undoes any narrowing the current buffer may have had
6426 when @code{what-line} was called.  (The narrowing that was there is
6427 the narrowing that @code{save-restriction} remembers.)  This widening
6428 makes it possible for the line counting commands to count from the
6429 beginning of the buffer.  Otherwise, they would have been limited to
6430 counting within the accessible region.  Any original narrowing is
6431 restored just before the completion of the function by the
6432 @code{save-restriction} special form.
6434 The call to @code{widen} is followed by @code{save-excursion}, which
6435 saves the location of the cursor (i.e., of point) and of the mark, and
6436 restores them after the code in the body of the @code{save-excursion}
6437 uses the @code{beginning-of-line} function to move point.
6439 (Note that the @code{(widen)} expression comes between the
6440 @code{save-restriction} and @code{save-excursion} special forms.  When
6441 you write the two @code{save- @dots{}} expressions in sequence, write
6442 @code{save-excursion} outermost.)
6444 @need 1200
6445 The last two lines of the @code{what-line} function are functions to
6446 count the number of lines in the buffer and then print the number in the
6447 echo area.
6449 @smallexample
6450 @group
6451 (message "Line %d"
6452          (1+ (count-lines 1 (point)))))))
6453 @end group
6454 @end smallexample
6456 The @code{message} function prints a one-line message at the bottom of the
6457 Emacs screen.  The first argument is inside of quotation marks and is
6458 printed as a string of characters.  However, it may contain @samp{%d},
6459 @samp{%s}, or @samp{%c} to print arguments that follow the string.
6460 @samp{%d} prints the argument as a decimal, so the message will say
6461 something such as @samp{Line 243}.
6463 @need 1200
6464 The number that is printed in place of the @samp{%d} is computed by the
6465 last line of the function:
6467 @smallexample
6468 (1+ (count-lines 1 (point)))
6469 @end smallexample
6471 @noindent
6472 What this does is count the lines from the first position of the
6473 buffer, indicated by the @code{1}, up to @code{(point)}, and then add
6474 one to that number.  (The @code{1+} function adds one to its
6475 argument.)  We add one to it because line 2 has only one line before
6476 it, and @code{count-lines} counts only the lines @emph{before} the
6477 current line.
6479 After @code{count-lines} has done its job, and the message has been
6480 printed in the echo area, the @code{save-excursion} restores point and
6481 mark to their original positions; and @code{save-restriction} restores
6482 the original narrowing, if any.
6484 @node narrow Exercise,  , what-line, Narrowing & Widening
6485 @section Exercise with Narrowing
6487 Write a function that will display the first 60 characters of the
6488 current buffer, even if you have narrowed the buffer to its latter
6489 half so that the first line is inaccessible.  Restore point, mark,
6490 and narrowing.  For this exercise, you need to use
6491 @code{save-restriction}, @code{widen}, @code{goto-char},
6492 @code{point-min}, @code{buffer-substring}, @code{message}, and other
6493 functions, a whole potpourri.
6495 @node car cdr & cons, Cutting & Storing Text, Narrowing & Widening, Top
6496 @comment  node-name,  next,  previous,  up
6497 @chapter @code{car}, @code{cdr}, @code{cons}: Fundamental Functions
6498 @findex car, @r{introduced}
6499 @findex cdr, @r{introduced}
6501 In Lisp, @code{car}, @code{cdr}, and @code{cons} are fundamental
6502 functions.  The @code{cons} function is used to construct lists, and
6503 the @code{car} and @code{cdr} functions are used to take them apart.
6505 In the walk through of the @code{copy-region-as-kill} function, we
6506 will see @code{cons} as well as two variants on @code{cdr},
6507 namely, @code{setcdr} and @code{nthcdr}.  (@xref{copy-region-as-kill}.)
6509 @menu
6510 * Strange Names::               An historical aside: why the strange names?
6511 * car & cdr::                   Functions for extracting part of a list.
6512 * cons::                        Constructing a list.
6513 * nthcdr::                      Calling @code{cdr} repeatedly.
6514 * nth::
6515 * setcar::                      Changing the first element of a list.
6516 * setcdr::                      Changing the rest of a list.
6517 * cons Exercise::
6518 @end menu
6520 @node Strange Names, car & cdr, car cdr & cons, car cdr & cons
6521 @ifnottex
6522 @unnumberedsec Strange Names
6523 @end ifnottex
6525 The name of the @code{cons} function is not unreasonable: it is an
6526 abbreviation of the word `construct'.  The origins of the names for
6527 @code{car} and @code{cdr}, on the other hand, are esoteric: @code{car}
6528 is an acronym from the phrase `Contents of the Address part of the
6529 Register'; and @code{cdr} (pronounced `could-er') is an acronym from
6530 the phrase `Contents of the Decrement part of the Register'.  These
6531 phrases refer to specific pieces of hardware on the very early
6532 computer on which the original Lisp was developed.  Besides being
6533 obsolete, the phrases have been completely irrelevant for more than 25
6534 years to anyone thinking about Lisp.  Nonetheless, although a few
6535 brave scholars have begun to use more reasonable names for these
6536 functions, the old terms are still in use.  In particular, since the
6537 terms are used in the Emacs Lisp source code, we will use them in this
6538 introduction.
6540 @node car & cdr, cons, Strange Names, car cdr & cons
6541 @comment  node-name,  next,  previous,  up
6542 @section @code{car} and @code{cdr}
6544 The @sc{car} of a list is, quite simply, the first item in the list.
6545 Thus the @sc{car} of the list @code{(rose violet daisy buttercup)} is
6546 @code{rose}.
6548 @need 1200
6549 If you are reading this in Info in GNU Emacs, you can see this by
6550 evaluating the following:
6552 @smallexample
6553 (car '(rose violet daisy buttercup))
6554 @end smallexample
6556 @noindent
6557 After evaluating the expression, @code{rose} will appear in the echo
6558 area.
6560 Clearly, a more reasonable name for the @code{car} function would be
6561 @code{first} and this is often suggested.
6563 @code{car} does not remove the first item from the list; it only reports
6564 what it is.  After @code{car} has been applied to a list, the list is
6565 still the same as it was.  In the jargon, @code{car} is
6566 `non-destructive'.  This feature turns out to be important.
6568 The @sc{cdr} of a list is the rest of the list, that is, the
6569 @code{cdr} function returns the part of the list that follows the
6570 first item.  Thus, while the @sc{car} of the list @code{'(rose violet
6571 daisy buttercup)} is @code{rose}, the rest of the list, the value
6572 returned by the @code{cdr} function, is @code{(violet daisy
6573 buttercup)}.
6575 @need 1250
6576 You can see this by evaluating the following in the usual way:
6578 @smallexample
6579 (cdr '(rose violet daisy buttercup))
6580 @end smallexample
6582 @noindent
6583 When you evaluate this, @code{(violet daisy buttercup)} will appear in
6584 the echo area.
6586 Like @code{car}, @code{cdr} does not remove any elements from the
6587 list---it just returns a report of what the second and subsequent
6588 elements are.
6590 Incidentally, in the example, the list of flowers is quoted.  If it were
6591 not, the Lisp interpreter would try to evaluate the list by calling
6592 @code{rose} as a function.  In this example, we do not want to do that.
6594 Clearly, a more reasonable name for @code{cdr} would be @code{rest}.
6596 (There is a lesson here: when you name new functions, consider very
6597 carefully what you are doing, since you may be stuck with the names
6598 for far longer than you expect.  The reason this document perpetuates
6599 these names is that the Emacs Lisp source code uses them, and if I did
6600 not use them, you would have a hard time reading the code; but do,
6601 please, try to avoid using these terms yourself.  The people who come
6602 after you will be grateful to you.)
6604 When @code{car} and @code{cdr} are applied to a list made up of symbols,
6605 such as the list @code{(pine fir oak maple)}, the element of the list
6606 returned by the function @code{car} is the symbol @code{pine} without
6607 any parentheses around it.  @code{pine} is the first element in the
6608 list.  However, the @sc{cdr} of the list is a list itself, @code{(fir
6609 oak maple)}, as you can see by evaluating the following expressions in
6610 the usual way:
6612 @smallexample
6613 @group
6614 (car '(pine fir oak maple))
6616 (cdr '(pine fir oak maple))
6617 @end group
6618 @end smallexample
6620 On the other hand, in a list of lists, the first element is itself a
6621 list.  @code{car} returns this first element as a list.  For example,
6622 the following list contains three sub-lists, a list of carnivores, a
6623 list of herbivores and a list of sea mammals:
6625 @smallexample
6626 @group
6627 (car '((lion tiger cheetah)
6628        (gazelle antelope zebra)
6629        (whale dolphin seal)))
6630 @end group
6631 @end smallexample
6633 @noindent
6634 In this example, the first element or @sc{car} of the list is the list of
6635 carnivores, @code{(lion tiger cheetah)}, and the rest of the list is
6636 @code{((gazelle antelope zebra) (whale dolphin seal))}.
6638 @smallexample
6639 @group
6640 (cdr '((lion tiger cheetah)
6641        (gazelle antelope zebra)
6642        (whale dolphin seal)))
6643 @end group
6644 @end smallexample
6646 It is worth saying again that @code{car} and @code{cdr} are
6647 non-destructive---that is, they do not modify or change lists to which
6648 they are applied.  This is very important for how they are used.
6650 Also, in the first chapter, in the discussion about atoms, I said that
6651 in Lisp, ``certain kinds of atom, such as an array, can be separated
6652 into parts; but the mechanism for doing this is different from the
6653 mechanism for splitting a list.  As far as Lisp is concerned, the
6654 atoms of a list are unsplittable.''  (@xref{Lisp Atoms}.)  The
6655 @code{car} and @code{cdr} functions are used for splitting lists and
6656 are considered fundamental to Lisp.  Since they cannot split or gain
6657 access to the parts of an array, an array is considered an atom.
6658 Conversely, the other fundamental function, @code{cons}, can put
6659 together or construct a list, but not an array.  (Arrays are handled
6660 by array-specific functions.  @xref{Arrays, , Arrays, elisp, The GNU
6661 Emacs Lisp Reference Manual}.)
6663 @node cons, nthcdr, car & cdr, car cdr & cons
6664 @comment  node-name,  next,  previous,  up
6665 @section @code{cons}
6666 @findex cons, @r{introduced}
6668 The @code{cons} function constructs lists; it is the inverse of
6669 @code{car} and @code{cdr}.  For example, @code{cons} can be used to make
6670 a four element list from the three element list, @code{(fir oak maple)}:
6672 @smallexample
6673 (cons 'pine '(fir oak maple))
6674 @end smallexample
6676 @need 800
6677 @noindent
6678 After evaluating this list, you will see
6680 @smallexample
6681 (pine fir oak maple)
6682 @end smallexample
6684 @noindent
6685 appear in the echo area.  @code{cons} causes the creation of a new
6686 list in which the element is followed by the elements of the original
6687 list.
6689 We often say that `@code{cons} puts a new element at the beginning of
6690 a list; it attaches or pushes elements onto the list', but this
6691 phrasing can be misleading, since @code{cons} does not change an
6692 existing list, but creates a new one.
6694 Like @code{car} and @code{cdr}, @code{cons} is non-destructive.
6696 @menu
6697 * Build a list::
6698 * length::                      How to find the length of a list.
6699 @end menu
6701 @node Build a list, length, cons, cons
6702 @ifnottex
6703 @unnumberedsubsec Build a list
6704 @end ifnottex
6706 @code{cons} must have a list to attach to.@footnote{Actually, you can
6707 @code{cons} an element to an atom to produce a dotted pair.  Dotted
6708 pairs are not discussed here; see @ref{Dotted Pair Notation, , Dotted
6709 Pair Notation, elisp, The GNU Emacs Lisp Reference Manual}.}  You
6710 cannot start from absolutely nothing.  If you are building a list, you
6711 need to provide at least an empty list at the beginning.  Here is a
6712 series of @code{cons} expressions that build up a list of flowers.  If
6713 you are reading this in Info in GNU Emacs, you can evaluate each of
6714 the expressions in the usual way; the value is printed in this text
6715 after @samp{@result{}}, which you may read as `evaluates to'.
6717 @smallexample
6718 @group
6719 (cons 'buttercup ())
6720      @result{} (buttercup)
6721 @end group
6723 @group
6724 (cons 'daisy '(buttercup))
6725      @result{} (daisy buttercup)
6726 @end group
6728 @group
6729 (cons 'violet '(daisy buttercup))
6730      @result{} (violet daisy buttercup)
6731 @end group
6733 @group
6734 (cons 'rose '(violet daisy buttercup))
6735      @result{} (rose violet daisy buttercup)
6736 @end group
6737 @end smallexample
6739 @noindent
6740 In the first example, the empty list is shown as @code{()} and a list
6741 made up of @code{buttercup} followed by the empty list is constructed.
6742 As you can see, the empty list is not shown in the list that was
6743 constructed.  All that you see is @code{(buttercup)}.  The empty list is
6744 not counted as an element of a list because there is nothing in an empty
6745 list.  Generally speaking, an empty list is invisible.
6747 The second example, @code{(cons 'daisy '(buttercup))} constructs a new,
6748 two element list by putting @code{daisy} in front of @code{buttercup};
6749 and the third example constructs a three element list by putting
6750 @code{violet} in front of @code{daisy} and @code{buttercup}.
6752 @node length,  , Build a list, cons
6753 @comment  node-name,  next,  previous,  up
6754 @subsection Find the Length of a List: @code{length}
6755 @findex length
6757 You can find out how many elements there are in a list by using the Lisp
6758 function @code{length}, as in the following examples:
6760 @smallexample
6761 @group
6762 (length '(buttercup))
6763      @result{} 1
6764 @end group
6766 @group
6767 (length '(daisy buttercup))
6768      @result{} 2
6769 @end group
6771 @group
6772 (length (cons 'violet '(daisy buttercup)))
6773      @result{} 3
6774 @end group
6775 @end smallexample
6777 @noindent
6778 In the third example, the @code{cons} function is used to construct a
6779 three element list which is then passed to the @code{length} function as
6780 its argument.
6782 @need 1200
6783 We can also use @code{length} to count the number of elements in an
6784 empty list:
6786 @smallexample
6787 @group
6788 (length ())
6789      @result{} 0
6790 @end group
6791 @end smallexample
6793 @noindent
6794 As you would expect, the number of elements in an empty list is zero.
6796 An interesting experiment is to find out what happens if you try to find
6797 the length of no list at all; that is, if you try to call @code{length}
6798 without giving it an argument, not even an empty list:
6800 @smallexample
6801 (length )
6802 @end smallexample
6804 @need 800
6805 @noindent
6806 What you see, if you evaluate this, is the error message
6808 @smallexample
6809 Wrong number of arguments: #<subr length>, 0
6810 @end smallexample
6812 @noindent
6813 This means that the function receives the wrong number of
6814 arguments, zero, when it expects some other number of arguments.  In
6815 this case, one argument is expected, the argument being a list whose
6816 length the function is measuring.  (Note that @emph{one} list is
6817 @emph{one} argument, even if the list has many elements inside it.)
6819 The part of the error message that says @samp{#<subr length>} is the
6820 name of the function.  This is written with a special notation,
6821 @samp{#<subr}, that indicates that the function @code{length} is one
6822 of the primitive functions written in C rather than in Emacs Lisp.
6823 (@samp{subr} is an abbreviation for `subroutine'.)  @xref{What Is a
6824 Function, , What Is a Function?, elisp , The GNU Emacs Lisp Reference
6825 Manual}, for more about subroutines.
6827 @node nthcdr, nth, cons, car cdr & cons
6828 @comment  node-name,  next,  previous,  up
6829 @section @code{nthcdr}
6830 @findex nthcdr
6832 The @code{nthcdr} function is associated with the @code{cdr} function.
6833 What it does is take the @sc{cdr} of a list repeatedly.
6835 If you take the @sc{cdr} of the list @code{(pine fir
6836 oak maple)}, you will be returned the list @code{(fir oak maple)}.  If you
6837 repeat this on what was returned, you will be returned the list
6838 @code{(oak maple)}.  (Of course, repeated @sc{cdr}ing on the original
6839 list will just give you the original @sc{cdr} since the function does
6840 not change the list.  You need to evaluate the @sc{cdr} of the
6841 @sc{cdr} and so on.)  If you continue this, eventually you will be
6842 returned an empty list, which in this case, instead of being shown as
6843 @code{()} is shown as @code{nil}.
6845 @need 1200
6846 For review, here is a series of repeated @sc{cdr}s, the text following
6847 the @samp{@result{}} shows what is returned.
6849 @smallexample
6850 @group
6851 (cdr '(pine fir oak maple))
6852      @result{}(fir oak maple)
6853 @end group
6855 @group
6856 (cdr '(fir oak maple))
6857      @result{} (oak maple)
6858 @end group
6860 @group
6861 (cdr '(oak maple))
6862      @result{}(maple)
6863 @end group
6865 @group
6866 (cdr '(maple))
6867      @result{} nil
6868 @end group
6870 @group
6871 (cdr 'nil)
6872      @result{} nil
6873 @end group
6875 @group
6876 (cdr ())
6877      @result{} nil
6878 @end group
6879 @end smallexample
6881 @need 1200
6882 You can also do several @sc{cdr}s without printing the values in
6883 between, like this:
6885 @smallexample
6886 @group
6887 (cdr (cdr '(pine fir oak maple)))
6888      @result{} (oak maple)
6889 @end group
6890 @end smallexample
6892 @noindent
6893 In this example, the Lisp interpreter evaluates the innermost list first.
6894 The innermost list is quoted, so it just passes the list as it is to the
6895 innermost @code{cdr}.  This @code{cdr} passes a list made up of the
6896 second and subsequent elements of the list to the outermost @code{cdr},
6897 which produces a list composed of the third and subsequent elements of
6898 the original list.  In this example, the @code{cdr} function is repeated
6899 and returns a list that consists of the original list without its
6900 first two elements.
6902 The @code{nthcdr} function does the same as repeating the call to
6903 @code{cdr}.  In the following example, the argument 2 is passed to the
6904 function @code{nthcdr}, along with the list, and the value returned is
6905 the list without its first two items, which is exactly the same
6906 as repeating @code{cdr} twice on the list:
6908 @smallexample
6909 @group
6910 (nthcdr 2 '(pine fir oak maple))
6911      @result{} (oak maple)
6912 @end group
6913 @end smallexample
6915 @need 1200
6916 Using the original four element list, we can see what happens when
6917 various numeric arguments are passed to @code{nthcdr}, including 0, 1,
6918 and 5:
6920 @smallexample
6921 @group
6922 ;; @r{Leave the list as it was.}
6923 (nthcdr 0 '(pine fir oak maple))
6924      @result{} (pine fir oak maple)
6925 @end group
6927 @group
6928 ;; @r{Return a copy without the first element.}
6929 (nthcdr 1 '(pine fir oak maple))
6930      @result{} (fir oak maple)
6931 @end group
6933 @group
6934 ;; @r{Return a copy of the list without three elements.}
6935 (nthcdr 3 '(pine fir oak maple))
6936      @result{} (maple)
6937 @end group
6939 @group
6940 ;; @r{Return a copy lacking all four elements.}
6941 (nthcdr 4 '(pine fir oak maple))
6942      @result{} nil
6943 @end group
6945 @group
6946 ;; @r{Return a copy lacking all elements.}
6947 (nthcdr 5 '(pine fir oak maple))
6948      @result{} nil
6949 @end group
6950 @end smallexample
6952 @node nth, setcar, nthcdr, car cdr & cons
6953 @comment  node-name,  next,  previous,  up
6954 @section @code{nth}
6955 @findex nth
6957 The @code{nthcdr} function takes the @sc{cdr} of a list repeatedly.
6958 The @code{nth} function takes the @sc{car} of the result returned by
6959 @code{nthcdr}.  It returns the Nth element of the list.
6961 @need 1500
6962 Thus, if it were not defined in C for speed, the definition of
6963 @code{nth} would be:
6965 @smallexample
6966 @group
6967 (defun nth (n list)
6968   "Returns the Nth element of LIST.
6969 N counts from zero.  If LIST is not that long, nil is returned."
6970   (car (nthcdr n list)))
6971 @end group
6972 @end smallexample
6974 @noindent
6975 (Originally, @code{nth} was defined in Emacs Lisp in @file{subr.el},
6976 but its definition was redone in C in the 1980s.)
6978 The @code{nth} function returns a single element of a list.
6979 This can be very convenient.
6981 Note that the elements are numbered from zero, not one.  That is to
6982 say, the first element of a list, its @sc{car} is the zeroth element.
6983 This is called `zero-based' counting and often bothers people who
6984 are accustomed to the first element in a list being number one, which
6985 is `one-based'.
6987 @need 1250
6988 For example:
6990 @smallexample
6991 @group
6992 (nth 0 '("one" "two" "three"))
6993     @result{} "one"
6995 (nth 1 '("one" "two" "three"))
6996     @result{} "two"
6997 @end group
6998 @end smallexample
7000 It is worth mentioning that @code{nth}, like @code{nthcdr} and
7001 @code{cdr}, does not change the original list---the function is
7002 non-destructive.  This is in sharp contrast to the @code{setcar} and
7003 @code{setcdr} functions.
7005 @node setcar, setcdr, nth, car cdr & cons
7006 @comment  node-name,  next,  previous,  up
7007 @section @code{setcar}
7008 @findex setcar
7010 As you might guess from their names, the @code{setcar} and @code{setcdr}
7011 functions set the @sc{car} or the @sc{cdr} of a list to a new value.
7012 They actually change the original list, unlike @code{car} and @code{cdr}
7013 which leave the original list as it was.  One way to find out how this
7014 works is to experiment.  We will start with the @code{setcar} function.
7016 @need 1200
7017 First, we can make a list and then set the value of a variable to the
7018 list, using the @code{setq} function.  Here is a list of animals:
7020 @smallexample
7021 (setq animals '(antelope giraffe lion tiger))
7022 @end smallexample
7024 @noindent
7025 If you are reading this in Info inside of GNU Emacs, you can evaluate
7026 this expression in the usual fashion, by positioning the cursor after
7027 the expression and typing @kbd{C-x C-e}.  (I'm doing this right here as
7028 I write this.  This is one of the advantages of having the interpreter
7029 built into the computing environment.)
7031 @need 1200
7032 When we evaluate the variable @code{animals}, we see that it is bound to
7033 the list @code{(antelope giraffe lion tiger)}:
7035 @smallexample
7036 @group
7037 animals
7038      @result{} (antelope giraffe lion tiger)
7039 @end group
7040 @end smallexample
7042 @noindent
7043 Put another way, the variable @code{animals} points to the list
7044 @code{(antelope giraffe lion tiger)}.
7046 Next, evaluate the function @code{setcar} while passing it two
7047 arguments, the variable @code{animals} and the quoted symbol
7048 @code{hippopotamus}; this is done by writing the three element list
7049 @code{(setcar animals 'hippopotamus)} and then evaluating it in the
7050 usual fashion:
7052 @smallexample
7053 (setcar animals 'hippopotamus)
7054 @end smallexample
7056 @need 1200
7057 @noindent
7058 After evaluating this expression, evaluate the variable @code{animals}
7059 again.  You will see that the list of animals has changed:
7061 @smallexample
7062 @group
7063 animals
7064      @result{} (hippopotamus giraffe lion tiger)
7065 @end group
7066 @end smallexample
7068 @noindent
7069 The first element on the list, @code{antelope} is replaced by
7070 @code{hippopotamus}.
7072 So we can see that @code{setcar} did not add a new element to the list
7073 as @code{cons} would have; it replaced @code{giraffe} with
7074 @code{hippopotamus}; it @emph{changed} the list.
7076 @node setcdr, cons Exercise, setcar, car cdr & cons
7077 @comment  node-name,  next,  previous,  up
7078 @section @code{setcdr}
7079 @findex setcdr
7081 The @code{setcdr} function is similar to the @code{setcar} function,
7082 except that the function replaces the second and subsequent elements of
7083 a list rather than the first element.
7085 @need 1200
7086 To see how this works, set the value of the variable to a list of
7087 domesticated animals by evaluating the following expression:
7089 @smallexample
7090 (setq domesticated-animals '(horse cow sheep goat))
7091 @end smallexample
7093 @need 1200
7094 @noindent
7095 If you now evaluate the list, you will be returned the list
7096 @code{(horse cow sheep goat)}:
7098 @smallexample
7099 @group
7100 domesticated-animals
7101      @result{} (horse cow sheep goat)
7102 @end group
7103 @end smallexample
7105 @need 1200
7106 Next, evaluate @code{setcdr} with two arguments, the name of the
7107 variable which has a list as its value, and the list to which the
7108 @sc{cdr} of the first list will be set;
7110 @smallexample
7111 (setcdr domesticated-animals '(cat dog))
7112 @end smallexample
7114 @noindent
7115 If you evaluate this expression, the list @code{(cat dog)} will appear
7116 in the echo area.  This is the value returned by the function.  The
7117 result we are interested in is the ``side effect'', which we can see by
7118 evaluating the variable @code{domesticated-animals}:
7120 @smallexample
7121 @group
7122 domesticated-animals
7123      @result{} (horse cat dog)
7124 @end group
7125 @end smallexample
7127 @noindent
7128 Indeed, the list is changed from @code{(horse cow sheep goat)} to
7129 @code{(horse cat dog)}.  The @sc{cdr} of the list is changed from
7130 @code{(cow sheep goat)} to @code{(cat dog)}.
7132 @node cons Exercise,  , setcdr, car cdr & cons
7133 @section Exercise
7135 Construct a list of four birds by evaluating several expressions with
7136 @code{cons}.  Find out what happens when you @code{cons} a list onto
7137 itself.  Replace the first element of the list of four birds with a
7138 fish.  Replace the rest of that list with a list of other fish.
7140 @node Cutting & Storing Text, List Implementation, car cdr & cons, Top
7141 @comment  node-name,  next,  previous,  up
7142 @chapter Cutting and Storing Text
7143 @cindex Cutting and storing text
7144 @cindex Storing and cutting text
7145 @cindex Killing text
7146 @cindex Clipping text
7147 @cindex Erasing text
7148 @cindex Deleting text
7150 Whenever you cut or clip text out of a buffer with a `kill' command in
7151 GNU Emacs, it is stored in a list and you can bring it back with a
7152 `yank' command.
7154 (The use of the word `kill' in Emacs for processes which specifically
7155 @emph{do not} destroy the values of the entities is an unfortunate
7156 historical accident.  A much more appropriate word would be `clip' since
7157 that is what the kill commands do; they clip text out of a buffer and
7158 put it into storage from which it can be brought back.  I have often
7159 been tempted to replace globally all occurrences of `kill' in the Emacs
7160 sources with `clip' and all occurrences of `killed' with `clipped'.)
7162 @menu
7163 * Storing Text::                Text is stored in a list.
7164 * zap-to-char::                 Cutting out text up to a character.
7165 * kill-region::                 Cutting text out of a region.
7166 * Digression into C::           Minor note on C programming language macros.
7167 * defvar::                      How to give a variable an initial value.
7168 * copy-region-as-kill::         A definition for copying text.
7169 * cons & search-fwd Review::
7170 * search Exercises::
7171 @end menu
7173 @node Storing Text, zap-to-char, Cutting & Storing Text, Cutting & Storing Text
7174 @ifnottex
7175 @unnumberedsec Storing Text in a List
7176 @end ifnottex
7178 When text is cut out of a buffer, it is stored on a list.  Successive
7179 pieces of text are stored on the list successively, so the list might
7180 look like this:
7182 @smallexample
7183 ("a piece of text" "previous piece")
7184 @end smallexample
7186 @need 1200
7187 @noindent
7188 The function @code{cons} can be used to to create a new list from a
7189 piece of text (an `atom', to use the jargon) and an existing list,
7190 like this:
7192 @smallexample
7193 @group
7194 (cons "another piece"
7195       '("a piece of text" "previous piece"))
7196 @end group
7197 @end smallexample
7199 @need 1200
7200 @noindent
7201 If you evaluate this expression, a list of three elements will appear in
7202 the echo area:
7204 @smallexample
7205 ("another piece" "a piece of text" "previous piece")
7206 @end smallexample
7208 With the @code{car} and @code{nthcdr} functions, you can retrieve
7209 whichever piece of text you want.  For example, in the following code,
7210 @code{nthcdr 1 @dots{}} returns the list with the first item removed;
7211 and the @code{car} returns the first element of that remainder---the
7212 second element of the original list:
7214 @smallexample
7215 @group
7216 (car (nthcdr 1 '("another piece"
7217                  "a piece of text"
7218                  "previous piece")))
7219      @result{} "a piece of text"
7220 @end group
7221 @end smallexample
7223 The actual functions in Emacs are more complex than this, of course.
7224 The code for cutting and retrieving text has to be written so that
7225 Emacs can figure out which element in the list you want---the first,
7226 second, third, or whatever.  In addition, when you get to the end of
7227 the list, Emacs should give you the first element of the list, rather
7228 than nothing at all.
7230 The list that holds the pieces of text is called the @dfn{kill ring}.
7231 This chapter leads up to a description of the kill ring and how it is
7232 used by first tracing how the @code{zap-to-char} function works.  This
7233 function uses (or `calls') a function that invokes a function that
7234 manipulates the kill ring.  Thus, before reaching the mountains, we
7235 climb the foothills.
7237 A subsequent chapter describes how text that is cut from the buffer is
7238 retrieved.  @xref{Yanking, , Yanking Text Back}.
7240 @node zap-to-char, kill-region, Storing Text, Cutting & Storing Text
7241 @comment  node-name,  next,  previous,  up
7242 @section @code{zap-to-char}
7243 @findex zap-to-char
7245 The @code{zap-to-char} function barely changed between GNU Emacs
7246 version 19 and GNU Emacs version 21.  However, @code{zap-to-char}
7247 calls another function, @code{kill-region}, which enjoyed a major rewrite
7248 on the way to version 21.
7250 The @code{kill-region} function in Emacs 19 is complex, but does not
7251 use code that is important at this time.  We will skip it.
7253 The @code{kill-region} function in Emacs 21 is easier to read than the
7254 same function in Emacs 19 and introduces a very important concept,
7255 that of error handling.  We will walk through the function.
7257 But first, let us look at the interactive @code{zap-to-char} function.
7259 @menu
7260 * Complete zap-to-char::        The complete implementation.
7261 * zap-to-char interactive::     A three part interactive expression.
7262 * zap-to-char body::            A short overview.
7263 * search-forward::              How to search for a string.
7264 * progn::                       The @code{progn} special form.
7265 * Summing up zap-to-char::      Using @code{point} and @code{search-forward}.
7266 @end menu
7268 @node Complete zap-to-char, zap-to-char interactive, zap-to-char, zap-to-char
7269 @ifnottex
7270 @unnumberedsubsec The Complete @code{zap-to-char} Implementation
7271 @end ifnottex
7273 The GNU Emacs version 19 and version 21 implementations of the
7274 @code{zap-to-char} function are nearly identical in form, and they
7275 work alike.  The function removes the text in the region between the
7276 location of the cursor (i.e., of point) up to and including the next
7277 occurrence of a specified character.  The text that @code{zap-to-char}
7278 removes is put in the kill ring; and it can be retrieved from the kill
7279 ring by typing @kbd{C-y} (@code{yank}).  If the command is given an
7280 argument, it removes text through that number of occurrences.  Thus,
7281 if the cursor were at the beginning of this sentence and the character
7282 were @samp{s}, @samp{Thus} would be removed.  If the argument were
7283 two, @samp{Thus, if the curs} would be removed, up to and including
7284 the @samp{s} in @samp{cursor}.
7286 If the specified character is not found, @code{zap-to-char} will say
7287 ``Search failed'', tell you the character you typed, and not remove
7288 any text.
7290 In order to determine how much text to remove, @code{zap-to-char} uses
7291 a search function.  Searches are used extensively in code that
7292 manipulates text, and we will focus attention on them as well as on the
7293 deletion command.
7295 @need 800
7296 Here is the complete text of the version 19 implementation of the function:
7298 @c v 19
7299 @smallexample
7300 @group
7301 (defun zap-to-char (arg char)  ; version 19 implementation
7302   "Kill up to and including ARG'th occurrence of CHAR.
7303 Goes backward if ARG is negative; error if CHAR not found."
7304   (interactive "*p\ncZap to char: ")
7305   (kill-region (point)
7306                (progn
7307                  (search-forward
7308                   (char-to-string char) nil nil arg)
7309                  (point))))
7310 @end group
7311 @end smallexample
7313 @node zap-to-char interactive, zap-to-char body, Complete zap-to-char, zap-to-char
7314 @comment  node-name,  next,  previous,  up
7315 @subsection The @code{interactive} Expression
7317 @need 800
7318 The interactive expression in the @code{zap-to-char} command looks like
7319 this:
7321 @smallexample
7322 (interactive "*p\ncZap to char: ")
7323 @end smallexample
7325 The part within quotation marks, @code{"*p\ncZap to char:@: "}, specifies
7326 three different things.  First, and most simply, the asterisk, @samp{*},
7327 causes an error to be signalled if the buffer is read-only.  This means that
7328 if you try @code{zap-to-char} in a read-only buffer you will not be able to
7329 remove text, and you will receive a message that says ``Buffer is
7330 read-only''; your terminal may beep at you as well.
7332 The version 21 implementation does not have the asterisk, @samp{*}.  The
7333 function works the same as in version 19: in both cases, it cannot
7334 remove text from a read-only buffer but the function does copy the
7335 text that would have been removed to the kill ring.  Also, in both
7336 cases, you see an error message.
7338 However, the version 19 implementation copies text from a read-only
7339 buffer only because of a mistake in the implementation of
7340 @code{interactive}.  According to the documentation for
7341 @code{interactive}, the asterisk, @samp{*}, should prevent the
7342 @code{zap-to-char} function from doing anything at all when the buffer
7343 is read only.  The function should not copy the text to the kill ring.
7344 It is a bug that it does.
7346 In version 21, @code{interactive} is implemented correctly.  So the
7347 asterisk, @samp{*}, had to be removed from the interactive
7348 specification.  If you insert an @samp{*} and evaluate the function
7349 definition, then the next time you run the @code{zap-to-char} function
7350 on a read-only buffer, you will not copy any text.
7352 That change aside, and a change to the documentation, the two versions
7353 of the  @code{zap-to-char} function are identical.
7355 Let us continue with the interactive specification.
7357 The second part of @code{"*p\ncZap to char:@: "} is the @samp{p}.
7358 This part is separated from the next part by a newline, @samp{\n}.
7359 The @samp{p} means that the first argument to the function will be
7360 passed the value of a `processed prefix'.  The prefix argument is
7361 passed by typing @kbd{C-u} and a number, or @kbd{M-} and a number.  If
7362 the function is called interactively without a prefix, 1 is passed to
7363 this argument.
7365 The third part of @code{"*p\ncZap to char:@: "} is @samp{cZap to char:@:
7366 }.  In this part, the lower case @samp{c} indicates that
7367 @code{interactive} expects a prompt and that the argument will be a
7368 character.  The prompt follows the @samp{c} and is the string @samp{Zap
7369 to char:@: } (with a space after the colon to make it look good).
7371 What all this does is prepare the arguments to @code{zap-to-char} so they
7372 are of the right type, and give the user a prompt.
7374 @node zap-to-char body, search-forward, zap-to-char interactive, zap-to-char
7375 @comment  node-name,  next,  previous,  up
7376 @subsection The Body of @code{zap-to-char}
7378 The body of the @code{zap-to-char} function contains the code that
7379 kills (that is, removes) the text in the region from the current
7380 position of the cursor up to and including the specified character.
7381 The first part of the code looks like this:
7383 @smallexample
7384 (kill-region (point) @dots{}
7385 @end smallexample
7387 @noindent
7388 @code{(point)} is the current position of the cursor.
7390 The next part of the code is an expression using @code{progn}.  The body
7391 of the @code{progn} consists of calls to @code{search-forward} and
7392 @code{point}.
7394 It is easier to understand how @code{progn} works after learning about
7395 @code{search-forward}, so we will look at @code{search-forward} and
7396 then at @code{progn}.
7398 @node search-forward, progn, zap-to-char body, zap-to-char
7399 @comment  node-name,  next,  previous,  up
7400 @subsection The @code{search-forward} Function
7401 @findex search-forward
7403 The @code{search-forward} function is used to locate the
7404 zapped-for-character in @code{zap-to-char}.  If the search is
7405 successful, @code{search-forward} leaves point immediately after the
7406 last character in the target string.  (In @code{zap-to-char}, the
7407 target string is just one character long.)  If the search is
7408 backwards, @code{search-forward} leaves point just before the first
7409 character in the target.  Also, @code{search-forward} returns @code{t}
7410 for true.  (Moving point is therefore a `side effect'.)
7412 @need 1250
7413 In @code{zap-to-char}, the @code{search-forward} function looks like this:
7415 @smallexample
7416 (search-forward (char-to-string char) nil nil arg)
7417 @end smallexample
7419 The @code{search-forward} function takes four arguments:
7421 @enumerate
7422 @item
7423 The first argument is the target, what is searched for.  This must be a
7424 string, such as @samp{"z"}.
7426 As it happens, the argument passed to @code{zap-to-char} is a single
7427 character.  Because of the way computers are built, the Lisp
7428 interpreter may treat a single character as being different from a
7429 string of characters.  Inside the computer, a single character has a
7430 different electronic format than a string of one character.  (A single
7431 character can often be recorded in the computer using exactly one
7432 byte; but a string may be longer, and the computer needs to be ready
7433 for this.)  Since the @code{search-forward} function searches for a
7434 string, the character that the @code{zap-to-char} function receives as
7435 its argument must be converted inside the computer from one format to
7436 the other; otherwise the @code{search-forward} function will fail.
7437 The @code{char-to-string} function is used to make this conversion.
7439 @item
7440 The second argument bounds the search; it is specified as a position in
7441 the buffer.  In this case, the search can go to the end of the buffer,
7442 so no bound is set and the second argument is @code{nil}.
7444 @item
7445 The third argument tells the function what it should do if the search
7446 fails---it can signal an error (and print a message) or it can return
7447 @code{nil}.  A @code{nil} as the third argument causes the function to
7448 signal an error when the search fails.
7450 @item
7451 The fourth argument to @code{search-forward} is the repeat count---how
7452 many occurrences of the string to look for.  This argument is optional
7453 and if the function is called without a repeat count, this argument is
7454 passed the value 1.  If this argument is negative, the search goes
7455 backwards.
7456 @end enumerate
7458 @need 800
7459 In template form, a @code{search-forward} expression looks like this:
7461 @smallexample
7462 @group
7463 (search-forward "@var{target-string}"
7464                 @var{limit-of-search}
7465                 @var{what-to-do-if-search-fails}
7466                 @var{repeat-count})
7467 @end group
7468 @end smallexample
7470 We will look at @code{progn} next.
7472 @node progn, Summing up zap-to-char, search-forward, zap-to-char
7473 @comment  node-name,  next,  previous,  up
7474 @subsection The @code{progn} Special Form
7475 @findex progn
7477 @code{progn} is a special form that causes each of its arguments to be
7478 evaluated in sequence and then returns the value of the last one.  The
7479 preceding expressions are evaluated only for the side effects they
7480 perform.  The values produced by them are discarded.
7482 @need 800
7483 The template for a @code{progn} expression is very simple:
7485 @smallexample
7486 @group
7487 (progn
7488   @var{body}@dots{})
7489 @end group
7490 @end smallexample
7492 In @code{zap-to-char}, the @code{progn} expression has to do two things:
7493 put point in exactly the right position; and return the location of
7494 point so that @code{kill-region} will know how far to kill to.
7496 The first argument to the @code{progn} is @code{search-forward}.  When
7497 @code{search-forward} finds the string, the function leaves point
7498 immediately after the last character in the target string.  (In this
7499 case the target string is just one character long.)  If the search is
7500 backwards, @code{search-forward} leaves point just before the first
7501 character in the target.  The movement of point is a side effect.
7503 The second and last argument to @code{progn} is the expression
7504 @code{(point)}.  This expression returns the value of point, which in
7505 this case will be the location to which it has been moved by
7506 @code{search-forward}.  This value is returned by the @code{progn}
7507 expression and is passed to @code{kill-region} as @code{kill-region}'s
7508 second argument.
7510 @node Summing up zap-to-char,  , progn, zap-to-char
7511 @comment  node-name,  next,  previous,  up
7512 @subsection Summing up @code{zap-to-char}
7514 Now that we have seen how @code{search-forward} and @code{progn} work,
7515 we can see how the @code{zap-to-char} function works as a whole.
7517 The first argument to @code{kill-region} is the position of the cursor
7518 when the @code{zap-to-char} command is given---the value of point at
7519 that time.  Within the @code{progn}, the search function then moves
7520 point to just after the zapped-to-character and @code{point} returns the
7521 value of this location.  The @code{kill-region} function puts together
7522 these two values of point, the first one as the beginning of the region
7523 and the second one as the end of the region, and removes the region.
7525 The @code{progn} special form is necessary because the @code{kill-region}
7526 command takes two arguments; and it would fail if @code{search-forward}
7527 and @code{point} expressions were  written in sequence as two
7528 additional arguments.  The @code{progn} expression is a single argument
7529 to @code{kill-region} and returns the one value that @code{kill-region}
7530 needs for its second argument.
7532 @node kill-region, Digression into C, zap-to-char, Cutting & Storing Text
7533 @comment  node-name,  next,  previous,  up
7534 @section @code{kill-region}
7535 @findex kill-region
7537 The @code{zap-to-char} function uses the @code{kill-region} function.
7538 This function clips text from a region and copies that text to
7539 the kill ring, from which it may be retrieved.
7541 The Emacs 21 version of that function uses @code{condition-case} and
7542 @code{copy-region-as-kill}, both of which we will explain.
7543 @code{condition-case} is an important special form.
7545 In essence, the @code{kill-region} function calls
7546 @code{condition-case}, which takes three arguments.  In this function,
7547 the first argument does nothing.  The second argument contains the
7548 code that does the work when all goes well.  The third argument
7549 contains the code that is called in the event of an error.
7551 @menu
7552 * Complete kill-region::        The function definition.
7553 * condition-case::              Dealing with a problem.
7554 * delete-and-extract-region::   Doing the work.
7555 @end menu
7557 @node Complete kill-region, condition-case, kill-region, kill-region
7558 @ifnottex
7559 @unnumberedsubsec The Complete @code{kill-region} Definition
7560 @end ifnottex
7562 @need 1200
7563 We will go through the @code{condition-case} code in a moment.  First,
7564 let us look at the complete definition of @code{kill-region}, with
7565 comments added:
7567 @c v 21
7568 @smallexample
7569 @group
7570 (defun kill-region (beg end)
7571   "Kill between point and mark.
7572 The text is deleted but saved in the kill ring."
7573   (interactive "r")
7574 @end group
7576 @group
7577   ;; 1. `condition-case' takes three arguments.
7578   ;;    If the first argument is nil, as it is here,
7579   ;;    information about the error signal is not
7580   ;;    stored for use by another function.
7581   (condition-case nil
7582 @end group
7584 @group
7585       ;; 2. The second argument to `condition-case'
7586       ;;    tells the Lisp interpreter what to do when all goes well.
7587 @end group
7589 @group
7590       ;;    The `delete-and-extract-region' function usually does the
7591       ;;    work.  If the beginning and ending of the region are both
7592       ;;    the same, then the variable `string' will be empty, or nil
7593       (let ((string (delete-and-extract-region beg end)))
7594 @end group
7596 @group
7597         ;; `when' is an `if' clause that cannot take an `else-part'.
7598         ;; Emacs normally sets the value of `last-command' to the
7599         ;; previous command.
7600 @end group
7601 @group
7602         ;; `kill-append' concatenates the new string and the old.
7603         ;; `kill-new' inserts text into a new item in the kill ring.
7604         (when string
7605           (if (eq last-command 'kill-region)
7606               ;; if true, prepend string
7607               (kill-append string (< end beg))
7608             (kill-new string)))
7609         (setq this-command 'kill-region))
7610 @end group
7612 @group
7613     ;; 3. The third argument to `condition-case' tells the interpreter
7614     ;;    what to do with an error.
7615 @end group
7616 @group
7617     ;;    The third argument has a conditions part and a body part.
7618     ;;    If the conditions are met (in this case,
7619     ;;             if text or buffer is read-only)
7620     ;;    then the body is executed.
7621 @end group
7622 @group
7623     ((buffer-read-only text-read-only) ;; this is the if-part
7624      ;; then...
7625      (copy-region-as-kill beg end)
7626 @end group
7627 @group
7628      (if kill-read-only-ok            ;; usually this variable is nil
7629          (message "Read only text copied to kill ring")
7630        ;; or else, signal an error if the buffer is read-only;
7631        (barf-if-buffer-read-only)
7632        ;; and, in any case, signal that the text is read-only.
7633        (signal 'text-read-only (list (current-buffer)))))))
7634 @end group
7635 @end smallexample
7637 @node condition-case, delete-and-extract-region, Complete kill-region, kill-region
7638 @comment  node-name,  next,  previous,  up
7639 @subsection @code{condition-case}
7640 @findex condition-case
7642 As we have seen earlier (@pxref{Making Errors, , Generate an Error
7643 Message}), when the Emacs Lisp interpreter has trouble evaluating an
7644 expression, it provides you with help; in the jargon, this is called
7645 ``signaling an error''.  Usually, the computer stops the program and
7646 shows you a message.
7648 However, some programs undertake complicated actions.  They should not
7649 simply stop on an error.  In the @code{kill-region} function, the most
7650 likely error is that you will try to kill text that is read-only and
7651 cannot be removed.  So the @code{kill-region} function contains code
7652 to handle this circumstance.  This code, which makes up the body of
7653 the @code{kill-region} function, is inside of a @code{condition-case}
7654 special form.
7656 @need 800
7657 The template for @code{condition-case} looks like this:
7659 @smallexample
7660 @group
7661 (condition-case
7662   @var{var}
7663   @var{bodyform}
7664   @var{error-handler}@dots{})
7665 @end group
7666 @end smallexample
7668 The second argument, @var{bodyform}, is straightforward.  The
7669 @code{condition-case} special form causes the Lisp interpreter to
7670 evaluate the code in @var{bodyform}.  If no error occurs, the special
7671 form returns the code's value and produces the side-effects, if any.
7673 In short, the @var{bodyform} part of a @code{condition-case}
7674 expression determines what should happen when everything works
7675 correctly.
7677 However, if an error occurs, among its other actions, the function
7678 generating the error signal will define one or more error condition
7679 names.
7681 An error handler is the third argument to @code{condition case}.
7682 An error handler has two parts, a @var{condition-name} and a
7683 @var{body}.  If the @var{condition-name} part of an error handler
7684 matches a condition name generated by an error, then the @var{body}
7685 part of the error handler is run.
7687 As you will expect, the @var{condition-name} part of an error handler
7688 may be either a single condition name or a list of condition names.
7690 Also, a complete @code{condition-case} expression may contain more
7691 than one error handler.  When an error occurs, the first applicable
7692 handler is run.
7694 Lastly, the first argument to the @code{condition-case} expression,
7695 the @var{var} argument, is sometimes bound to a variable that
7696 contains information about the error.  However, if that argument is
7697 nil, as is the case in @code{kill-region}, that information is
7698 discarded.
7700 @need 1200
7701 In brief, in the @code{kill-region} function, the code
7702 @code{condition-case} works like this:
7704 @smallexample
7705 @group
7706 @var{If no errors}, @var{run only this code}
7707     @var{but}, @var{if errors}, @var{run this other code}.
7708 @end group
7709 @end smallexample
7711 @node delete-and-extract-region,  , condition-case, kill-region
7712 @comment  node-name,  next,  previous,  up
7713 @subsection @code{delete-and-extract-region}
7714 @findex delete-and-extract-region
7716 A @code{condition-case} expression has two parts, a part that is
7717 evaluated in the expectation that all will go well, but which may
7718 generate an error; and a part that is evaluated when there is an
7719 error.
7721 First, let us look at the code in @code{kill-region} that is run in
7722 the expectation that all goes well.  This is the core of the function.
7723 The code looks like this:
7725 @smallexample
7726 @group
7727 (let ((string (delete-and-extract-region beg end)))
7728   (when string
7729     (if (eq last-command 'kill-region)
7730         (kill-append string (< end beg))
7731       (kill-new string)))
7732   (setq this-command 'kill-region))
7733 @end group
7734 @end smallexample
7736 It looks complicated because we have the new functions
7737 @code{delete-and-extract-region}, @code{kill-append}, and
7738 @code{kill-new} as well as the new variables,
7739 @code{last-command} and @code{this-command}.
7741 The @code{delete-and-extract-region} function is straightforward.  It
7742 is a built-in function that deletes the text in a region (a side
7743 effect) and also returns that text.  This is the function that
7744 actually removes the text.  (And if it cannot do that, it signals the
7745 error.)
7747 In this @code{let} expression, the text that
7748 @code{delete-and-extract-region} returns is placed in the local
7749 variable called @samp{string}.  This is the text that is removed from
7750 the buffer.  (To be more precise, the variable is set to point to the
7751 address of the extracted text; to say it is `placed in' the variable
7752 is simply a shorthand.)
7754 If the variable @samp{string} does point to text, that text is added
7755 to the kill ring.  The variable will have a @code{nil} value if no
7756 text was removed.
7758 The code uses @code{when} to determine whether the variable
7759 @samp{string} points to text.  A @code{when} statement is simply a
7760 programmers' convenience.  A @code{when} statement is an @code{if}
7761 statement without the possibility of an else clause.  In your mind, you
7762 can replace @code{when} with @code{if} and understand what goes on.
7763 That is what the Lisp interpreter does.
7765 @cindex Macro, lisp
7766 @cindex Lisp macro
7767 Technically speaking, @code{when} is a Lisp macro.  A Lisp @dfn{macro}
7768 enables you to define new control constructs and other language
7769 features.  It tells the interpreter how to compute another Lisp
7770 expression which will in turn compute the value.  In this case, the
7771 `other expression' is an @code{if} expression.  For more about Lisp
7772 macros, see @ref{Macros, , Macros, elisp, The GNU Emacs Lisp Reference
7773 Manual}.  The C programming language also provides macros.  These are
7774 different, but also useful.  We will briefly look at C macros in
7775 @ref{Digression into C}.
7777 @need 1200
7778 If the string has content, then another conditional expression is
7779 executed.  This is an @code{if} with both a then-part and an else-part.
7781 @smallexample
7782 @group
7783 (if (eq last-command 'kill-region)
7784     (kill-append string (< end beg))
7785   (kill-new string)))
7786 @end group
7787 @end smallexample
7789 The then-part is evaluated if the previous command was another call to
7790 @code{kill-region}; if not, the else-part is evaluated.
7792 @code{last-command} is a variable that comes with Emacs that we have
7793 not seen before.  Normally, whenever a function is executed, Emacs
7794 sets the value of @code{last-command} to the previous command.
7796 @need 1200
7797 In this segment of the definition, the @code{if} expression checks
7798 whether the previous command was @code{kill-region}.  If it was,
7800 @smallexample
7801 (kill-append string (< end beg))
7802 @end smallexample
7804 @noindent
7805 concatenates a copy of the newly clipped text to the just previously
7806 clipped text in the kill ring.  (If the @w{@code{(< end beg))}}
7807 expression is true, @code{kill-append} prepends the string to the just
7808 previously clipped text.  For a detailed discussion, see
7809 @ref{kill-append function, , The @code{kill-append} function}.)
7811 If you then yank back the text, i.e., `paste' it, you get both
7812 pieces of text at once.  That way, if you delete two words in a row,
7813 and then yank them back, you get both words, in their proper order,
7814 with one yank.  (The @w{@code{(< end beg))}} expression makes sure the
7815 order is correct.)
7817 On the other hand, if the previous command is not @code{kill-region},
7818 then the @code{kill-new} function is called, which adds the text to
7819 the kill ring as the latest item, and sets the
7820 @code{kill-ring-yank-pointer} variable to point to it.
7822 @node Digression into C, defvar, kill-region, Cutting & Storing Text
7823 @comment  node-name,  next,  previous,  up
7824 @section Digression into C
7825 @findex delete-and-extract-region
7826 @cindex C, a digression into
7827 @cindex Digression into C
7829 The @code{zap-to-char} command uses the
7830 @code{delete-and-extract-region} function, which in turn uses two
7831 other functions, @code{copy-region-as-kill} and
7832 @code{del_range_1}.  The @code{copy-region-as-kill} function will be
7833 described in a following section; it puts a copy of the region in the
7834 kill ring so it can be yanked back.  (@xref{copy-region-as-kill, ,
7835 @code{copy-region-as-kill}}.)
7837 The @code{delete-and-extract-region} function removes the contents of
7838 a region and you cannot get them back.
7840 Unlike the other code discussed here, @code{delete-and-extract-region}
7841 is not written in Emacs Lisp; it is written in C and is one of the
7842 primitives of the GNU Emacs system.  Since it is very simple, I will
7843 digress briefly from Lisp and describe it here.
7845 @need 1500
7846 Like many of the other Emacs primitives,
7847 @code{delete-and-extract-region} is written as an instance of a C
7848 macro, a macro being a template for code.  The complete macro looks
7849 like this:
7851 @c /usr/local/src/emacs/src/editfns.c
7852 @smallexample
7853 @group
7854 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
7855        Sdelete_and_extract_region, 2, 2, 0,
7856   "Delete the text between START and END and return it.")
7857   (start, end)
7858      Lisp_Object start, end;
7860   validate_region (&start, &end);
7861   return del_range_1 (XINT (start), XINT (end), 1, 1);
7863 @end group
7864 @end smallexample
7866 Without going into the details of the macro writing process, let me
7867 point out that this macro starts with the word @code{DEFUN}.  The word
7868 @code{DEFUN} was chosen since the code serves the same purpose as
7869 @code{defun} does in Lisp.  The word @code{DEFUN} is followed by seven
7870 parts inside of parentheses:
7872 @itemize @bullet
7873 @item
7874 The first part is the name given to the function in Lisp,
7875 @code{delete-and-extract-region}.
7877 @item
7878 The second part is the name of the function in C,
7879 @code{Fdelete_and_extract_region}.  By convention, it starts with
7880 @samp{F}.  Since C does not use hyphens in names, underscores are used
7881 instead.
7883 @item
7884 The third part is the name for the C constant structure that records
7885 information on this function for internal use.  It is the name of the
7886 function in C but begins with an @samp{S} instead of an @samp{F}.
7888 @item
7889 The fourth and fifth parts specify the minimum and maximum number of
7890 arguments the function can have.  This function demands exactly 2
7891 arguments.
7893 @item
7894 The sixth part is nearly like the argument that follows the
7895 @code{interactive} declaration in a function written in Lisp: a letter
7896 followed, perhaps, by a prompt.  The only difference from the Lisp is
7897 when the macro is called with no arguments.  Then you write a @code{0}
7898 (which is a `null string'), as in this macro.
7900 If you were to specify arguments, you would place them between
7901 quotation marks.  The C macro for @code{goto-char} includes
7902 @code{"NGoto char: "} in this position to indicate that the function
7903 expects a raw prefix, in this case, a numerical location in a buffer,
7904 and provides a prompt.
7906 @item
7907 The seventh part is a documentation string, just like the one for a
7908 function written in Emacs Lisp, except that every newline must be
7909 written explicitly as @samp{\n} followed by a backslash and carriage
7910 return.
7912 @need 1000
7913 Thus, the first two lines of documentation for  @code{goto-char} are
7914 written like this:
7916 @smallexample
7917 @group
7918   "Set point to POSITION, a number or marker.\n\
7919 Beginning of buffer is position (point-min), end is (point-max).
7920 @end group
7921 @end smallexample
7922 @end itemize
7924 @need 1200
7925 In a C macro, the formal parameters come next, with a statement of
7926 what kind of object they are, followed by what might be called the `body'
7927 of the macro.  For @code{delete-and-extract-region} the `body'
7928 consists of the following two lines:
7930 @smallexample
7931 @group
7932 validate_region (&start, &end);
7933 return del_range_1 (XINT (start), XINT (end), 1, 1);
7934 @end group
7935 @end smallexample
7937 The first function, @code{validate_region} checks whether the values
7938 passed as the beginning and end of the region are the proper type and
7939 are within range.  The second function, @code{del_range_1}, actually
7940 deletes the text.
7942 @code{del_range_1} is a complex function we will not look into.  It
7943 updates the buffer and does other things.
7945 However, it is worth looking at the two arguments passed to
7946 @code{del_range}.  These are @w{@code{XINT (start)}} and @w{@code{XINT
7947 (end)}}.
7949 As far as the C language is concerned, @code{start} and @code{end} are
7950 two integers that mark the beginning and end of the region to be
7951 deleted@footnote{More precisely, and requiring more expert knowledge
7952 to understand, the two integers are of type `Lisp_Object', which can
7953 also be a C union instead of an integer type.}.
7955 In early versions of Emacs, these two numbers were thirty-two bits
7956 long, but the code is slowly being generalized to handle other
7957 lengths.  Three of the available bits are used to specify the type of
7958 information and a fourth bit is used for handling the computer's
7959 memory; the remaining bits are used as `content'.
7961 @samp{XINT} is a C macro that extracts the relevant number from the
7962 longer collection of bits; the four other bits are discarded.
7964 @need 800
7965 The command in @code{delete-and-extract-region} looks like this:
7967 @smallexample
7968 del_range_1 (XINT (start), XINT (end), 1, 1);
7969 @end smallexample
7971 @noindent
7972 It deletes the region between the beginning position, @code{start},
7973 and the ending position, @code{end}.
7975 From the point of view of the person writing Lisp, Emacs is all very
7976 simple; but hidden underneath is a great deal of complexity to make it
7977 all work.
7979 @node defvar, copy-region-as-kill, Digression into C, Cutting & Storing Text
7980 @comment  node-name,  next,  previous,  up
7981 @section Initializing a Variable with @code{defvar}
7982 @findex defvar
7983 @cindex Initializing a variable
7984 @cindex Variable initialization
7986 Unlike the @code{delete-and-extract-region} function, the
7987 @code{copy-region-as-kill} function is written in Emacs Lisp.  Two
7988 functions within it, @code{kill-append} and @code{kill-new}, copy a
7989 region in a buffer and save it in a variable called the
7990 @code{kill-ring}.  This section describes how the @code{kill-ring}
7991 variable is created and initialized using the @code{defvar} special
7992 form.
7994 (Again we note that the term @code{kill-ring} is a misnomer.  The text
7995 that is clipped out of the buffer can be brought back; it is not a ring
7996 of corpses, but a ring of resurrectable text.)
7998 In Emacs Lisp, a variable such as the @code{kill-ring} is created and
7999 given an initial value by using the @code{defvar} special form.  The
8000 name comes from ``define variable''.
8002 The @code{defvar} special form is similar to @code{setq} in that it sets
8003 the value of a variable.  It is unlike @code{setq} in two ways: first,
8004 it only sets the value of the variable if the variable does not already
8005 have a value.  If the variable already has a value, @code{defvar} does
8006 not override the existing value.  Second, @code{defvar} has a
8007 documentation string.
8009 (Another special form, @code{defcustom}, is designed for variables
8010 that people customize.  It has more features than @code{defvar}.
8011 (@xref{defcustom, , Setting Variables with @code{defcustom}}.)
8013 @menu
8014 * See variable current value::
8015 * defvar and asterisk::         An old-time convention.
8016 @end menu
8018 @node See variable current value, defvar and asterisk, defvar, defvar
8019 @ifnottex
8020 @unnumberedsubsec Seeing the Current Value of a Variable
8021 @end ifnottex
8023 You can see the current value of a variable, any variable, by using
8024 the @code{describe-variable} function, which is usually invoked by
8025 typing @kbd{C-h v}.  If you type @kbd{C-h v} and then @code{kill-ring}
8026 (followed by @key{RET}) when prompted, you will see what is in your
8027 current kill ring---this may be quite a lot!  Conversely, if you have
8028 been doing nothing this Emacs session except read this document, you
8029 may have nothing in it.  Also, you will see the documentation for
8030 @code{kill-ring}:
8032 @smallexample
8033 @group
8034 Documentation:
8035 List of killed text sequences.
8036 Since the kill ring is supposed to interact nicely with cut-and-paste
8037 facilities offered by window systems, use of this variable should
8038 @end group
8039 @group
8040 interact nicely with `interprogram-cut-function' and
8041 `interprogram-paste-function'.  The functions `kill-new',
8042 `kill-append', and `current-kill' are supposed to implement this
8043 interaction; you may want to use them instead of manipulating the kill
8044 ring directly.
8045 @end group
8046 @end smallexample
8048 @need 800
8049 The kill ring is defined by a @code{defvar} in the following way:
8051 @smallexample
8052 @group
8053 (defvar kill-ring nil
8054   "List of killed text sequences.
8055 @dots{}")
8056 @end group
8057 @end smallexample
8059 @noindent
8060 In this variable definition, the variable is given an initial value of
8061 @code{nil}, which makes sense, since if you have saved nothing, you want
8062 nothing back if you give a @code{yank} command.  The documentation
8063 string is written just like the documentation string of a @code{defun}.
8064 As with the documentation string of the @code{defun}, the first line of
8065 the documentation should be a complete sentence, since some commands,
8066 like @code{apropos}, print only the first line of documentation.
8067 Succeeding lines should not be indented; otherwise they look odd when
8068 you use @kbd{C-h v} (@code{describe-variable}).
8070 @node defvar and asterisk,  , See variable current value, defvar
8071 @subsection @code{defvar} and an asterisk
8072 @findex defvar @r{for a user customizable variable}
8073 @findex defvar @r{with an asterisk}
8075 In the past, Emacs used the @code{defvar} special form both for
8076 internal variables that you would not expect a user to change and for
8077 variables that you do expect a user to change.  Although you can still
8078 use @code{defvar} for user customizable variables, please use
8079 @code{defcustom} instead, since that special form provides a path into
8080 the Customization commands.  (@xref{defcustom, , Setting Variables
8081 with @code{defcustom}}.)
8083 When you specified a variable using the @code{defvar} special form,
8084 you could distinguish a readily settable variable from others by
8085 typing an asterisk, @samp{*}, in the first column of its documentation
8086 string.  For example:
8088 @smallexample
8089 @group
8090 (defvar shell-command-default-error-buffer nil
8091   "*Buffer name for `shell-command' @dots{} error output.
8092 @dots{} ")
8093 @end group
8094 @end smallexample
8096 @noindent
8097 This means that you could (and still can) use the @code{edit-options}
8098 command to change the value of
8099 @code{shell-command-default-error-buffer} temporarily.
8101 @findex edit-options
8102 However, options set using @code{edit-options} are set only for the
8103 duration of your editing session.  The new values are not saved
8104 between sessions.  Each time Emacs starts, it reads the original
8105 value, unless you change the value within your @file{.emacs} file,
8106 either by setting it manually or by using @code{customize}.
8107 @xref{Emacs Initialization, , Your @file{.emacs} File}.
8109 For me, the major use of the @code{edit-options} command is to suggest
8110 variables that I might want to set in my @file{.emacs} file.  I urge
8111 you to look through the list.  (@xref{Edit Options, , Editing Variable
8112 Values, emacs, The GNU Emacs Manual}.)
8114 @node copy-region-as-kill, cons & search-fwd Review, defvar, Cutting & Storing Text
8115 @comment  node-name,  next,  previous,  up
8116 @section @code{copy-region-as-kill}
8117 @findex copy-region-as-kill
8118 @findex nthcdr
8120 The @code{copy-region-as-kill} function copies a region of text from a
8121 buffer and (via either @code{kill-append} or @code{kill-new}) saves it
8122 in the @code{kill-ring}.
8124 If you call @code{copy-region-as-kill} immediately after a
8125 @code{kill-region} command, Emacs appends the newly copied text to the
8126 previously copied text.  This means that if you yank back the text, you
8127 get it all, from both this and the previous operation.  On the other
8128 hand, if some other command precedes the @code{copy-region-as-kill},
8129 the function copies the text into a separate entry in the kill ring.
8131 @menu
8132 * Complete copy-region-as-kill::  The complete function definition.
8133 * copy-region-as-kill body::    The body of @code{copy-region-as-kill}.
8134 @end menu
8136 @node Complete copy-region-as-kill, copy-region-as-kill body, copy-region-as-kill, copy-region-as-kill
8137 @ifnottex
8138 @unnumberedsubsec The complete @code{copy-region-as-kill} function definition
8139 @end ifnottex
8141 @need 1200
8142 Here is the complete text of the version 21 @code{copy-region-as-kill}
8143 function:
8145 @smallexample
8146 @group
8147 (defun copy-region-as-kill (beg end)
8148   "Save the region as if killed, but don't kill it.
8149 In Transient Mark mode, deactivate the mark.
8150 If `interprogram-cut-function' is non-nil, also save
8151 the text for a window system cut and paste."
8152   (interactive "r")
8153 @end group
8154 @group
8155   (if (eq last-command 'kill-region)
8156       (kill-append (buffer-substring beg end) (< end beg))
8157     (kill-new (buffer-substring beg end)))
8158 @end group
8159 @group
8160   (if transient-mark-mode
8161       (setq deactivate-mark t))
8162   nil)
8163 @end group
8164 @end smallexample
8166 @need 800
8167 As usual, this function can be divided into its component parts:
8169 @smallexample
8170 @group
8171 (defun copy-region-as-kill (@var{argument-list})
8172   "@var{documentation}@dots{}"
8173   (interactive "r")
8174   @var{body}@dots{})
8175 @end group
8176 @end smallexample
8178 The arguments are @code{beg} and @code{end} and the function is
8179 interactive with @code{"r"}, so the two arguments must refer to the
8180 beginning and end of the region.  If you have been reading though this
8181 document from the beginning, understanding these parts of a function is
8182 almost becoming routine.
8184 The documentation is somewhat confusing unless you remember that the
8185 word `kill' has a meaning different from its usual meaning.  The
8186 `Transient Mark' and @code{interprogram-cut-function} comments explain
8187 certain side-effects.
8189 After you once set a mark, a buffer always contains a region.  If you
8190 wish, you can use Transient Mark mode to highlight the region
8191 temporarily.  (No one wants to highlight the region all the time, so
8192 Transient Mark mode highlights it only at appropriate times.  Many
8193 people turn off Transient Mark mode, so the region is never
8194 highlighted.)
8196 Also, a windowing system allows you to copy, cut, and paste among
8197 different programs.  In the X windowing system, for example, the
8198 @code{interprogram-cut-function} function is @code{x-select-text},
8199 which works with the windowing system's equivalent of the Emacs kill
8200 ring.
8202 The body of the @code{copy-region-as-kill} function starts with an
8203 @code{if} clause.  What this clause does is distinguish between two
8204 different situations: whether or not this command is executed
8205 immediately after a previous @code{kill-region} command.  In the first
8206 case, the new region is appended to the previously copied text.
8207 Otherwise, it is inserted into the beginning of the kill ring as a
8208 separate piece of text from the previous piece.
8210 The last two lines of the function prevent the region from lighting up
8211 if Transient Mark mode is turned on.
8213 The body of @code{copy-region-as-kill} merits discussion in detail.
8215 @node copy-region-as-kill body,  , Complete copy-region-as-kill, copy-region-as-kill
8216 @comment  node-name,  next,  previous,  up
8217 @subsection The Body of @code{copy-region-as-kill}
8219 The @code{copy-region-as-kill} function works in much the same way as
8220 the @code{kill-region} function (@pxref{kill-region,
8221 ,@code{kill-region}}).  Both are written so that two or more kills in
8222 a row combine their text into a single entry.  If you yank back the
8223 text from the kill ring, you get it all in one piece.  Moreover, kills
8224 that kill forward from the current position of the cursor are added to
8225 the end of the previously copied text and commands that copy text
8226 backwards add it to the beginning of the previously copied text.  This
8227 way, the words in the text stay in the proper order.
8229 Like @code{kill-region}, the @code{copy-region-as-kill} function makes
8230 use of the @code{last-command} variable that keeps track of the
8231 previous Emacs command.
8233 @menu
8234 * last-command & this-command::
8235 * kill-append function::
8236 * kill-new function::
8237 @end menu
8239 @node last-command & this-command, kill-append function, copy-region-as-kill body, copy-region-as-kill body
8240 @ifnottex
8241 @unnumberedsubsubsec @code{last-command} and @code{this-command}
8242 @end ifnottex
8244 Normally, whenever a function is executed, Emacs sets the value of
8245 @code{this-command} to the function being executed (which in this case
8246 would be @code{copy-region-as-kill}).  At the same time, Emacs sets
8247 the value of @code{last-command} to the previous value of
8248 @code{this-command}.
8250 In the first part of the body of the @code{copy-region-as-kill}
8251 function, an @code{if} expression determines whether the value of
8252 @code{last-command} is @code{kill-region}.  If so, the then-part of
8253 the @code{if} expression is evaluated; it uses the @code{kill-append}
8254 function to concatenate the text copied at this call to the function
8255 with the text already in the first element (the @sc{car}) of the kill
8256 ring.  On the other hand, if the value of @code{last-command} is not
8257 @code{kill-region}, then the @code{copy-region-as-kill} function
8258 attaches a new element to the kill ring using the @code{kill-new}
8259 function.
8261 @need 1250
8262 The @code{if} expression reads as follows; it uses @code{eq}, which is
8263 a function we have not yet seen:
8265 @smallexample
8266 @group
8267   (if (eq last-command 'kill-region)
8268       ;; @r{then-part}
8269       (kill-append (buffer-substring beg end) (< end beg))
8270     ;; @r{else-part}
8271     (kill-new (buffer-substring beg end)))
8272 @end group
8273 @end smallexample
8275 @findex eq @r{(example of use)}
8276 @noindent
8277 The @code{eq} function tests whether its first argument is the same Lisp
8278 object as its second argument.  The @code{eq} function is similar to the
8279 @code{equal} function in that it is used to test for equality, but
8280 differs in that it determines whether two representations are actually
8281 the same object inside the computer, but with different names.
8282 @code{equal} determines whether the structure and contents of two
8283 expressions are the same.
8285 If the previous command was @code{kill-region}, then the Emacs Lisp
8286 interpreter calls the @code{kill-append} function
8288 @node kill-append function, kill-new function, last-command & this-command, copy-region-as-kill body
8289 @unnumberedsubsubsec The @code{kill-append} function
8290 @findex kill-append
8292 @need 800
8293 The @code{kill-append} function looks like this:
8295 @smallexample
8296 @group
8297 (defun kill-append (string before-p)
8298   "Append STRING to the end of the latest kill in the kill ring.
8299 If BEFORE-P is non-nil, prepend STRING to the kill.
8300 If `interprogram-cut-function' is set, pass the resulting kill to
8301 it."
8302   (kill-new (if before-p
8303                 (concat string (car kill-ring))
8304               (concat (car kill-ring) string))
8305             t))
8306 @end group
8307 @end smallexample
8309 @noindent
8310 The @code{kill-append} function is fairly straightforward.  It uses
8311 the @code{kill-new} function, which we will discuss in more detail in
8312 a moment.
8314 First, let us look at the conditional that is one of the two arguments
8315 to @code{kill-new}.  It uses @code{concat} to concatenate the new text
8316 to the @sc{car} of the kill ring.  Whether it prepends or appends the
8317 text depends on the results of an @code{if} expression:
8319 @smallexample
8320 @group
8321 (if before-p                            ; @r{if-part}
8322     (concat string (car kill-ring))     ; @r{then-part}
8323   (concat (car kill-ring) string))      ; @r{else-part}
8324 @end group
8325 @end smallexample
8327 @noindent
8328 If the region being killed is before the region that was killed in the
8329 last command, then it should be prepended before the material that was
8330 saved in the previous kill; and conversely, if the killed text follows
8331 what was just killed, it should be appended after the previous text.
8332 The @code{if} expression depends on the predicate @code{before-p} to
8333 decide whether the newly saved text should be put before or after the
8334 previously saved text.
8336 The symbol @code{before-p} is the name of one of the arguments to
8337 @code{kill-append}.  When the @code{kill-append} function is
8338 evaluated, it is bound to the value returned by evaluating the actual
8339 argument.  In this case, this is the expression @code{(< end beg)}.
8340 This expression does not directly determine whether the killed text in
8341 this command is located before or after the kill text of the last
8342 command; what is does is determine whether the value of the variable
8343 @code{end} is less than the value of the variable @code{beg}.  If it
8344 is, it means that the user is most likely heading towards the
8345 beginning of the buffer.  Also, the result of evaluating the predicate
8346 expression, @code{(< end beg)}, will be true and the text will be
8347 prepended before the previous text.  On the other hand, if the value of
8348 the variable @code{end} is greater than the value of the variable
8349 @code{beg}, the text will be appended after the previous text.
8351 @need 800
8352 When the newly saved text will be prepended, then the string with the new
8353 text will be concatenated before the old text:
8355 @smallexample
8356 (concat string (car kill-ring))
8357 @end smallexample
8359 @need 1200
8360 @noindent
8361 But if the text will be appended, it will be concatenated
8362 after the old text:
8364 @smallexample
8365 (concat (car kill-ring) string))
8366 @end smallexample
8368 To understand how this works, we first need to review the
8369 @code{concat} function.  The @code{concat} function links together or
8370 unites two strings of text.  The result is a string.  For example:
8372 @smallexample
8373 @group
8374 (concat "abc" "def")
8375      @result{} "abcdef"
8376 @end group
8378 @group
8379 (concat "new "
8380         (car '("first element" "second element")))
8381      @result{} "new first element"
8383 (concat (car
8384         '("first element" "second element")) " modified")
8385      @result{} "first element modified"
8386 @end group
8387 @end smallexample
8389 We can now make sense of @code{kill-append}: it modifies the contents
8390 of the kill ring.  The kill ring is a list, each element of which is
8391 saved text.  The @code{kill-append} function uses the @code{kill-new}
8392 function which in turn uses the @code{setcar} function.
8394 @node kill-new function,  , kill-append function, copy-region-as-kill body
8395 @unnumberedsubsubsec The @code{kill-new} function
8396 @findex kill-new
8398 @need 1200
8399 The @code{kill-new} function looks like this:
8401 @smallexample
8402 @group
8403 (defun kill-new (string &optional replace)
8404   "Make STRING the latest kill in the kill ring.
8405 Set the kill-ring-yank pointer to point to it.
8406 If `interprogram-cut-function' is non-nil, apply it to STRING.
8407 Optional second argument REPLACE non-nil means that STRING will replace
8408 the front of the kill ring, rather than being added to the list."
8409 @end group
8410 @group
8411   (and (fboundp 'menu-bar-update-yank-menu)
8412        (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8413 @end group
8414 @group
8415   (if (and replace kill-ring)
8416       (setcar kill-ring string)
8417     (setq kill-ring (cons string kill-ring))
8418     (if (> (length kill-ring) kill-ring-max)
8419         (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8420 @end group
8421 @group
8422   (setq kill-ring-yank-pointer kill-ring)
8423   (if interprogram-cut-function
8424       (funcall interprogram-cut-function string (not replace))))
8425 @end group
8426 @end smallexample
8428 As usual, we can look at this function in parts.
8430 @need 1200
8431 The first line of the documentation makes sense:
8433 @smallexample
8434 Make STRING the latest kill in the kill ring.
8435 @end smallexample
8437 @noindent
8438 Let's skip over the rest of the documentation for the moment.
8440 Also, let's skip over the first two lines of code, those involving
8441 @code{menu-bar-update-yank-menu}.  We will explain them below.
8443 @need 1200
8444 The critical lines are these:
8446 @smallexample
8447 @group
8448   (if (and replace kill-ring)
8449       ;; @r{then}
8450       (setcar kill-ring string)
8451 @end group
8452 @group
8453     ;; @r{else}
8454     (setq kill-ring (cons string kill-ring))
8455     (if (> (length kill-ring) kill-ring-max)
8456         ;; @r{avoid overly long kill ring}
8457         (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil)))
8458 @end group
8459 @group
8460   (setq kill-ring-yank-pointer kill-ring)
8461   (if interprogram-cut-function
8462       (funcall interprogram-cut-function string (not replace))))
8463 @end group
8464 @end smallexample
8466 The conditional test is @w{@code{(and replace kill-ring)}}.
8467 This will be true when two conditions are met:  the kill ring has
8468 something in it, and the @code{replace} variable is true.
8470 @need 1250
8471 The @code{kill-append} function sets @code{replace} to be true; then,
8472 when the kill ring has at least one item in it, the @code{setcar}
8473 expression is executed:
8475 @smallexample
8476 (setcar kill-ring string)
8477 @end smallexample
8479 The @code{setcar} function actually changes the first element of the
8480 @code{kill-ring} list to the value of @code{string}.  It replaces the
8481 first element.
8483 On the other hand, if the kill ring is empty, or replace is false, the
8484 else-part of the condition is executed:
8486 @smallexample
8487 @group
8488 (setq kill-ring (cons string kill-ring))
8489 (if (> (length kill-ring) kill-ring-max)
8490     (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8491 @end group
8492 @end smallexample
8494 @noindent
8495 This expression first constructs a new version of the kill ring by
8496 prepending @code{string} to the existing kill ring as a new element.
8497 Then it executes a second @code{if} clause.  This second @code{if}
8498 clause keeps the kill ring from growing too long.
8500 Let's look at these two expressions in order.
8502 The @code{setq} line of the else-part sets the new value of the kill
8503 ring to what results from adding the string being killed to the old kill
8504 ring.
8506 @need 800
8507 We can see how this works with an example:
8509 @smallexample
8510 (setq example-list '("here is a clause" "another clause"))
8511 @end smallexample
8513 @need 1200
8514 @noindent
8515 After evaluating this expression with @kbd{C-x C-e}, you can evaluate
8516 @code{example-list} and see what it returns:
8518 @smallexample
8519 @group
8520 example-list
8521      @result{} ("here is a clause" "another clause")
8522 @end group
8523 @end smallexample
8525 @need 1200
8526 @noindent
8527 Now, we can add a new element on to this list by evaluating the
8528 following expression:
8529 @findex cons, @r{example}
8531 @smallexample
8532 (setq example-list (cons "a third clause" example-list))
8533 @end smallexample
8535 @need 800
8536 @noindent
8537 When we evaluate @code{example-list}, we find its value is:
8539 @smallexample
8540 @group
8541 example-list
8542      @result{} ("a third clause" "here is a clause" "another clause")
8543 @end group
8544 @end smallexample
8546 @noindent
8547 Thus, the third clause was added to the list by @code{cons}.
8549 @need 1200
8550 This is exactly similar to what the @code{setq} and @code{cons} do in
8551 the function.  Here is the line again:
8553 @smallexample
8554 (setq kill-ring (cons string kill-ring))
8555 @end smallexample
8557 @need 1200
8558 Now for the second part of the @code{if} clause.  This expression
8559 keeps the kill ring from growing too long.  It looks like this:
8561 @smallexample
8562 @group
8563 (if (> (length kill-ring) kill-ring-max)
8564     (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
8565 @end group
8566 @end smallexample
8568 The code checks whether the length of the kill ring is greater than
8569 the maximum permitted length.  This is the value of
8570 @code{kill-ring-max} (which is 60, by default).  If the length of the
8571 kill ring is too long, then this code sets the last element of the
8572 kill ring to @code{nil}.  It does this by using two functions,
8573 @code{nthcdr} and @code{setcdr}.
8575 We looked at @code{setcdr} earlier (@pxref{setcdr, , @code{setcdr}}).
8576 It sets the @sc{cdr} of a list, just as @code{setcar} sets the
8577 @sc{car} of a list.  In this case, however, @code{setcdr} will not be
8578 setting the @sc{cdr} of the whole kill ring; the @code{nthcdr}
8579 function is used to cause it to set the @sc{cdr} of the next to last
8580 element of the kill ring---this means that since the @sc{cdr} of the
8581 next to last element is the last element of the kill ring, it will set
8582 the last element of the kill ring.
8584 @findex nthcdr, @r{example}
8585 The @code{nthcdr} function works by repeatedly taking the @sc{cdr} of a
8586 list---it takes the @sc{cdr} of the @sc{cdr} of the @sc{cdr}
8587 @dots{}  It does this @var{N} times and returns the results.
8589 @findex setcdr, @r{example}
8590 Thus, if we had a four element list that was supposed to be three
8591 elements long, we could set the @sc{cdr} of the next to last element
8592 to @code{nil}, and thereby shorten the list.
8594 You can see this by evaluating the following three expressions in turn.
8595 First set the value of @code{trees} to @code{(maple oak pine birch)},
8596 then set the @sc{cdr} of its second @sc{cdr} to @code{nil} and then
8597 find the value of @code{trees}:
8599 @smallexample
8600 @group
8601 (setq trees '(maple oak pine birch))
8602      @result{} (maple oak pine birch)
8603 @end group
8605 @group
8606 (setcdr (nthcdr 2 trees) nil)
8607      @result{} nil
8609 trees
8610      @result{} (maple oak pine)
8611 @end group
8612 @end smallexample
8614 @noindent
8615 (The value returned by the @code{setcdr} expression is @code{nil} since
8616 that is what the @sc{cdr} is set to.)
8618 To repeat, in @code{kill-new}, the @code{nthcdr} function takes the
8619 @sc{cdr} a number of times that is one less than the maximum permitted
8620 size of the kill ring and sets the @sc{cdr} of that element (which
8621 will be the rest of the elements in the kill ring) to @code{nil}.
8622 This prevents the kill ring from growing too long.
8624 @need 800
8625 The next to last expression in the @code{kill-new} function is
8627 @smallexample
8628 (setq kill-ring-yank-pointer kill-ring)
8629 @end smallexample
8631 The @code{kill-ring-yank-pointer} is a global variable that is set to be
8632 the @code{kill-ring}.
8634 Even though the @code{kill-ring-yank-pointer} is called a
8635 @samp{pointer}, it is a variable just like the kill ring.  However, the
8636 name has been chosen to help humans understand how the variable is used.
8637 The variable is used in functions such as @code{yank} and
8638 @code{yank-pop} (@pxref{Yanking, , Yanking Text Back}).
8640 @need 1200
8641 Now, to return to the first two lines in the body of the function:
8643 @smallexample
8644 @group
8645   (and (fboundp 'menu-bar-update-yank-menu)
8646        (menu-bar-update-yank-menu string (and replace (car kill-ring))))
8647 @end group
8648 @end smallexample
8650 @noindent
8651 This is an expression whose first element is the function @code{and}.
8653 @findex and, @r{introduced}
8654 The @code{and} special form evaluates each of its arguments until one of
8655 the arguments returns a value of @code{nil}, in which case the
8656 @code{and} expression returns @code{nil}; however, if none of the
8657 arguments returns a value of @code{nil}, the value resulting from
8658 evaluating the last argument is returned.  (Since such a value is not
8659 @code{nil}, it is considered true in Emacs Lisp.)  In other words, an
8660 @code{and} expression returns a true value only if all its arguments
8661 are true.
8662 @findex and
8664 In this case, the expression tests first to see whether
8665 @code{menu-bar-update-yank-menu} exists as a function, and if so,
8666 calls it.  The @code{fboundp} function returns true if the symbol it
8667 is testing has a function definition that `is not void'.  If the
8668 symbol's function definition were void, we would receive an error
8669 message, as we did when we created errors intentionally (@pxref{Making
8670 Errors, , Generate an Error Message}).
8672 @need 1200
8673 Essentially, the @code{and} is an @code{if} expression that reads like
8674 this:
8676 @smallexample
8677 @group
8678 if @var{the-menu-bar-function-exists}
8679   then @var{execute-it}
8680 @end group
8681 @end smallexample
8683 @code{menu-bar-update-yank-menu} is one of the functions that make it
8684 possible to use the `Select and Paste' menu in the Edit item of a menu
8685 bar; using a mouse, you can look at the various pieces of text you
8686 have saved and select one piece to paste.
8688 Finally, the last expression in the @code{kill-new} function adds the
8689 newly copied string to whatever facility exists for copying and
8690 pasting among different programs running in a windowing system.  In
8691 the X Windowing system, for example, the @code{x-select-text} function
8692 takes the string and stores it in memory operated by X.  You can paste
8693 the string in another program, such as an Xterm.
8695 @need 1200
8696 The expression looks like this:
8698 @smallexample
8699 @group
8700   (if interprogram-cut-function
8701       (funcall interprogram-cut-function string (not replace))))
8702 @end group
8703 @end smallexample
8705 If an @code{interprogram-cut-function} exists, then Emacs executes
8706 @code{funcall}, which in turn calls its first argument as a function
8707 and passes the remaining arguments to it.  (Incidentally, as far as I
8708 can see, this @code{if} expression could be replaced by an @code{and}
8709 expression similar to the one in the first part of the function.)
8711 We are not going to discuss windowing systems and other programs
8712 further, but merely note that this is a mechanism that enables GNU
8713 Emacs to work easily and well with other programs.
8715 This code for placing text in the kill ring, either concatenated with
8716 an existing element or as a new element, leads us to the code for
8717 bringing back text that has been cut out of the buffer---the yank
8718 commands.  However, before discussing the yank commands, it is better
8719 to learn how lists are implemented in a computer.  This will make
8720 clear such mysteries as the use of the term `pointer'.
8722 @node cons & search-fwd Review, search Exercises, copy-region-as-kill, Cutting & Storing Text
8723 @comment  node-name,  next,  previous,  up
8724 @section Review
8726 Here is a brief summary of some recently introduced functions.
8728 @table @code
8729 @item car
8730 @itemx cdr
8731 @code{car} returns the first element of a list; @code{cdr} returns the
8732 second and subsequent elements of a list.
8734 @need 1250
8735 For example:
8737 @smallexample
8738 @group
8739 (car '(1 2 3 4 5 6 7))
8740      @result{} 1
8741 (cdr '(1 2 3 4 5 6 7))
8742      @result{} (2 3 4 5 6 7)
8743 @end group
8744 @end smallexample
8746 @item cons
8747 @code{cons} constructs a list by prepending its first argument to its
8748 second argument.
8750 @need 1250
8751 For example:
8753 @smallexample
8754 @group
8755 (cons 1 '(2 3 4))
8756      @result{} (1 2 3 4)
8757 @end group
8758 @end smallexample
8760 @item nthcdr
8761 Return the result of taking @sc{cdr} `n' times on a list.
8762 @iftex
8764 @tex
8765 $n^{th}$
8766 @end tex
8767 @code{cdr}.
8768 @end iftex
8769 The `rest of the rest', as it were.
8771 @need 1250
8772 For example:
8774 @smallexample
8775 @group
8776 (nthcdr 3 '(1 2 3 4 5 6 7))
8777      @result{} (4 5 6 7)
8778 @end group
8779 @end smallexample
8781 @item setcar
8782 @itemx setcdr
8783 @code{setcar} changes the first element of a list; @code{setcdr}
8784 changes the second and subsequent elements of a list.
8786 @need 1250
8787 For example:
8789 @smallexample
8790 @group
8791 (setq triple '(1 2 3))
8793 (setcar triple '37)
8795 triple
8796      @result{} (37 2 3)
8798 (setcdr triple '("foo" "bar"))
8800 triple
8801      @result{} (37 "foo" "bar")
8802 @end group
8803 @end smallexample
8805 @item progn
8806 Evaluate each argument in sequence and then return the value of the
8807 last.
8809 @need 1250
8810 For example:
8812 @smallexample
8813 @group
8814 (progn 1 2 3 4)
8815      @result{} 4
8816 @end group
8817 @end smallexample
8819 @item save-restriction
8820 Record whatever narrowing is in effect in the current buffer, if any,
8821 and restore that narrowing after evaluating the arguments.
8823 @item search-forward
8824 Search for a string, and if the string is found, move point.
8826 @need 1250
8827 @noindent
8828 Takes four arguments:
8830 @enumerate
8831 @item
8832 The string to search for.
8834 @item
8835 Optionally, the limit of the search.
8837 @item
8838 Optionally, what to do if the search fails, return @code{nil} or an
8839 error message.
8841 @item
8842 Optionally, how many times to repeat the search; if negative, the
8843 search goes backwards.
8844 @end enumerate
8846 @item kill-region
8847 @itemx delete-region
8848 @itemx copy-region-as-kill
8850 @code{kill-region} cuts the text between point and mark from the
8851 buffer and stores that text in the kill ring, so you can get it back
8852 by yanking.
8854 @code{delete-and-extract-region} removes the text between point and
8855 mark from the buffer and throws it away.  You cannot get it back.
8857 @code{copy-region-as-kill} copies the text between point and mark into
8858 the kill ring, from which you can get it by yanking.  The function
8859 does not cut or remove the text from the buffer.
8860 @end table
8862 @need 1500
8863 @node search Exercises,  , cons & search-fwd Review, Cutting & Storing Text
8864 @section Searching Exercises
8866 @itemize @bullet
8867 @item
8868 Write an interactive function that searches for a string.  If the
8869 search finds the string, leave point after it and display a message
8870 that says ``Found!''.  (Do not use @code{search-forward} for the name
8871 of this function; if you do, you will overwrite the existing version of
8872 @code{search-forward} that comes with Emacs.  Use a name such as
8873 @code{test-search} instead.)
8875 @item
8876 Write a function that prints the third element of the kill ring in the
8877 echo area, if any; if the kill ring does not contain a third element,
8878 print an appropriate message.
8879 @end itemize
8881 @node List Implementation, Yanking, Cutting & Storing Text, Top
8882 @comment  node-name,  next,  previous,  up
8883 @chapter How Lists are Implemented
8884 @cindex Lists in a computer
8886 In Lisp, atoms are recorded in a straightforward fashion; if the
8887 implementation is not straightforward in practice, it is, nonetheless,
8888 straightforward in theory.  The atom @samp{rose}, for example, is
8889 recorded as the four contiguous letters @samp{r}, @samp{o}, @samp{s},
8890 @samp{e}.  A list, on the other hand, is kept differently.  The mechanism
8891 is equally simple, but it takes a moment to get used to the idea.  A
8892 list is kept using a series of pairs of pointers.  In the series, the
8893 first pointer in each pair points to an atom or to another list, and the
8894 second pointer in each pair points to the next pair, or to the symbol
8895 @code{nil}, which marks the end of the list.
8897 A pointer itself is quite simply the electronic address of what is
8898 pointed to.  Hence, a list is kept as a series of electronic addresses.
8900 @menu
8901 * Lists diagrammed::
8902 * Symbols as Chest::            Exploring a powerful metaphor.
8903 * List Exercise::
8904 @end menu
8906 @node Lists diagrammed, Symbols as Chest, List Implementation, List Implementation
8907 @ifnottex
8908 @unnumberedsec Lists diagrammed
8909 @end ifnottex
8911 For example, the list @code{(rose violet buttercup)} has three elements,
8912 @samp{rose}, @samp{violet}, and @samp{buttercup}.  In the computer, the
8913 electronic address of @samp{rose} is recorded in a segment of computer
8914 memory along with the address that gives the electronic address of where
8915 the atom @samp{violet} is located; and that address (the one that tells
8916 where @samp{violet} is located) is kept along with an address that tells
8917 where the address for the atom @samp{buttercup} is located.
8919 @need 1200
8920 This sounds more complicated than it is and is easier seen in a diagram:
8922 @c clear print-postscript-figures
8923 @c !!! cons-cell-diagram #1
8924 @ifnottex
8925 @smallexample
8926 @group
8927     ___ ___      ___ ___      ___ ___
8928    |___|___|--> |___|___|--> |___|___|--> nil
8929      |            |            |
8930      |            |            |
8931       --> rose     --> violet   --> buttercup
8932 @end group
8933 @end smallexample
8934 @end ifnottex
8935 @ifset print-postscript-figures
8936 @sp 1
8937 @tex
8938 @image{cons-1}
8939 %%%% old method of including an image
8940 % \input /usr/local/lib/tex/inputs/psfig.tex
8941 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-1.eps}}
8942 % \catcode`\@=0 %
8943 @end tex
8944 @sp 1
8945 @end ifset
8946 @ifclear print-postscript-figures
8947 @iftex
8948 @smallexample
8949 @group
8950     ___ ___      ___ ___      ___ ___
8951    |___|___|--> |___|___|--> |___|___|--> nil
8952      |            |            |
8953      |            |            |
8954       --> rose     --> violet   --> buttercup
8955 @end group
8956 @end smallexample
8957 @end iftex
8958 @end ifclear
8960 @noindent
8961 In the diagram, each box represents a word of computer memory that
8962 holds a Lisp object, usually in the form of a memory address.  The boxes,
8963 i.e.@: the addresses, are in pairs.  Each arrow points to what the address
8964 is the address of, either an atom or another pair of addresses.  The
8965 first box is the electronic address of @samp{rose} and the arrow points
8966 to @samp{rose}; the second box is the address of the next pair of boxes,
8967 the first part of which is the address of @samp{violet} and the second
8968 part of which is the address of the next pair.  The very last box
8969 points to the symbol @code{nil}, which marks the end of the list.
8971 @need 1200
8972 When a variable is set to a list with a function such as @code{setq},
8973 it stores the address of the first box in the variable.  Thus,
8974 evaluation of the expression
8976 @smallexample
8977 (setq bouquet '(rose violet buttercup))
8978 @end smallexample
8980 @need 1250
8981 @noindent
8982 creates a situation like this:
8984 @c cons-cell-diagram #2
8985 @ifnottex
8986 @smallexample
8987 @group
8988 bouquet
8989      |
8990      |     ___ ___      ___ ___      ___ ___
8991       --> |___|___|--> |___|___|--> |___|___|--> nil
8992             |            |            |
8993             |            |            |
8994              --> rose     --> violet   --> buttercup
8995 @end group
8996 @end smallexample
8997 @end ifnottex
8998 @ifset print-postscript-figures
8999 @sp 1
9000 @tex
9001 @image{cons-2}
9002 %%%% old method of including an image
9003 % \input /usr/local/lib/tex/inputs/psfig.tex
9004 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2.eps}}
9005 % \catcode`\@=0 %
9006 @end tex
9007 @sp 1
9008 @end ifset
9009 @ifclear print-postscript-figures
9010 @iftex
9011 @smallexample
9012 @group
9013 bouquet
9014      |
9015      |     ___ ___      ___ ___      ___ ___
9016       --> |___|___|--> |___|___|--> |___|___|--> nil
9017             |            |            |
9018             |            |            |
9019              --> rose     --> violet   --> buttercup
9020 @end group
9021 @end smallexample
9022 @end iftex
9023 @end ifclear
9025 @noindent
9026 In this example, the symbol @code{bouquet} holds the address of the first
9027 pair of boxes.
9029 @need 1200
9030 This same list can be illustrated in a different sort of box notation
9031 like this:
9033 @c cons-cell-diagram #2a
9034 @ifnottex
9035 @smallexample
9036 @group
9037 bouquet
9039  |    --------------       ---------------       ----------------
9040  |   | car   | cdr  |     | car    | cdr  |     | car     | cdr  |
9041   -->| rose  |   o------->| violet |   o------->| butter- |  nil |
9042      |       |      |     |        |      |     | cup     |      |
9043       --------------       ---------------       ----------------
9044 @end group
9045 @end smallexample
9046 @end ifnottex
9047 @ifset print-postscript-figures
9048 @sp 1
9049 @tex
9050 @image{cons-2a}
9051 %%%% old method of including an image
9052 % \input /usr/local/lib/tex/inputs/psfig.tex
9053 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-2a.eps}}
9054 % \catcode`\@=0 %
9055 @end tex
9056 @sp 1
9057 @end ifset
9058 @ifclear print-postscript-figures
9059 @iftex
9060 @smallexample
9061 @group
9062 bouquet
9064  |    --------------       ---------------       ----------------
9065  |   | car   | cdr  |     | car    | cdr  |     | car     | cdr  |
9066   -->| rose  |   o------->| violet |   o------->| butter- |  nil |
9067      |       |      |     |        |      |     | cup     |      |
9068       --------------       ---------------       ----------------
9069 @end group
9070 @end smallexample
9071 @end iftex
9072 @end ifclear
9074 (Symbols consist of more than pairs of addresses, but the structure of
9075 a symbol is made up of addresses.  Indeed, the symbol @code{bouquet}
9076 consists of a group of address-boxes, one of which is the address of
9077 the printed word @samp{bouquet}, a second of which is the address of a
9078 function definition attached to the symbol, if any, a third of which
9079 is the address of the first pair of address-boxes for the list
9080 @code{(rose violet buttercup)}, and so on.  Here we are showing that
9081 the symbol's third address-box points to the first pair of
9082 address-boxes for the list.)
9084 If a symbol is set to the @sc{cdr} of a list, the list itself is not
9085 changed; the symbol simply has an address further down the list.  (In
9086 the jargon, @sc{car} and @sc{cdr} are `non-destructive'.)  Thus,
9087 evaluation of the following expression
9089 @smallexample
9090 (setq flowers (cdr bouquet))
9091 @end smallexample
9093 @need 800
9094 @noindent
9095 produces this:
9097 @c cons-cell-diagram #3
9098 @ifnottex
9099 @sp 1
9100 @smallexample
9101 @group
9102 bouquet        flowers
9103   |              |
9104   |     ___ ___  |     ___ ___      ___ ___
9105    --> |   |   |  --> |   |   |    |   |   |
9106        |___|___|----> |___|___|--> |___|___|--> nil
9107          |              |            |
9108          |              |            |
9109           --> rose       --> violet   --> buttercup
9110 @end group
9111 @end smallexample
9112 @sp 1
9113 @end ifnottex
9114 @ifset print-postscript-figures
9115 @sp 1
9116 @tex
9117 @image{cons-3}
9118 %%%% old method of including an image
9119 % \input /usr/local/lib/tex/inputs/psfig.tex
9120 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-3.eps}}
9121 % \catcode`\@=0 %
9122 @end tex
9123 @sp 1
9124 @end ifset
9125 @ifclear print-postscript-figures
9126 @iftex
9127 @sp 1
9128 @smallexample
9129 @group
9130 bouquet        flowers
9131   |              |
9132   |     ___ ___  |     ___ ___      ___ ___
9133    --> |   |   |  --> |   |   |    |   |   |
9134        |___|___|----> |___|___|--> |___|___|--> nil
9135          |              |            |
9136          |              |            |
9137           --> rose       --> violet   --> buttercup
9138 @end group
9139 @end smallexample
9140 @sp 1
9141 @end iftex
9142 @end ifclear
9144 @noindent
9145 The value of @code{flowers} is @code{(violet buttercup)}, which is
9146 to say, the symbol @code{flowers} holds the address of the pair of
9147 address-boxes, the first of which holds the address of @code{violet},
9148 and the second of which holds the address of @code{buttercup}.
9150 A pair of address-boxes is called a @dfn{cons cell} or @dfn{dotted
9151 pair}.  @xref{List Type, , List Type , elisp, The GNU Emacs Lisp
9152 Reference Manual}, and @ref{Dotted Pair Notation, , Dotted Pair
9153 Notation, elisp, The GNU Emacs Lisp Reference Manual}, for more
9154 information about cons cells and dotted pairs.
9156 @need 1200
9157 The function @code{cons} adds a new pair of addresses to the front of
9158 a series of addresses like that shown above.  For example, evaluating
9159 the expression
9161 @smallexample
9162 (setq bouquet (cons 'lily bouquet))
9163 @end smallexample
9165 @need 1500
9166 @noindent
9167 produces:
9169 @c cons-cell-diagram #4
9170 @ifnottex
9171 @sp 1
9172 @smallexample
9173 @group
9174 bouquet                       flowers
9175   |                             |
9176   |     ___ ___        ___ ___  |     ___ ___       ___ ___
9177    --> |   |   |      |   |   |  --> |   |   |     |   |   |
9178        |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9179          |              |              |             |
9180          |              |              |             |
9181           --> lily      --> rose       --> violet    --> buttercup
9182 @end group
9183 @end smallexample
9184 @sp 1
9185 @end ifnottex
9186 @ifset print-postscript-figures
9187 @sp 1
9188 @tex
9189 @image{cons-4}
9190 %%%% old method of including an image
9191 % \input /usr/local/lib/tex/inputs/psfig.tex
9192 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-4.eps}}
9193 % \catcode`\@=0 %
9194 @end tex
9195 @sp 1
9196 @end ifset
9197 @ifclear print-postscript-figures
9198 @iftex
9199 @sp 1
9200 @smallexample
9201 @group
9202 bouquet                       flowers
9203   |                             |
9204   |     ___ ___        ___ ___  |     ___ ___       ___ ___
9205    --> |   |   |      |   |   |  --> |   |   |     |   |   |
9206        |___|___|----> |___|___|----> |___|___|---->|___|___|--> nil
9207          |              |              |             |
9208          |              |              |             |
9209           --> lily      --> rose       --> violet    --> buttercup
9210 @end group
9211 @end smallexample
9212 @sp 1
9213 @end iftex
9214 @end ifclear
9216 @need 1200
9217 @noindent
9218 However, this does not change the value of the symbol
9219 @code{flowers}, as you can see by evaluating the following,
9221 @smallexample
9222 (eq (cdr (cdr bouquet)) flowers)
9223 @end smallexample
9225 @noindent
9226 which returns @code{t} for true.
9228 Until it is reset, @code{flowers} still has the value
9229 @code{(violet buttercup)}; that is, it has the address of the cons
9230 cell whose first address is of @code{violet}.  Also, this does not
9231 alter any of the pre-existing cons cells; they are all still there.
9233 Thus, in Lisp, to get the @sc{cdr} of a list, you just get the address
9234 of the next cons cell in the series; to get the @sc{car} of a list,
9235 you get the address of the first element of the list; to @code{cons} a
9236 new element on a list, you add a new cons cell to the front of the list.
9237 That is all there is to it!  The underlying structure of Lisp is
9238 brilliantly simple!
9240 And what does the last address in a series of cons cells refer to?  It
9241 is the address of the empty list, of @code{nil}.
9243 In summary, when a Lisp variable is set to a value, it is provided with
9244 the address of the list to which the variable refers.
9246 @node Symbols as Chest, List Exercise, Lists diagrammed, List Implementation
9247 @section Symbols as a Chest of Drawers
9248 @cindex Symbols as a Chest of Drawers
9249 @cindex Chest of Drawers, metaphor for a symbol
9250 @cindex Drawers, Chest of, metaphor for a symbol
9252 In an earlier section, I suggested that you might imagine a symbol as
9253 being a chest of drawers.  The function definition is put in one
9254 drawer, the value in another, and so on.  What is put in the drawer
9255 holding the value can be changed without affecting the contents of the
9256 drawer holding the function definition, and vice-versa.
9258 Actually, what is put in each drawer is the address of the value or
9259 function definition.  It is as if you found an old chest in the attic,
9260 and in one of its drawers you found a map giving you directions to
9261 where the buried treasure lies.
9263 (In addition to its name, symbol definition, and variable value, a
9264 symbol has a `drawer' for a @dfn{property list} which can be used to
9265 record other information.  Property lists are not discussed here; see
9266 @ref{Property Lists, , Property Lists, elisp, The GNU Emacs Lisp
9267 Reference Manual}.)
9269 @need 1500
9270 Here is a fanciful representation:
9272 @c chest-of-drawers diagram
9273 @ifnottex
9274 @sp 1
9275 @smallexample
9276 @group
9277             Chest of Drawers            Contents of Drawers
9279             __   o0O0o   __
9280           /                 \
9281          ---------------------
9282         |    directions to    |            [map to]
9283         |     symbol name     |             bouquet
9284         |                     |
9285         +---------------------+
9286         |    directions to    |
9287         |  symbol definition  |             [none]
9288         |                     |
9289         +---------------------+
9290         |    directions to    |            [map to]
9291         |    variable value   |             (rose violet buttercup)
9292         |                     |
9293         +---------------------+
9294         |    directions to    |
9295         |    property list    |             [not described here]
9296         |                     |
9297         +---------------------+
9298         |/                   \|
9299 @end group
9300 @end smallexample
9301 @sp 1
9302 @end ifnottex
9303 @ifset print-postscript-figures
9304 @sp 1
9305 @tex
9306 @image{drawers}
9307 %%%% old method of including an image
9308 % \input /usr/local/lib/tex/inputs/psfig.tex
9309 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/drawers.eps}}
9310 % \catcode`\@=0 %
9311 @end tex
9312 @sp 1
9313 @end ifset
9314 @ifclear print-postscript-figures
9315 @iftex
9316 @sp 1
9317 @smallexample
9318 @group
9319             Chest of Drawers            Contents of Drawers
9321             __   o0O0o   __
9322           /                 \
9323          ---------------------
9324         |    directions to    |            [map to]
9325         |     symbol name     |             bouquet
9326         |                     |
9327         +---------------------+
9328         |    directions to    |
9329         |  symbol definition  |             [none]
9330         |                     |
9331         +---------------------+
9332         |    directions to    |            [map to]
9333         |    variable value   |             (rose violet buttercup)
9334         |                     |
9335         +---------------------+
9336         |    directions to    |
9337         |    property list    |             [not described here]
9338         |                     |
9339         +---------------------+
9340         |/                   \|
9341 @end group
9342 @end smallexample
9343 @sp 1
9344 @end iftex
9345 @end ifclear
9347 @node List Exercise,  , Symbols as Chest, List Implementation
9348 @section Exercise
9350 Set @code{flowers} to @code{violet} and @code{buttercup}.  Cons two
9351 more flowers on to this list and set this new list to
9352 @code{more-flowers}.  Set the @sc{car} of @code{flowers} to a fish.
9353 What does the @code{more-flowers} list now contain?
9355 @node Yanking, Loops & Recursion, List Implementation, Top
9356 @comment  node-name,  next,  previous,  up
9357 @chapter Yanking Text Back
9358 @findex yank
9359 @findex rotate-yank-pointer
9360 @cindex Text retrieval
9361 @cindex Retrieving text
9362 @cindex Pasting text
9364 Whenever you cut text out of a buffer with a `kill' command in GNU Emacs,
9365 you can bring it back with a `yank' command.  The text that is cut out of
9366 the buffer is put in the kill ring and the yank commands insert the
9367 appropriate contents of the kill ring back into a buffer (not necessarily
9368 the original buffer).
9370 A simple @kbd{C-y} (@code{yank}) command inserts the first item from
9371 the kill ring into the current buffer.  If the @kbd{C-y} command is
9372 followed immediately by @kbd{M-y}, the first element is replaced by
9373 the second element.  Successive @kbd{M-y} commands replace the second
9374 element with the third, fourth, or fifth element, and so on.  When the
9375 last element in the kill ring is reached, it is replaced by the first
9376 element and the cycle is repeated.  (Thus the kill ring is called a
9377 `ring' rather than just a `list'.  However, the actual data structure
9378 that holds the text is a list.
9379 @xref{Kill Ring, , Handling the Kill Ring}, for the details of how the
9380 list is handled as a ring.)
9382 @menu
9383 * Kill Ring Overview::          The kill ring is a list.
9384 * kill-ring-yank-pointer::      The @code{kill-ring-yank-pointer} variable.
9385 * yank nthcdr Exercises::
9386 @end menu
9388 @node Kill Ring Overview, kill-ring-yank-pointer, Yanking, Yanking
9389 @comment  node-name,  next,  previous,  up
9390 @section Kill Ring Overview
9391 @cindex Kill ring overview
9393 The kill ring is a list of textual strings.  This is what it looks like:
9395 @smallexample
9396 ("some text" "a different piece of text" "yet more text")
9397 @end smallexample
9399 If this were the contents of my kill ring and I pressed @kbd{C-y}, the
9400 string of characters saying @samp{some text} would be inserted in this
9401 buffer where my cursor is located.
9403 The @code{yank} command is also used for duplicating text by copying it.
9404 The copied text is not cut from the buffer, but a copy of it is put on the
9405 kill ring and is inserted by yanking it back.
9407 Three functions are used for bringing text back from the kill ring:
9408 @code{yank}, which is usually bound to @kbd{C-y}; @code{yank-pop},
9409 which is usually bound to @kbd{M-y}; and @code{rotate-yank-pointer},
9410 which is used by the two other functions.
9412 These functions refer to the kill ring through a variable called the
9413 @code{kill-ring-yank-pointer}.  Indeed, the insertion code for both the
9414 @code{yank} and @code{yank-pop} functions is:
9416 @smallexample
9417 (insert (car kill-ring-yank-pointer))
9418 @end smallexample
9420 To begin to understand how @code{yank} and @code{yank-pop} work, it is
9421 first necessary to look at the @code{kill-ring-yank-pointer} variable
9422 and the @code{rotate-yank-pointer} function.
9424 @node kill-ring-yank-pointer, yank nthcdr Exercises, Kill Ring Overview, Yanking
9425 @comment  node-name,  next,  previous,  up
9426 @section The @code{kill-ring-yank-pointer} Variable
9428 @code{kill-ring-yank-pointer} is a variable, just as @code{kill-ring} is
9429 a variable.  It points to something by being bound to the value of what
9430 it points to, like any other Lisp variable.
9432 @need 1000
9433 Thus, if the value of the kill ring is:
9435 @smallexample
9436 ("some text" "a different piece of text" "yet more text")
9437 @end smallexample
9439 @need 1250
9440 @noindent
9441 and the @code{kill-ring-yank-pointer} points to the second clause, the
9442 value of @code{kill-ring-yank-pointer} is:
9444 @smallexample
9445 ("a different piece of text" "yet more text")
9446 @end smallexample
9448 As explained in the previous chapter (@pxref{List Implementation}), the
9449 computer does not keep two different copies of the text being pointed to
9450 by both the @code{kill-ring} and the @code{kill-ring-yank-pointer}.  The
9451 words ``a different piece of text'' and ``yet more text'' are not
9452 duplicated.  Instead, the two Lisp variables point to the same pieces of
9453 text.  Here is a diagram:
9455 @c cons-cell-diagram #5
9456 @ifnottex
9457 @smallexample
9458 @group
9459 kill-ring     kill-ring-yank-pointer
9460     |               |
9461     |      ___ ___  |     ___ ___      ___ ___
9462      ---> |   |   |  --> |   |   |    |   |   |
9463           |___|___|----> |___|___|--> |___|___|--> nil
9464             |              |            |
9465             |              |            |
9466             |              |             --> "yet more text"
9467             |              |
9468             |               --> "a different piece of text
9469             |
9470              --> "some text"
9471 @end group
9472 @end smallexample
9473 @sp 1
9474 @end ifnottex
9475 @ifset print-postscript-figures
9476 @sp 1
9477 @tex
9478 @image{cons-5}
9479 %%%% old method of including an image
9480 % \input /usr/local/lib/tex/inputs/psfig.tex
9481 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/cons-5.eps}}
9482 % \catcode`\@=0 %
9483 @end tex
9484 @sp 1
9485 @end ifset
9486 @ifclear print-postscript-figures
9487 @iftex
9488 @smallexample
9489 @group
9490 kill-ring     kill-ring-yank-pointer
9491     |               |
9492     |      ___ ___  |     ___ ___      ___ ___
9493      ---> |   |   |  --> |   |   |    |   |   |
9494           |___|___|----> |___|___|--> |___|___|--> nil
9495             |              |            |
9496             |              |            |
9497             |              |             --> "yet more text"
9498             |              |
9499             |               --> "a different piece of text
9500             |
9501              --> "some text"
9502 @end group
9503 @end smallexample
9504 @sp 1
9505 @end iftex
9506 @end ifclear
9508 Both the variable @code{kill-ring} and the variable
9509 @code{kill-ring-yank-pointer} are pointers.  But the kill ring itself is
9510 usually described as if it were actually what it is composed of.  The
9511 @code{kill-ring} is spoken of as if it were the list rather than that it
9512 points to the list.  Conversely, the @code{kill-ring-yank-pointer} is
9513 spoken of as pointing to a list.
9515 These two ways of talking about the same thing sound confusing at first but
9516 make sense on reflection.  The kill ring is generally thought of as the
9517 complete structure of data that holds the information of what has recently
9518 been cut out of the Emacs buffers.  The @code{kill-ring-yank-pointer}
9519 on the other hand, serves to indicate---that is, to `point to'---that part
9520 of the kill ring of which the first element (the @sc{car}) will be
9521 inserted.
9523 The @code{rotate-yank-pointer} function changes the element in the
9524 kill ring to which the @code{kill-ring-yank-pointer} points; when the
9525 pointer is set to point to the next element beyond the end of the kill
9526 ring, it automatically sets it to point to the first element of the
9527 kill ring.  This is how the list is transformed into a ring.  The
9528 @code{rotate-yank-pointer} function itself is not difficult, but
9529 contains many details.  It and the much simpler @code{yank} and
9530 @code{yank-pop} functions are described in an appendix.
9531 @xref{Kill Ring, , Handling the Kill Ring}.
9533 @need 1500
9534 @node yank nthcdr Exercises,  , kill-ring-yank-pointer, Yanking
9535 @section Exercises with @code{yank} and @code{nthcdr}
9537 @itemize @bullet
9538 @item
9539 Using @kbd{C-h v} (@code{describe-variable}), look at the value of
9540 your kill ring.  Add several items to your kill ring; look at its
9541 value again.  Using @kbd{M-y} (@code{yank-pop)}, move all the way
9542 around the kill ring.  How many items were in your kill ring?  Find
9543 the value of @code{kill-ring-max}.  Was your kill ring full, or could
9544 you have kept more blocks of text within it?
9546 @item
9547 Using @code{nthcdr} and @code{car}, construct a series of expressions
9548 to return the first, second, third, and fourth elements of a list.
9549 @end itemize
9551 @node Loops & Recursion, Regexp Search, Yanking, Top
9552 @comment  node-name,  next,  previous,  up
9553 @chapter Loops and Recursion
9554 @cindex Loops and recursion
9555 @cindex Recursion and loops
9556 @cindex Repetition (loops)
9558 Emacs Lisp has two primary ways to cause an expression, or a series of
9559 expressions, to be evaluated repeatedly: one uses a @code{while}
9560 loop, and the other uses @dfn{recursion}.
9562 Repetition can be very valuable.  For example, to move forward four
9563 sentences, you need only write a program that will move forward one
9564 sentence and then repeat the process four times.  Since a computer does
9565 not get bored or tired, such repetitive action does not have the
9566 deleterious effects that excessive or the wrong kinds of repetition can
9567 have on humans.
9569 People mostly write Emacs Lisp functions using @code{while} loops and
9570 their kin; but you can use recursion, which provides a very powerful
9571 way to think about and then to solve problems@footnote{You can write
9572 recursive functions to be frugal or wasteful of mental or computer
9573 resources; as it happens, methods that people find easy---that are
9574 frugal of `mental resources'---sometimes use considerable computer
9575 resources.  Emacs was designed to run on machines that we now consider
9576 limited and its default settings are conservative.  You may want to
9577 increase the values of @code{max-specpdl-size} and
9578 @code{max-lisp-eval-depth}.  In my @file{.emacs} file, I set them to
9579 15 and 30 times their default value.}.
9581 @menu
9582 * while::                       Causing a stretch of code to repeat.
9583 * dolist dotimes::
9584 * Recursion::                   Causing a function to call itself.
9585 * Looping exercise::
9586 @end menu
9588 @node while, dolist dotimes, Loops & Recursion, Loops & Recursion
9589 @comment  node-name,  next,  previous,  up
9590 @section @code{while}
9591 @cindex Loops
9592 @findex while
9594 The @code{while} special form tests whether the value returned by
9595 evaluating its first argument is true or false.  This is similar to what
9596 the Lisp interpreter does with an @code{if}; what the interpreter does
9597 next, however, is different.
9599 In a @code{while} expression, if the value returned by evaluating the
9600 first argument is false, the Lisp interpreter skips the rest of the
9601 expression (the @dfn{body} of the expression) and does not evaluate it.
9602 However, if the value is true, the Lisp interpreter evaluates the body
9603 of the expression and then again tests whether the first argument to
9604 @code{while} is true or false.  If the value returned by evaluating the
9605 first argument is again true, the Lisp interpreter again evaluates the
9606 body of the expression.
9608 @need 1200
9609 The template for a @code{while} expression looks like this:
9611 @smallexample
9612 @group
9613 (while @var{true-or-false-test}
9614   @var{body}@dots{})
9615 @end group
9616 @end smallexample
9618 @menu
9619 * Looping with while::          Repeat so long as test returns true.
9620 * Loop Example::                A @code{while} loop that uses a list.
9621 * print-elements-of-list::      Uses @code{while}, @code{car}, @code{cdr}.
9622 * Incrementing Loop::           A loop with an incrementing counter.
9623 * Decrementing Loop::           A loop with a decrementing counter.
9624 @end menu
9626 @node Looping with while, Loop Example, while, while
9627 @ifnottex
9628 @unnumberedsubsec Looping with @code{while}
9629 @end ifnottex
9631 So long as the true-or-false-test of the @code{while} expression
9632 returns a true value when it is evaluated, the body is repeatedly
9633 evaluated.  This process is called a loop since the Lisp interpreter
9634 repeats the same thing again and again, like an airplane doing a loop.
9635 When the result of evaluating the true-or-false-test is false, the
9636 Lisp interpreter does not evaluate the rest of the @code{while}
9637 expression and `exits the loop'.
9639 Clearly, if the value returned by evaluating the first argument to
9640 @code{while} is always true, the body following will be evaluated
9641 again and again @dots{} and again @dots{} forever.  Conversely, if the
9642 value returned is never true, the expressions in the body will never
9643 be evaluated.  The craft of writing a @code{while} loop consists of
9644 choosing a mechanism such that the true-or-false-test returns true
9645 just the number of times that you want the subsequent expressions to
9646 be evaluated, and then have the test return false.
9648 The value returned by evaluating a @code{while} is the value of the
9649 true-or-false-test.  An interesting consequence of this is that a
9650 @code{while} loop that evaluates without error will return @code{nil}
9651 or false regardless of whether it has looped 1 or 100 times or none at
9652 all.  A @code{while} expression that evaluates successfully never
9653 returns a true value!  What this means is that @code{while} is always
9654 evaluated for its side effects, which is to say, the consequences of
9655 evaluating the expressions within the body of the @code{while} loop.
9656 This makes sense.  It is not the mere act of looping that is desired,
9657 but the consequences of what happens when the expressions in the loop
9658 are repeatedly evaluated.
9660 @node Loop Example, print-elements-of-list, Looping with while, while
9661 @comment  node-name,  next,  previous,  up
9662 @subsection A @code{while} Loop and a List
9664 A common way to control a @code{while} loop is to test whether a list
9665 has any elements.  If it does, the loop is repeated; but if it does not,
9666 the repetition is ended.  Since this is an important technique, we will
9667 create a short example to illustrate it.
9669 A simple way to test whether a list has elements is to evaluate the
9670 list: if it has no elements, it is an empty list and will return the
9671 empty list, @code{()}, which is a synonym for @code{nil} or false.  On
9672 the other hand, a list with elements will return those elements when it
9673 is evaluated.  Since Emacs Lisp considers as true any value that is not
9674 @code{nil}, a list that returns elements will test true in a
9675 @code{while} loop.
9677 @need 1200
9678 For example, you can set the variable @code{empty-list} to @code{nil} by
9679 evaluating the following @code{setq} expression:
9681 @smallexample
9682 (setq empty-list ())
9683 @end smallexample
9685 @noindent
9686 After evaluating the @code{setq} expression, you can evaluate the
9687 variable @code{empty-list} in the usual way, by placing the cursor after
9688 the symbol and typing @kbd{C-x C-e}; @code{nil} will appear in your
9689 echo area:
9691 @smallexample
9692 empty-list
9693 @end smallexample
9695 On the other hand, if you set a variable to be a list with elements, the
9696 list will appear when you evaluate the variable, as you can see by
9697 evaluating the following two expressions:
9699 @smallexample
9700 @group
9701 (setq animals '(gazelle giraffe lion tiger))
9703 animals
9704 @end group
9705 @end smallexample
9707 Thus, to create a @code{while} loop that tests whether there are any
9708 items in the list @code{animals}, the first part of the loop will be
9709 written like this:
9711 @smallexample
9712 @group
9713 (while animals
9714        @dots{}
9715 @end group
9716 @end smallexample
9718 @noindent
9719 When the @code{while} tests its first argument, the variable
9720 @code{animals} is evaluated.  It returns a list.  So long as the list
9721 has elements, the @code{while} considers the results of the test to be
9722 true; but when the list is empty, it considers the results of the test
9723 to be false.
9725 To prevent the @code{while} loop from running forever, some mechanism
9726 needs to be provided to empty the list eventually.  An oft-used
9727 technique is to have one of the subsequent forms in the @code{while}
9728 expression set the value of the list to be the @sc{cdr} of the list.
9729 Each time the @code{cdr} function is evaluated, the list will be made
9730 shorter, until eventually only the empty list will be left.  At this
9731 point, the test of the @code{while} loop will return false, and the
9732 arguments to the @code{while} will no longer be evaluated.
9734 For example, the list of animals bound to the variable @code{animals}
9735 can be set to be the @sc{cdr} of the original list with the
9736 following expression:
9738 @smallexample
9739 (setq animals (cdr animals))
9740 @end smallexample
9742 @noindent
9743 If you have evaluated the previous expressions and then evaluate this
9744 expression, you will see @code{(giraffe lion tiger)} appear in the echo
9745 area.  If you evaluate the expression again, @code{(lion tiger)} will
9746 appear in the echo area.  If you evaluate it again and yet again,
9747 @code{(tiger)} appears and then the empty list, shown by @code{nil}.
9749 A template for a @code{while} loop that uses the @code{cdr} function
9750 repeatedly to cause the true-or-false-test eventually to test false
9751 looks like this:
9753 @smallexample
9754 @group
9755 (while @var{test-whether-list-is-empty}
9756   @var{body}@dots{}
9757   @var{set-list-to-cdr-of-list})
9758 @end group
9759 @end smallexample
9761 This test and use of @code{cdr} can be put together in a function that
9762 goes through a list and prints each element of the list on a line of its
9763 own.
9765 @node print-elements-of-list, Incrementing Loop, Loop Example, while
9766 @subsection An Example: @code{print-elements-of-list}
9767 @findex print-elements-of-list
9769 The @code{print-elements-of-list} function illustrates a @code{while}
9770 loop with a list.
9772 @cindex @file{*scratch*} buffer
9773 The function requires several lines for its output.  If you are
9774 reading this in Emacs 21 or a later version, you can evaluate the
9775 following expression inside of Info, as usual.
9777 If you are using an earlier version of Emacs, you need to copy the
9778 necessary expressions to your @file{*scratch*} buffer and evaluate
9779 them there.  This is because the echo area had only one line in the
9780 earlier versions.
9782 You can copy the expressions by marking the beginning of the region
9783 with @kbd{C-@key{SPC}} (@code{set-mark-command}), moving the cursor to
9784 the end of the region and then copying the region using @kbd{M-w}
9785 (@code{copy-region-as-kill}).  In the @file{*scratch*} buffer, you can
9786 yank the expressions back by typing @kbd{C-y} (@code{yank}).
9788 After you have copied the expressions to the @file{*scratch*} buffer,
9789 evaluate each expression in turn.  Be sure to evaluate the last
9790 expression, @code{(print-elements-of-list animals)}, by typing
9791 @kbd{C-u C-x C-e}, that is, by giving an argument to
9792 @code{eval-last-sexp}.  This will cause the result of the evaluation
9793 to be printed in the @file{*scratch*} buffer instead of being printed
9794 in the echo area.  (Otherwise you will see something like this in your
9795 echo area: @code{^Jgazelle^J^Jgiraffe^J^Jlion^J^Jtiger^Jnil}, in which
9796 each @samp{^J} stands for a `newline'.)
9798 @need 1500
9799 If you are using Emacs 21 or later, you can evaluate these expressions
9800 directly in the Info buffer, and the echo area will grow to show the
9801 results.
9803 @smallexample
9804 @group
9805 (setq animals '(gazelle giraffe lion tiger))
9807 (defun print-elements-of-list (list)
9808   "Print each element of LIST on a line of its own."
9809   (while list
9810     (print (car list))
9811     (setq list (cdr list))))
9813 (print-elements-of-list animals)
9814 @end group
9815 @end smallexample
9817 @need 1200
9818 @noindent
9819 When you evaluate the three expressions in sequence, you will see
9820 this:
9822 @smallexample
9823 @group
9824 gazelle
9826 giraffe
9828 lion
9830 tiger
9832 @end group
9833 @end smallexample
9835 Each element of the list is printed on a line of its own (that is what
9836 the function @code{print} does) and then the value returned by the
9837 function is printed.  Since the last expression in the function is the
9838 @code{while} loop, and since @code{while} loops always return
9839 @code{nil}, a @code{nil} is printed after the last element of the list.
9841 @node Incrementing Loop, Decrementing Loop, print-elements-of-list, while
9842 @comment  node-name,  next,  previous,  up
9843 @subsection A Loop with an Incrementing Counter
9845 A loop is not useful unless it stops when it ought.  Besides
9846 controlling a loop with a list, a common way of stopping a loop is to
9847 write the first argument as a test that returns false when the correct
9848 number of repetitions are complete.  This means that the loop must
9849 have a counter---an expression that counts how many times the loop
9850 repeats itself.
9852 The test can be an expression such as @code{(< count desired-number)}
9853 which returns @code{t} for true if the value of @code{count} is less
9854 than the @code{desired-number} of repetitions and @code{nil} for false if
9855 the value of @code{count} is equal to or is greater than the
9856 @code{desired-number}.  The expression that increments the count can be
9857 a simple @code{setq} such as @code{(setq count (1+ count))}, where
9858 @code{1+} is a built-in function in Emacs Lisp that adds 1 to its
9859 argument.  (The expression @w{@code{(1+ count)}} has the same result as
9860 @w{@code{(+ count 1)}}, but is easier for a human to read.)
9862 @need 1250
9863 The template for a @code{while} loop controlled by an incrementing
9864 counter looks like this:
9866 @smallexample
9867 @group
9868 @var{set-count-to-initial-value}
9869 (while (< count desired-number)         ; @r{true-or-false-test}
9870   @var{body}@dots{}
9871   (setq count (1+ count)))              ; @r{incrementer}
9872 @end group
9873 @end smallexample
9875 @noindent
9876 Note that you need to set the initial value of @code{count}; usually it
9877 is set to 1.
9879 @menu
9880 * Incrementing Example::        Counting pebbles in a triangle.
9881 * Inc Example parts::           The parts of the function definition.
9882 * Inc Example altogether::      Putting the function definition together.
9883 @end menu
9885 @node Incrementing Example, Inc Example parts, Incrementing Loop, Incrementing Loop
9886 @unnumberedsubsubsec  Example with incrementing counter
9888 Suppose you are playing on the beach and decide to make a triangle of
9889 pebbles, putting one pebble in the first row, two in the second row,
9890 three in the third row and so on, like this:
9892 @sp 1
9893 @c pebble diagram
9894 @ifnottex
9895 @smallexample
9896 @group
9897                *
9898               * *
9899              * * *
9900             * * * *
9901 @end group
9902 @end smallexample
9903 @end ifnottex
9904 @iftex
9905 @smallexample
9906 @group
9907                @bullet{}
9908               @bullet{} @bullet{}
9909              @bullet{} @bullet{} @bullet{}
9910             @bullet{} @bullet{} @bullet{} @bullet{}
9911 @end group
9912 @end smallexample
9913 @end iftex
9914 @sp 1
9916 @noindent
9917 (About 2500 years ago, Pythagoras and others developed the beginnings of
9918 number theory by considering questions such as this.)
9920 Suppose you want to know how many pebbles you will need to make a
9921 triangle with 7 rows?
9923 Clearly, what you need to do is add up the numbers from 1 to 7.  There
9924 are two ways to do this; start with the smallest number, one, and add up
9925 the list in sequence, 1, 2, 3, 4 and so on; or start with the largest
9926 number and add the list going down: 7, 6, 5, 4 and so on.  Because both
9927 mechanisms illustrate common ways of writing @code{while} loops, we will
9928 create two examples, one counting up and the other counting down.  In
9929 this first example, we will start with 1 and add 2, 3, 4 and so on.
9931 If you are just adding up a short list of numbers, the easiest way to do
9932 it is to add up all the numbers at once.  However, if you do not know
9933 ahead of time how many numbers your list will have, or if you want to be
9934 prepared for a very long list, then you need to design your addition so
9935 that what you do is repeat a simple process many times instead of doing
9936 a more complex process once.
9938 For example, instead of adding up all the pebbles all at once, what you
9939 can do is add the number of pebbles in the first row, 1, to the number
9940 in the second row, 2, and then add the total of those two rows to the
9941 third row, 3.  Then you can add the number in the fourth row, 4, to the
9942 total of the first three rows; and so on.
9944 The critical characteristic of the process is that each repetitive
9945 action is simple.  In this case, at each step we add only two numbers,
9946 the number of pebbles in the row and the total already found.  This
9947 process of adding two numbers is repeated again and again until the last
9948 row has been added to the total of all the preceding rows.  In a more
9949 complex loop the repetitive action might not be so simple, but it will
9950 be simpler than doing everything all at once.
9952 @node Inc Example parts, Inc Example altogether, Incrementing Example, Incrementing Loop
9953 @unnumberedsubsubsec The parts of the function definition
9955 The preceding analysis gives us the bones of our function definition:
9956 first, we will need a variable that we can call @code{total} that will
9957 be the total number of pebbles.  This will be the value returned by
9958 the function.
9960 Second, we know that the function will require an argument: this
9961 argument will be the total number of rows in the triangle.  It can be
9962 called @code{number-of-rows}.
9964 Finally, we need a variable to use as a counter.  We could call this
9965 variable @code{counter}, but a better name is @code{row-number}.
9966 That is because what the counter does is count rows, and a program
9967 should be written to be as understandable as possible.
9969 When the Lisp interpreter first starts evaluating the expressions in the
9970 function, the value of @code{total} should be set to zero, since we have
9971 not added anything to it.  Then the function should add the number of
9972 pebbles in the first row to the total, and then add the number of
9973 pebbles in the second to the total, and then add the number of
9974 pebbles in the third row to the total, and so on, until there are no
9975 more rows left to add.
9977 Both @code{total} and @code{row-number} are used only inside the
9978 function, so they can be declared as local variables with @code{let}
9979 and given initial values.  Clearly, the initial value for @code{total}
9980 should be 0.  The initial value of @code{row-number} should be 1,
9981 since we start with the first row.  This means that the @code{let}
9982 statement will look like this:
9984 @smallexample
9985 @group
9986   (let ((total 0)
9987         (row-number 1))
9988     @var{body}@dots{})
9989 @end group
9990 @end smallexample
9992 After the internal variables are declared and bound to their initial
9993 values, we can begin the @code{while} loop.  The expression that serves
9994 as the test should return a value of @code{t} for true so long as the
9995 @code{row-number} is less than or equal to the @code{number-of-rows}.
9996 (If the expression tests true only so long as the row number is less
9997 than the number of rows in the triangle, the last row will never be
9998 added to the total; hence the row number has to be either less than or
9999 equal to the number of rows.)
10001 @need 1500
10002 @findex <= @r{(less than or equal)}
10003 Lisp provides the @code{<=} function that returns true if the value of
10004 its first argument is less than or equal to the value of its second
10005 argument and false otherwise.  So the expression that the @code{while}
10006 will evaluate as its test should look like this:
10008 @smallexample
10009 (<= row-number number-of-rows)
10010 @end smallexample
10012 The total number of pebbles can be found by repeatedly adding the number
10013 of pebbles in a row to the total already found.  Since the number of
10014 pebbles in the row is equal to the row number, the total can be found by
10015 adding the row number to the total.  (Clearly, in a more complex
10016 situation, the number of pebbles in the row might be related to the row
10017 number in a more complicated way; if this were the case, the row number
10018 would be replaced by the appropriate expression.)
10020 @smallexample
10021 (setq total (+ total row-number))
10022 @end smallexample
10024 @noindent
10025 What this does is set the new value of @code{total} to be equal to the
10026 sum of adding the number of pebbles in the row to the previous total.
10028 After setting the value of @code{total}, the conditions need to be
10029 established for the next repetition of the loop, if there is one.  This
10030 is done by incrementing the value of the @code{row-number} variable,
10031 which serves as a counter.  After the @code{row-number} variable has
10032 been incremented, the true-or-false-test at the beginning of the
10033 @code{while} loop tests whether its value is still less than or equal to
10034 the value of the @code{number-of-rows} and if it is, adds the new value
10035 of the @code{row-number} variable to the @code{total} of the previous
10036 repetition of the loop.
10038 @need 1200
10039 The built-in Emacs Lisp function @code{1+} adds 1 to a number, so the
10040 @code{row-number} variable can be incremented with this expression:
10042 @smallexample
10043 (setq row-number (1+ row-number))
10044 @end smallexample
10046 @node Inc Example altogether,  , Inc Example parts, Incrementing Loop
10047 @unnumberedsubsubsec Putting the function definition together
10049 We have created the parts for the function definition; now we need to
10050 put them together.
10052 @need 800
10053 First, the contents of the @code{while} expression:
10055 @smallexample
10056 @group
10057 (while (<= row-number number-of-rows)   ; @r{true-or-false-test}
10058   (setq total (+ total row-number))
10059   (setq row-number (1+ row-number)))    ; @r{incrementer}
10060 @end group
10061 @end smallexample
10063 Along with the @code{let} expression varlist, this very nearly
10064 completes the body of the function definition.  However, it requires
10065 one final element, the need for which is somewhat subtle.
10067 The final touch is to place the variable @code{total} on a line by
10068 itself after the @code{while} expression.  Otherwise, the value returned
10069 by the whole function is the value of the last expression that is
10070 evaluated in the body of the @code{let}, and this is the value
10071 returned by the @code{while}, which is always @code{nil}.
10073 This may not be evident at first sight.  It almost looks as if the
10074 incrementing expression is the last expression of the whole function.
10075 But that expression is part of the body of the @code{while}; it is the
10076 last element of the list that starts with the symbol @code{while}.
10077 Moreover, the whole of the @code{while} loop is a list within the body
10078 of the @code{let}.
10080 @need 1250
10081 In outline, the function will look like this:
10083 @smallexample
10084 @group
10085 (defun @var{name-of-function} (@var{argument-list})
10086   "@var{documentation}@dots{}"
10087   (let (@var{varlist})
10088     (while (@var{true-or-false-test})
10089       @var{body-of-while}@dots{} )
10090     @dots{} )                     ; @r{Need final expression here.}
10091 @end group
10092 @end smallexample
10094 The result of evaluating the @code{let} is what is going to be returned
10095 by the @code{defun} since the @code{let} is not embedded within any
10096 containing list, except for the @code{defun} as a whole.  However, if
10097 the @code{while} is the last element of the @code{let} expression, the
10098 function will always return @code{nil}.  This is not what we want!
10099 Instead, what we want is the value of the variable @code{total}.  This
10100 is returned by simply placing the symbol as the last element of the list
10101 starting with @code{let}.  It gets evaluated after the preceding
10102 elements of the list are evaluated, which means it gets evaluated after
10103 it has been assigned the correct value for the total.
10105 It may be easier to see this by printing the list starting with
10106 @code{let} all on one line.  This format makes it evident that the
10107 @var{varlist} and @code{while} expressions are the second and third
10108 elements of the list starting with @code{let}, and the @code{total} is
10109 the last element:
10111 @smallexample
10112 @group
10113 (let (@var{varlist}) (while (@var{true-or-false-test}) @var{body-of-while}@dots{} ) total)
10114 @end group
10115 @end smallexample
10117 @need 1200
10118 Putting everything together, the @code{triangle} function definition
10119 looks like this:
10121 @smallexample
10122 @group
10123 (defun triangle (number-of-rows)    ; @r{Version with}
10124                                     ; @r{  incrementing counter.}
10125   "Add up the number of pebbles in a triangle.
10126 The first row has one pebble, the second row two pebbles,
10127 the third row three pebbles, and so on.
10128 The argument is NUMBER-OF-ROWS."
10129 @end group
10130 @group
10131   (let ((total 0)
10132         (row-number 1))
10133     (while (<= row-number number-of-rows)
10134       (setq total (+ total row-number))
10135       (setq row-number (1+ row-number)))
10136     total))
10137 @end group
10138 @end smallexample
10140 @need 1200
10141 After you have installed @code{triangle} by evaluating the function, you
10142 can try it out.  Here are two examples:
10144 @smallexample
10145 @group
10146 (triangle 4)
10148 (triangle 7)
10149 @end group
10150 @end smallexample
10152 @noindent
10153 The sum of the first four numbers is 10 and the sum of the first seven
10154 numbers is 28.
10156 @node Decrementing Loop,  , Incrementing Loop, while
10157 @comment  node-name,  next,  previous,  up
10158 @subsection Loop with a Decrementing Counter
10160 Another common way to write a @code{while} loop is to write the test
10161 so that it determines whether a counter is greater than zero.  So long
10162 as the counter is greater than zero, the loop is repeated.  But when
10163 the counter is equal to or less than zero, the loop is stopped.  For
10164 this to work, the counter has to start out greater than zero and then
10165 be made smaller and smaller by a form that is evaluated
10166 repeatedly.
10168 The test will be an expression such as @code{(> counter 0)} which
10169 returns @code{t} for true if the value of @code{counter} is greater
10170 than zero, and @code{nil} for false if the value of @code{counter} is
10171 equal to or less than zero.  The expression that makes the number
10172 smaller and smaller can be a simple @code{setq} such as @code{(setq
10173 counter (1- counter))}, where @code{1-} is a built-in function in
10174 Emacs Lisp that subtracts 1 from its argument.
10176 @need 1250
10177 The template for a decrementing @code{while} loop looks like this:
10179 @smallexample
10180 @group
10181 (while (> counter 0)                    ; @r{true-or-false-test}
10182   @var{body}@dots{}
10183   (setq counter (1- counter)))          ; @r{decrementer}
10184 @end group
10185 @end smallexample
10187 @menu
10188 * Decrementing Example::        More pebbles on the beach.
10189 * Dec Example parts::           The parts of the function definition.
10190 * Dec Example altogether::      Putting the function definition together.
10191 @end menu
10193 @node Decrementing Example, Dec Example parts, Decrementing Loop, Decrementing Loop
10194 @unnumberedsubsubsec Example with decrementing counter
10196 To illustrate a loop with a decrementing counter, we will rewrite the
10197 @code{triangle} function so the counter decreases to zero.
10199 This is the reverse of the earlier version of the function.  In this
10200 case, to find out how many pebbles are needed to make a triangle with
10201 3 rows, add the number of pebbles in the third row, 3, to the number
10202 in the preceding row, 2, and then add the total of those two rows to
10203 the row that precedes them, which is 1.
10205 Likewise, to find the number of pebbles in a triangle with 7 rows, add
10206 the number of pebbles in the seventh row, 7, to the number in the
10207 preceding row, which is 6, and then add the total of those two rows to
10208 the row that precedes them, which is 5, and so on.  As in the previous
10209 example, each addition only involves adding two numbers, the total of
10210 the rows already added up and the number of pebbles in the row that is
10211 being added to the total.  This process of adding two numbers is
10212 repeated again and again until there are no more pebbles to add.
10214 We know how many pebbles to start with: the number of pebbles in the
10215 last row is equal to the number of rows.  If the triangle has seven
10216 rows, the number of pebbles in the last row is 7.  Likewise, we know how
10217 many pebbles are in the preceding row: it is one less than the number in
10218 the row.
10220 @node Dec Example parts, Dec Example altogether, Decrementing Example, Decrementing Loop
10221 @unnumberedsubsubsec The parts of the function definition
10223 We start with three variables: the total number of rows in the
10224 triangle; the number of pebbles in a row; and the total number of
10225 pebbles, which is what we want to calculate.  These variables can be
10226 named @code{number-of-rows}, @code{number-of-pebbles-in-row}, and
10227 @code{total}, respectively.
10229 Both @code{total} and @code{number-of-pebbles-in-row} are used only
10230 inside the function and are declared with @code{let}.  The initial
10231 value of @code{total} should, of course, be zero.  However, the
10232 initial value of @code{number-of-pebbles-in-row} should be equal to
10233 the number of rows in the triangle, since the addition will start with
10234 the longest row.
10236 @need 1250
10237 This means that the beginning of the @code{let} expression will look
10238 like this:
10240 @smallexample
10241 @group
10242 (let ((total 0)
10243       (number-of-pebbles-in-row number-of-rows))
10244   @var{body}@dots{})
10245 @end group
10246 @end smallexample
10248 The total number of pebbles can be found by repeatedly adding the number
10249 of pebbles in a row to the total already found, that is, by repeatedly
10250 evaluating the following expression:
10252 @smallexample
10253 (setq total (+ total number-of-pebbles-in-row))
10254 @end smallexample
10256 @noindent
10257 After the @code{number-of-pebbles-in-row} is added to the @code{total},
10258 the @code{number-of-pebbles-in-row} should be decremented by one, since
10259 the next time the loop repeats, the preceding row will be
10260 added to the total.
10262 The number of pebbles in a preceding row is one less than the number of
10263 pebbles in a row, so the built-in Emacs Lisp function @code{1-} can be
10264 used to compute the number of pebbles in the preceding row.  This can be
10265 done with the following expression:
10267 @smallexample
10268 @group
10269 (setq number-of-pebbles-in-row
10270       (1- number-of-pebbles-in-row))
10271 @end group
10272 @end smallexample
10274 Finally, we know that the @code{while} loop should stop making repeated
10275 additions when there are no pebbles in a row.  So the test for
10276 the @code{while} loop is simply:
10278 @smallexample
10279 (while (> number-of-pebbles-in-row 0)
10280 @end smallexample
10282 @node Dec Example altogether,  , Dec Example parts, Decrementing Loop
10283 @unnumberedsubsubsec Putting the function definition together
10285 We can put these expressions together to create a function definition
10286 that works.  However, on examination, we find that one of the local
10287 variables is unneeded!
10289 @need 1250
10290 The function definition looks like this:
10292 @smallexample
10293 @group
10294 ;;; @r{First subtractive version.}
10295 (defun triangle (number-of-rows)
10296   "Add up the number of pebbles in a triangle."
10297   (let ((total 0)
10298         (number-of-pebbles-in-row number-of-rows))
10299     (while (> number-of-pebbles-in-row 0)
10300       (setq total (+ total number-of-pebbles-in-row))
10301       (setq number-of-pebbles-in-row
10302             (1- number-of-pebbles-in-row)))
10303     total))
10304 @end group
10305 @end smallexample
10307 As written, this function works.
10309 However, we do not need @code{number-of-pebbles-in-row}.
10311 @cindex Argument as local variable
10312 When the @code{triangle} function is evaluated, the symbol
10313 @code{number-of-rows} will be bound to a number, giving it an initial
10314 value.  That number can be changed in the body of the function as if
10315 it were a local variable, without any fear that such a change will
10316 effect the value of the variable outside of the function.  This is a
10317 very useful characteristic of Lisp; it means that the variable
10318 @code{number-of-rows} can be used anywhere in the function where
10319 @code{number-of-pebbles-in-row} is used.
10321 @need 800
10322 Here is a second version of the function written a bit more cleanly:
10324 @smallexample
10325 @group
10326 (defun triangle (number)                ; @r{Second version.}
10327   "Return sum of numbers 1 through NUMBER inclusive."
10328   (let ((total 0))
10329     (while (> number 0)
10330       (setq total (+ total number))
10331       (setq number (1- number)))
10332     total))
10333 @end group
10334 @end smallexample
10336 In brief, a properly written @code{while} loop will consist of three parts:
10338 @enumerate
10339 @item
10340 A test that will return false after the loop has repeated itself the
10341 correct number of times.
10343 @item
10344 An expression the evaluation of which will return the value desired
10345 after being repeatedly evaluated.
10347 @item
10348 An expression to change the value passed to the true-or-false-test so
10349 that the test returns false after the loop has repeated itself the right
10350 number of times.
10351 @end enumerate
10353 @node dolist dotimes, Recursion, while, Loops & Recursion
10354 @comment  node-name,  next,  previous,  up
10355 @section Save your time: @code{dolist} and @code{dotimes}
10357 In addition to @code{while}, both @code{dolist} and @code{dotimes}
10358 provide for looping.  Sometimes these are quicker to write than the
10359 equivalent @code{while} loop.  Both are Lisp macros.  (@xref{Macros, ,
10360 Macros, elisp, The GNU Emacs Lisp Reference Manual}. )
10362 @code{dolist} works like a @code{while} loop that `@sc{cdr}s down a
10363 list':  @code{dolist} automatically shortens the list each time it
10364 loops---takes the @sc{cdr} of the list---and binds the @sc{car} of
10365 each shorter version of the list to the first of its arguments.
10367 @code{dotimes} loops a specific number of times: you specify the number.
10369 @menu
10370 * dolist::
10371 * dotimes::
10372 @end menu
10374 @node dolist, dotimes, dolist dotimes, dolist dotimes
10375 @unnumberedsubsubsec The @code{dolist} Macro
10376 @findex dolist
10378 Suppose, for example, you want to reverse a list, so that
10379 ``first'' ``second'' ``third'' becomes ``third'' ``second'' ``first''.
10381 @need 1250
10382 In practice, you would use the @code{reverse} function, like this:
10384 @smallexample
10385 @group
10386 (setq animals '(gazelle giraffe lion tiger))
10388 (reverse animals)
10389 @end group
10390 @end smallexample
10392 @need 800
10393 @noindent
10394 Here is how you could reverse the list using a @code{while} loop:
10396 @smallexample
10397 @group
10398 (setq animals '(gazelle giraffe lion tiger))
10400 (defun reverse-list-with-while (list)
10401   "Using while, reverse the order of LIST."
10402   (let (value)  ; make sure list starts empty
10403     (while list
10404       (setq value (cons (car list) value))
10405       (setq list (cdr list)))
10406     value))
10408 (reverse-list-with-while animals)
10409 @end group
10410 @end smallexample
10412 @need 800
10413 @noindent
10414 And here is how you could use the @code{dolist} macro:
10416 @smallexample
10417 @group
10418 (setq animals '(gazelle giraffe lion tiger))
10420 (defun reverse-list-with-dolist (list)
10421   "Using dolist, reverse the order of LIST."
10422   (let (value)  ; make sure list starts empty
10423     (dolist (element list value)
10424       (setq value (cons element value)))))
10426 (reverse-list-with-dolist animals)
10427 @end group
10428 @end smallexample
10430 @need 1250
10431 @noindent
10432 In Info, you can place your cursor after the closing parenthesis of
10433 each expression and type @kbd{C-x C-e}; in each case, you should see
10435 @smallexample
10436 (tiger lion giraffe gazelle)
10437 @end smallexample
10439 @noindent
10440 in the echo area.
10442 For this example, the existing @code{reverse} function is obviously best.
10443 The @code{while} loop is just like our first example (@pxref{Loop
10444 Example, , A @code{while} Loop and a List}).  The @code{while} first
10445 checks whether the list has elements; if so, it constructs a new list
10446 by adding the first element of the list to the existing list (which in
10447 the first iteration of the loop is @code{nil}).  Since the second
10448 element is prepended in front of the first element, and the third
10449 element is prepended in front of the second element, the list is reversed.
10451 In the expression using a @code{while} loop,
10452 the @w{@code{(setq list (cdr list))}}
10453 expression shortens the list, so the @code{while} loop eventually
10454 stops.  In addition, it provides the @code{cons} expression with a new
10455 first element by creating a new and shorter list at each repetition of
10456 the loop.
10458 The @code{dolist} expression does very much the same as the
10459 @code{while} expression, except that the @code{dolist} macro does some
10460 of the work you have to do when writing a @code{while} expression.
10462 Like a @code{while} loop, a @code{dolist} loops.  What is different is
10463 that it automatically shortens the list each time it loops --- it
10464 `@sc{cdr}s down the list' on its own --- and it automatically binds
10465 the @sc{car} of each shorter version of the list to the first of its
10466 arguments.
10468 In the example, the @sc{car} of each shorter version of the list is
10469 referred to using the symbol @samp{element}, the list itself is called
10470 @samp{list}, and the value returned is called @samp{value}.  The
10471 remainder of the @code{dolist} expression is the body.
10473 The @code{dolist} expression binds the @sc{car} of each shorter
10474 version of the list to @code{element} and then evaluates the body of
10475 the expression; and repeats the loop.  The result is returned in
10476 @code{value}.
10478 @node dotimes,  , dolist, dolist dotimes
10479 @unnumberedsubsubsec The @code{dotimes} Macro
10480 @findex dotimes
10482 The @code{dotimes} macro is similar to @code{dolist}, except that it
10483 loops a specific number of times.
10485 The first argument to @code{dotimes} is assigned the numbers 0, 1, 2
10486 and so forth each time around the loop, and the value of the third
10487 argument is returned.  You need to provide the value of the second
10488 argument, which is how many times the macro loops.
10490 @need 1250
10491 For example, the following binds the numbers from 0 up to, but not
10492 including, the number 3 to the first argument, @var{number}, and then
10493 constructs a list of the three numbers.  (The first number is 0, the
10494 second number is 1, and the third number is 2; this makes a total of
10495 three numbers in all, starting with zero as the first number.)
10497 @smallexample
10498 @group
10499 (let (value)      ; otherwise a value is a void variable
10500   (dotimes (number 3 value)
10501     (setq value (cons number value))))
10503 @result{} (2 1 0)
10504 @end group
10505 @end smallexample
10507 @noindent
10508 @code{dotimes} returns @code{value}, so the way to use
10509 @code{dotimes} is to operate on some expression @var{number} number of
10510 times and then return the result, either as a list or an atom.
10512 @need 1250
10513 Here is an example of a @code{defun} that uses @code{dotimes} to add
10514 up the number of pebbles in a triangle.
10516 @smallexample
10517 @group
10518 (defun triangle-using-dotimes (number-of-rows)
10519   "Using dotimes, add up the number of pebbles in a triangle."
10520 (let ((total 0))  ; otherwise a total is a void variable
10521   (dotimes (number number-of-rows total)
10522     (setq total (+ total (1+ number))))))
10524 (triangle-using-dotimes 4)
10525 @end group
10526 @end smallexample
10528 @node Recursion, Looping exercise, dolist dotimes, Loops & Recursion
10529 @comment  node-name,  next,  previous,  up
10530 @section Recursion
10531 @cindex Recursion
10533 A recursive function contains code that tells the Lisp interpreter to
10534 call a program that runs exactly like itself, but with slightly
10535 different arguments.  The code runs exactly the same because it has
10536 the same name.  However, even though the program has the same name, it
10537 is not the same entity.  It is different.  In the jargon, it is a
10538 different `instance'.
10540 Eventually, if the program is written correctly, the `slightly
10541 different arguments' will become sufficiently different from the first
10542 arguments that the final instance will stop.
10544 @menu
10545 * Building Robots::             Same model, different serial number ...
10546 * Recursive Definition Parts::  Walk until you stop ...
10547 * Recursion with list::         Using a list as the test whether to recurse.
10548 * Recursive triangle function::
10549 * Recursion with cond::
10550 * Recursive Patterns::          Often used templates.
10551 * No Deferment::                Don't store up work ...
10552 * No deferment solution::
10553 @end menu
10555 @node Building Robots, Recursive Definition Parts, Recursion, Recursion
10556 @comment  node-name,  next,  previous,  up
10557 @subsection Building Robots: Extending the Metaphor
10558 @cindex Building robots
10559 @cindex Robots, building
10561 It is sometimes helpful to think of a running program as a robot that
10562 does a job.  In doing its job, a recursive function calls on a second
10563 robot to help it.  The second robot is identical to the first in every
10564 way, except that the second robot helps the first and has been
10565 passed different arguments than the first.
10567 In a recursive function, the second robot may call a third; and the
10568 third may call a fourth, and so on.  Each of these is a different
10569 entity; but all are clones.
10571 Since each robot has slightly different instructions---the arguments
10572 will differ from one robot to the next---the last robot should know
10573 when to stop.
10575 Let's expand on the metaphor in which a computer program is a robot.
10577 A function definition provides the blueprints for a robot.  When you
10578 install a function definition, that is, when you evaluate a
10579 @code{defun} special form, you install the necessary equipment to
10580 build robots.  It is as if you were in a factory, setting up an
10581 assembly line.  Robots with the same name are built according to the
10582 same blueprints.  So they have, as it were, the same `model number',
10583 but a different `serial number'.
10585 We often say that a recursive function `calls itself'.  What we mean
10586 is that the instructions in a recursive function cause the Lisp
10587 interpreter to run a different function that has the same name and
10588 does the same job as the first, but with different arguments.
10590 It is important that the arguments differ from one instance to the
10591 next; otherwise, the process will never stop.
10593 @node Recursive Definition Parts, Recursion with list, Building Robots, Recursion
10594 @comment  node-name,  next,  previous,  up
10595 @subsection The Parts of a Recursive Definition
10596 @cindex Parts of a Recursive Definition
10597 @cindex Recursive Definition Parts
10599 A recursive function typically contains a conditional expression which
10600 has three parts:
10602 @enumerate
10603 @item
10604 A true-or-false-test that determines whether the function is called
10605 again, here called the @dfn{do-again-test}.
10607 @item
10608 The name of the function.  When this name is called, a new instance of
10609 the function---a new robot, as it were---is created and told what to do.
10611 @item
10612 An expression that returns a different value each time the function is
10613 called, here called the @dfn{next-step-expression}.  Consequently, the
10614 argument (or arguments) passed to the new instance of the function
10615 will be different from that passed to the previous instance.  This
10616 causes the conditional expression, the @dfn{do-again-test}, to test
10617 false after the correct number of repetitions.
10618 @end enumerate
10620 Recursive functions can be much simpler than any other kind of
10621 function.  Indeed, when people first start to use them, they often look
10622 so mysteriously simple as to be incomprehensible.  Like riding a
10623 bicycle, reading a recursive function definition takes a certain knack
10624 which is hard at first but then seems simple.
10626 @need 1200
10627 There are several different common recursive patterns.  A very simple
10628 pattern looks like this:
10630 @smallexample
10631 @group
10632 (defun @var{name-of-recursive-function} (@var{argument-list})
10633   "@var{documentation}@dots{}"
10634   (if @var{do-again-test}
10635     @var{body}@dots{}
10636     (@var{name-of-recursive-function}
10637          @var{next-step-expression})))
10638 @end group
10639 @end smallexample
10641 Each time a recursive function is evaluated, a new instance of it is
10642 created and told what to do.  The arguments tell the instance what to do.
10644 An argument is bound to the value of the next-step-expression.  Each
10645 instance runs with a different value of the next-step-expression.
10647 The value in the next-step-expression is used in the do-again-test.
10649 The value returned by the next-step-expression is passed to the new
10650 instance of the function, which evaluates it (or some
10651 transmogrification of it) to determine whether to continue or stop.
10652 The next-step-expression is designed so that the do-again-test returns
10653 false when the function should no longer be repeated.
10655 The do-again-test is sometimes called the @dfn{stop condition},
10656 since it stops the repetitions when it tests false.
10658 @node Recursion with list, Recursive triangle function, Recursive Definition Parts, Recursion
10659 @comment  node-name,  next,  previous,  up
10660 @subsection Recursion with a List
10662 The example of a @code{while} loop that printed the elements of a list
10663 of numbers can be written recursively.  Here is the code, including
10664 an expression to set the value of the variable @code{animals} to a list.
10666 If you are using Emacs 20 or before, this example must be copied to
10667 the @file{*scratch*} buffer and each expression must be evaluated
10668 there.  Use @kbd{C-u C-x C-e} to evaluate the
10669 @code{(print-elements-recursively animals)} expression so that the
10670 results are printed in the buffer; otherwise the Lisp interpreter will
10671 try to squeeze the results into the one line of the echo area.
10673 Also, place your cursor immediately after the last closing parenthesis
10674 of the @code{print-elements-recursively} function, before the comment.
10675 Otherwise, the Lisp interpreter will try to evaluate the comment.
10677 If you are using Emacs 21 or later, you can evaluate this expression
10678 directly in Info.
10680 @findex print-elements-recursively
10681 @smallexample
10682 @group
10683 (setq animals '(gazelle giraffe lion tiger))
10685 (defun print-elements-recursively (list)
10686   "Print each element of LIST on a line of its own.
10687 Uses recursion."
10688   (if list                              ; @r{do-again-test}
10689       (progn
10690         (print (car list))              ; @r{body}
10691         (print-elements-recursively     ; @r{recursive call}
10692          (cdr list)))))                 ; @r{next-step-expression}
10694 (print-elements-recursively animals)
10695 @end group
10696 @end smallexample
10698 The @code{print-elements-recursively} function first tests whether
10699 there is any content in the list; if there is, the function prints the
10700 first element of the list, the @sc{car} of the list.  Then the
10701 function `invokes itself', but gives itself as its argument, not the
10702 whole list, but the second and subsequent elements of the list, the
10703 @sc{cdr} of the list.
10705 Put another way, if the list is not empty, the function invokes
10706 another instance of code that is similar to the initial code, but is a
10707 different thread of execution, with different arguments than the first
10708 instance.
10710 Put in yet another way, if the list is not empty, the first robot
10711 assemblies a second robot and tells it what to do; the second robot is
10712 a different individual from the first, but is the same model.
10714 When the second evaluation occurs, the @code{if} expression is
10715 evaluated and if true, prints the first element of the list it
10716 receives as its argument (which is the second element of the original
10717 list).  Then the function `calls itself' with the @sc{cdr} of the list
10718 it is invoked with, which (the second time around) is the @sc{cdr} of
10719 the @sc{cdr} of the original list.
10721 Note that although we say that the function `calls itself', what we
10722 mean is that the Lisp interpreter assembles and instructs a new
10723 instance of the program.  The new instance is a clone of the first,
10724 but is a separate individual.
10726 Each time the function `invokes itself', it invokes itself on a
10727 shorter version of the original list.  It creates a new instance that
10728 works on a shorter list.
10730 Eventually, the function invokes itself on an empty list.  It creates
10731 a new instance whose argument is @code{nil}.  The conditional expression
10732 tests the value of @code{list}.  Since the value of @code{list} is
10733 @code{nil}, the @code{if} expression tests false so the then-part is
10734 not evaluated.  The function as a whole then returns @code{nil}.
10736 @need 1200
10737 When you evaluate @code{(print-elements-recursively animals)} in the
10738 @file{*scratch*} buffer, you see this result:
10740 @smallexample
10741 @group
10742 gazelle
10744 giraffe
10746 lion
10748 tiger
10750 @end group
10751 @end smallexample
10753 @node Recursive triangle function, Recursion with cond, Recursion with list, Recursion
10754 @comment  node-name,  next,  previous,  up
10755 @subsection Recursion in Place of a Counter
10756 @findex triangle-recursively
10758 @need 1200
10759 The @code{triangle} function described in a previous section can also
10760 be written recursively.  It looks like this:
10762 @smallexample
10763 @group
10764 (defun triangle-recursively (number)
10765   "Return the sum of the numbers 1 through NUMBER inclusive.
10766 Uses recursion."
10767   (if (= number 1)                    ; @r{do-again-test}
10768       1                               ; @r{then-part}
10769     (+ number                         ; @r{else-part}
10770        (triangle-recursively          ; @r{recursive call}
10771         (1- number)))))               ; @r{next-step-expression}
10773 (triangle-recursively 7)
10774 @end group
10775 @end smallexample
10777 @noindent
10778 You can install this function by evaluating it and then try it by
10779 evaluating @code{(triangle-recursively 7)}.  (Remember to put your
10780 cursor immediately after the last parenthesis of the function
10781 definition, before the comment.)  The function evaluates to 28.
10783 To understand how this function works, let's consider what happens in the
10784 various cases when the function is passed 1, 2, 3, or 4 as the value of
10785 its argument.
10787 @menu
10788 * Recursive Example arg of 1 or 2::
10789 * Recursive Example arg of 3 or 4::
10790 @end menu
10792 @node Recursive Example arg of 1 or 2, Recursive Example arg of 3 or 4, Recursive triangle function, Recursive triangle function
10793 @ifnottex
10794 @unnumberedsubsubsec An argument of 1 or 2
10795 @end ifnottex
10797 First, what happens if the value of the argument is 1?
10799 The function has an @code{if} expression after the documentation
10800 string.  It tests whether the value of @code{number} is equal to 1; if
10801 so, Emacs evaluates the then-part of the @code{if} expression, which
10802 returns the number 1 as the value of the function.  (A triangle with
10803 one row has one pebble in it.)
10805 Suppose, however, that the value of the argument is 2.  In this case,
10806 Emacs evaluates the else-part of the @code{if} expression.
10808 @need 1200
10809 The else-part consists of an addition, the recursive call to
10810 @code{triangle-recursively} and a decrementing action; and it looks like
10811 this:
10813 @smallexample
10814 (+ number (triangle-recursively (1- number)))
10815 @end smallexample
10817 When Emacs evaluates this expression, the innermost expression is
10818 evaluated first; then the other parts in sequence.  Here are the steps
10819 in detail:
10821 @table @i
10822 @item Step 1 @w{  } Evaluate the innermost expression.
10824 The innermost expression is @code{(1- number)} so Emacs decrements the
10825 value of @code{number} from 2 to 1.
10827 @item Step 2 @w{  } Evaluate the @code{triangle-recursively} function.
10829 The Lisp interpreter creates an individual instance of
10830 @code{triangle-recursively}.  It does not matter that this function is
10831 contained within itself.  Emacs passes the result Step 1 as the
10832 argument used by this instance of the @code{triangle-recursively}
10833 function
10835 In this case, Emacs evaluates @code{triangle-recursively} with an
10836 argument of 1.  This means that this evaluation of
10837 @code{triangle-recursively} returns 1.
10839 @item Step 3 @w{  } Evaluate the value of @code{number}.
10841 The variable @code{number} is the second element of the list that
10842 starts with @code{+}; its value is 2.
10844 @item Step 4 @w{  } Evaluate the @code{+} expression.
10846 The @code{+} expression receives two arguments, the first
10847 from the evaluation of @code{number} (Step 3) and the second from the
10848 evaluation of @code{triangle-recursively} (Step 2).
10850 The result of the addition is the sum of 2 plus 1, and the number 3 is
10851 returned, which is correct.  A triangle with two rows has three
10852 pebbles in it.
10853 @end table
10855 @node Recursive Example arg of 3 or 4,  , Recursive Example arg of 1 or 2, Recursive triangle function
10856 @unnumberedsubsubsec An argument of 3 or 4
10858 Suppose that @code{triangle-recursively} is called with an argument of
10861 @table @i
10862 @item Step 1 @w{  } Evaluate the do-again-test.
10864 The @code{if} expression is evaluated first.  This is the do-again
10865 test and returns false, so the else-part of the @code{if} expression
10866 is evaluated.  (Note that in this example, the do-again-test causes
10867 the function to call itself when it tests false, not when it tests
10868 true.)
10870 @item Step 2 @w{  } Evaluate the innermost expression of the else-part.
10872 The innermost expression of the else-part is evaluated, which decrements
10873 3 to 2.  This is the next-step-expression.
10875 @item Step 3 @w{  } Evaluate the @code{triangle-recursively} function.
10877 The number 2 is passed to the @code{triangle-recursively} function.
10879 We know what happens when Emacs evaluates @code{triangle-recursively} with
10880 an argument of 2.  After going through the sequence of actions described
10881 earlier, it returns a value of 3.  So that is what will happen here.
10883 @item Step 4 @w{  } Evaluate the addition.
10885 3 will be passed as an argument to the addition and will be added to the
10886 number with which the function was called, which is 3.
10887 @end table
10889 @noindent
10890 The value returned by the function as a whole will be 6.
10892 Now that we know what will happen when @code{triangle-recursively} is
10893 called with an argument of 3, it is evident what will happen if it is
10894 called with an argument of 4:
10896 @quotation
10897 @need 800
10898 In the recursive call, the evaluation of
10900 @smallexample
10901 (triangle-recursively (1- 4))
10902 @end smallexample
10904 @need 800
10905 @noindent
10906 will return the value of evaluating
10908 @smallexample
10909 (triangle-recursively 3)
10910 @end smallexample
10912 @noindent
10913 which is 6 and this value will be added to 4 by the addition in the
10914 third line.
10915 @end quotation
10917 @noindent
10918 The value returned by the function as a whole will be 10.
10920 Each time @code{triangle-recursively} is evaluated, it evaluates a
10921 version of itself---a different instance of itself---with a smaller
10922 argument, until the argument is small enough so that it does not
10923 evaluate itself.
10925 Note that this particular design for a recursive function
10926 requires that operations be deferred.
10928 Before @code{(triangle-recursively 7)} can calculate its answer, it
10929 must call @code{(triangle-recursively 6)}; and before
10930 @code{(triangle-recursively 6)} can calculate its answer, it must call
10931 @code{(triangle-recursively 5)}; and so on.  That is to say, the
10932 calculation that @code{(triangle-recursively 7)} makes must be
10933 deferred until @code{(triangle-recursively 6)} makes its calculation;
10934 and @code{(triangle-recursively 6)} must defer until
10935 @code{(triangle-recursively 5)} completes; and so on.
10937 If each of these instances of @code{triangle-recursively} are thought
10938 of as different robots, the first robot must wait for the second to
10939 complete its job, which must wait until the third completes, and so
10942 There is a way around this kind of waiting, which we will discuss in
10943 @ref{No Deferment, , Recursion without Deferments}.
10945 @node Recursion with cond, Recursive Patterns, Recursive triangle function, Recursion
10946 @comment  node-name,  next,  previous,  up
10947 @subsection Recursion Example Using @code{cond}
10948 @findex cond
10950 The version of @code{triangle-recursively} described earlier is written
10951 with the @code{if} special form.  It can also be written using another
10952 special form called @code{cond}.  The name of the special form
10953 @code{cond} is an abbreviation of the word @samp{conditional}.
10955 Although the @code{cond} special form is not used as often in the
10956 Emacs Lisp sources as @code{if}, it is used often enough to justify
10957 explaining it.
10959 @need 800
10960 The template for a @code{cond} expression looks like this:
10962 @smallexample
10963 @group
10964 (cond
10965  @var{body}@dots{})
10966 @end group
10967 @end smallexample
10969 @noindent
10970 where the @var{body} is a series of lists.
10972 @need 800
10973 Written out more fully, the template looks like this:
10975 @smallexample
10976 @group
10977 (cond
10978  (@var{first-true-or-false-test} @var{first-consequent})
10979  (@var{second-true-or-false-test} @var{second-consequent})
10980  (@var{third-true-or-false-test} @var{third-consequent})
10981   @dots{})
10982 @end group
10983 @end smallexample
10985 When the Lisp interpreter evaluates the @code{cond} expression, it
10986 evaluates the first element (the @sc{car} or true-or-false-test) of
10987 the first expression in a series of expressions within the body of the
10988 @code{cond}.
10990 If the true-or-false-test returns @code{nil} the rest of that
10991 expression, the consequent, is skipped and  the true-or-false-test of the
10992 next expression is evaluated.  When an expression is found whose
10993 true-or-false-test returns a value that is not @code{nil}, the
10994 consequent of that expression is evaluated.  The consequent can be one
10995 or more expressions.  If the consequent consists of more than one
10996 expression, the expressions are evaluated in sequence and the value of
10997 the last one is returned.  If the expression does not have a consequent,
10998 the value of the true-or-false-test is returned.
11000 If none of the true-or-false-tests test true, the @code{cond} expression
11001 returns @code{nil}.
11003 @need 1250
11004 Written using @code{cond}, the @code{triangle} function looks like this:
11006 @smallexample
11007 @group
11008 (defun triangle-using-cond (number)
11009   (cond ((<= number 0) 0)
11010         ((= number 1) 1)
11011         ((> number 1)
11012          (+ number (triangle-using-cond (1- number))))))
11013 @end group
11014 @end smallexample
11016 @noindent
11017 In this example, the @code{cond} returns 0 if the number is less than or
11018 equal to 0, it returns 1 if the number is 1 and it evaluates @code{(+
11019 number (triangle-using-cond (1- number)))} if the number is greater than
11022 @node Recursive Patterns, No Deferment, Recursion with cond, Recursion
11023 @comment  node-name,  next,  previous,  up
11024 @subsection Recursive Patterns
11025 @cindex Recursive Patterns
11027 Here are three common recursive patterns.  Each involves a list.
11028 Recursion does not need to involve lists, but Lisp is designed for lists
11029 and this provides a sense of its primal capabilities.
11031 @menu
11032 * Every::
11033 * Accumulate::
11034 * Keep::
11035 @end menu
11037 @node Every, Accumulate, Recursive Patterns, Recursive Patterns
11038 @comment  node-name,  next,  previous,  up
11039 @unnumberedsubsubsec Recursive Pattern: @emph{every}
11040 @cindex Every, type of recursive pattern
11041 @cindex Recursive pattern: every
11043 In the @code{every} recursive pattern, an action is performed on every
11044 element of a list.
11046 @need 1500
11047 The basic pattern is:
11049 @itemize @bullet
11050 @item
11051 If a list be empty, return @code{nil}.
11052 @item
11053 Else, act on the beginning of the list (the @sc{car} of the list)
11054     @itemize @minus
11055     @item
11056     through a recursive call by the function on the rest (the
11057     @sc{cdr}) of the list,
11058     @item
11059     and, optionally, combine the acted-on element, using @code{cons},
11060     with the results of acting on the rest.
11061     @end itemize
11062 @end itemize
11064 @need 1500
11065 Here is example:
11067 @smallexample
11068 @group
11069 (defun square-each (numbers-list)
11070   "Square each of a NUMBERS LIST, recursively."
11071   (if (not numbers-list)                ; do-again-test
11072       nil
11073     (cons
11074      (* (car numbers-list) (car numbers-list))
11075      (square-each (cdr numbers-list))))) ; next-step-expression
11076 @end group
11078 @group
11079 (square-each '(1 2 3))
11080     @result{} (1 4 9)
11081 @end group
11082 @end smallexample
11084 @need 1200
11085 @noindent
11086 If @code{numbers-list} is empty, do nothing.  But if it has content,
11087 construct a list combining the square of the first number in the list
11088 with the result of the recursive call.
11090 (The example follows the pattern exactly: @code{nil} is returned if
11091 the numbers' list is empty.  In practice, you would write the
11092 conditional so it carries out the action when the numbers' list is not
11093 empty.)
11095 The @code{print-elements-recursively} function (@pxref{Recursion with
11096 list, , Recursion with a List}) is another example of an @code{every}
11097 pattern, except in this case, rather than bring the results together
11098 using @code{cons}, we print each element of output.
11100 @need 1250
11101 The @code{print-elements-recursively} function looks like this:
11103 @smallexample
11104 @group
11105 (setq animals '(gazelle giraffe lion tiger))
11106 @end group
11108 @group
11109 (defun print-elements-recursively (list)
11110   "Print each element of LIST on a line of its own.
11111 Uses recursion."
11112   (if list                              ; @r{do-again-test}
11113       (progn
11114         (print (car list))              ; @r{body}
11115         (print-elements-recursively     ; @r{recursive call}
11116          (cdr list)))))                 ; @r{next-step-expression}
11118 (print-elements-recursively animals)
11119 @end group
11120 @end smallexample
11122 @need 1500
11123 The pattern for @code{print-elements-recursively} is:
11125 @itemize @bullet
11126 @item
11127 If the list be empty, do nothing.
11128 @item
11129 But if the list has at least one element,
11130     @itemize @minus
11131     @item
11132     act on the beginning of the list (the @sc{car} of the list),
11133     @item
11134     and make a recursive call on the rest (the @sc{cdr}) of the list.
11135     @end itemize
11136 @end itemize
11138 @node Accumulate, Keep, Every, Recursive Patterns
11139 @comment  node-name,  next,  previous,  up
11140 @unnumberedsubsubsec Recursive Pattern: @emph{accumulate}
11141 @cindex Accumulate, type of recursive pattern
11142 @cindex Recursive pattern: accumulate
11144 Another recursive pattern is called the @code{accumulate} pattern.  In
11145 the @code{accumulate} recursive pattern, an action is performed on
11146 every element of a list and the result of that action is accumulated
11147 with the results of performing the action on the other elements.
11149 This is very like the `every' pattern using @code{cons}, except that
11150 @code{cons} is not used, but some other combiner.
11152 @need 1500
11153 The pattern is:
11155 @itemize @bullet
11156 @item
11157 If a list be empty, return zero or some other constant.
11158 @item
11159 Else, act on the beginning of the list (the @sc{car} of the list),
11160     @itemize @minus
11161     @item
11162     and combine that acted-on element, using @code{+} or
11163     some other combining function, with
11164     @item
11165     a recursive call by the function on the rest (the @sc{cdr}) of the list.
11166     @end itemize
11167 @end itemize
11169 @need 1500
11170 Here is an example:
11172 @smallexample
11173 @group
11174 (defun add-elements (numbers-list)
11175   "Add the elements of NUMBERS-LIST together."
11176   (if (not numbers-list)
11177       0
11178     (+ (car numbers-list) (add-elements (cdr numbers-list)))))
11179 @end group
11181 @group
11182 (add-elements '(1 2 3 4))
11183     @result{} 10
11184 @end group
11185 @end smallexample
11187 @xref{Files List, , Making a List of Files}, for an example of the
11188 accumulate pattern.
11190 @node Keep,  , Accumulate, Recursive Patterns
11191 @comment  node-name,  next,  previous,  up
11192 @unnumberedsubsubsec Recursive Pattern: @emph{keep}
11193 @cindex Keep, type of recursive pattern
11194 @cindex Recursive pattern: keep
11196 A third recursive pattern is called the @code{keep} pattern.
11197 In the @code{keep} recursive pattern, each element of a list is tested;
11198 the element is acted on and the results are kept only if the element
11199 meets a criterion.
11201 Again, this is very like the `every' pattern, except the element is
11202 skipped unless it meets a criterion.
11204 @need 1500
11205 The pattern has three parts:
11207 @itemize @bullet
11208 @item
11209 If a list be empty, return @code{nil}.
11210 @item
11211 Else, if the beginning of the list (the @sc{car} of the list) passes
11212         a test
11213     @itemize @minus
11214     @item
11215     act on that element and combine it, using @code{cons} with
11216     @item
11217     a recursive call by the function on the rest (the @sc{cdr}) of the list.
11218     @end itemize
11219 @item
11220 Otherwise, if the beginning of the list (the @sc{car} of the list) fails
11221 the test
11222     @itemize @minus
11223     @item
11224     skip on that element,
11225     @item
11226     and, recursively call the function on the rest (the @sc{cdr}) of the list.
11227     @end itemize
11228 @end itemize
11230 @need 1500
11231 Here is an example that uses @code{cond}:
11233 @smallexample
11234 @group
11235 (defun keep-three-letter-words (word-list)
11236   "Keep three letter words in WORD-LIST."
11237   (cond
11238    ;; First do-again-test: stop-condition
11239    ((not word-list) nil)
11241    ;; Second do-again-test: when to act
11242    ((eq 3 (length (symbol-name (car word-list))))
11243     ;; combine acted-on element with recursive call on shorter list
11244     (cons (car word-list) (keep-three-letter-words (cdr word-list))))
11246    ;; Third do-again-test: when to skip element;
11247    ;;   recursively call shorter list with next-step expression
11248    (t  (keep-three-letter-words (cdr word-list)))))
11249 @end group
11251 @group
11252 (keep-three-letter-words '(one two three four five six))
11253     @result{} (one two six)
11254 @end group
11255 @end smallexample
11257 It goes without saying that you need not use @code{nil} as the test for
11258 when to stop; and you can, of course, combine these patterns.
11260 @node No Deferment, No deferment solution, Recursive Patterns, Recursion
11261 @subsection Recursion without Deferments
11262 @cindex Deferment in recursion
11263 @cindex Recursion without Deferments
11265 Let's consider again what happens with the @code{triangle-recursively}
11266 function.  We will find that the intermediate calculations are
11267 deferred until all can be done.
11269 @need 800
11270 Here is the function definition:
11272 @smallexample
11273 @group
11274 (defun triangle-recursively (number)
11275   "Return the sum of the numbers 1 through NUMBER inclusive.
11276 Uses recursion."
11277   (if (= number 1)                    ; @r{do-again-test}
11278       1                               ; @r{then-part}
11279     (+ number                         ; @r{else-part}
11280        (triangle-recursively          ; @r{recursive call}
11281         (1- number)))))               ; @r{next-step-expression}
11282 @end group
11283 @end smallexample
11285 What happens when we call this function with a argument of 7?
11287 The first instance of the @code{triangle-recursively} function adds
11288 the number 7 to the value returned by a second instance of
11289 @code{triangle-recursively}, an instance that has been passed an
11290 argument of 6.  That is to say, the first calculation is:
11292 @smallexample
11293 (+ 7 (triangle-recursively 6))
11294 @end smallexample
11296 @noindent
11297 The first instance of @code{triangle-recursively}---you may want to
11298 think of it as a little robot---cannot complete its job.  It must hand
11299 off the calculation for @code{(triangle-recursively 6)} to a second
11300 instance of the program, to a second robot.  This second individual is
11301 completely different from the first one; it is, in the jargon, a
11302 `different instantiation'.  Or, put another way, it is a different
11303 robot.  It is the same model as the first; it calculates triangle
11304 numbers recursively; but it has a different serial number.
11306 And what does @code{(triangle-recursively 6)} return?  It returns the
11307 number 6 added to the value returned by evaluating
11308 @code{triangle-recursively} with an argument of 5.  Using the robot
11309 metaphor, it asks yet another robot to help it.
11311 @need 800
11312 Now the total is:
11314 @smallexample
11315 (+ 7 6 (triangle-recursively 5))
11316 @end smallexample
11318 @need 800
11319 And what happens next?
11321 @smallexample
11322 (+ 7 6 5 (triangle-recursively 4))
11323 @end smallexample
11325 Each time @code{triangle-recursively} is called, except for the last
11326 time, it creates another instance of the program---another robot---and
11327 asks it to make a calculation.
11329 @need 800
11330 Eventually, the full addition is set up and performed:
11332 @smallexample
11333 (+ 7 6 5 4 3 2 1)
11334 @end smallexample
11336 This design for the function defers the calculation of the first step
11337 until the second can be done, and defers that until the third can be
11338 done, and so on.  Each deferment means the computer must remember what
11339 is being waited on.  This is not a problem when there are only a few
11340 steps, as in this example.  But it can be a problem when there are
11341 more steps.
11343 @node No deferment solution,  , No Deferment, Recursion
11344 @subsection No Deferment Solution
11345 @cindex No deferment solution
11346 @cindex Defermentless solution
11347 @cindex Solution without deferment
11349 The solution to the problem of deferred operations is to write in a
11350 manner that does not defer operations@footnote{The phrase @dfn{tail
11351 recursive} is used to describe such a process, one that uses
11352 `constant space'.}.  This requires
11353 writing to a different pattern, often one that involves writing two
11354 function definitions, an `initialization' function and a `helper'
11355 function.
11357 The `initialization' function sets up the job; the `helper' function
11358 does the work.
11360 @need 1200
11361 Here are the two function definitions for adding up numbers.  They are
11362 so simple, I find them hard to understand.
11364 @smallexample
11365 @group
11366 (defun triangle-initialization (number)
11367   "Return the sum of the numbers 1 through NUMBER inclusive.
11368 This is the `initialization' component of a two function
11369 duo that uses recursion."
11370   (triangle-recursive-helper 0 0 number))
11371 @end group
11372 @end smallexample
11374 @smallexample
11375 @group
11376 (defun triangle-recursive-helper (sum counter number)
11377   "Return SUM, using COUNTER, through NUMBER inclusive.
11378 This is the `helper' component of a two function duo
11379 that uses recursion."
11380   (if (> counter number)
11381       sum
11382     (triangle-recursive-helper (+ sum counter)  ; @r{sum}
11383                                (1+ counter)     ; @r{counter}
11384                                number)))        ; @r{number}
11385 @end group
11386 @end smallexample
11388 @need 1250
11389 Install both function definitions by evaluating them, then call
11390 @code{triangle-initialization} with 2 rows:
11392 @smallexample
11393 @group
11394 (triangle-initialization 2)
11395     @result{} 3
11396 @end group
11397 @end smallexample
11399 The `initialization' function calls the first instance of the `helper'
11400 function with three arguments: zero, zero, and a number which is the
11401 number of rows in the triangle.
11403 The first two arguments passed to the `helper' function are
11404 initialization values.  These values are changed when
11405 @code{triangle-recursive-helper} invokes new instances.@footnote{The
11406 jargon is mildly confusing:  @code{triangle-recursive-helper} uses a
11407 process that is iterative in a procedure that is recursive.  The
11408 process is called iterative because the computer need only record the
11409 three values, @code{sum}, @code{counter}, and @code{number}; the
11410 procedure is recursive because the function `calls itself'.  On the
11411 other hand, both the process and the procedure used by
11412 @code{triangle-recursively} are called recursive.  The word
11413 `recursive' has different meanings in the two contexts.}
11415 Let's see what happens when we have a triangle that has one row.  (This
11416 triangle will have one pebble in it!)
11418 @need 1200
11419 @code{triangle-initialization} will call its helper with
11420 the arguments @w{@code{0 0 1}}.  That function will run the conditional
11421 test whether @code{(> counter number)}:
11423 @smallexample
11424 (> 0 1)
11425 @end smallexample
11427 @need 1200
11428 @noindent
11429 and find that the result is false, so it will invoke
11430 the then-part of the @code{if} clause:
11432 @smallexample
11433 @group
11434     (triangle-recursive-helper
11435      (+ sum counter)  ; @r{sum plus counter} @result{} @r{sum}
11436      (1+ counter)     ; @r{increment counter} @result{} @r{counter}
11437      number)          ; @r{number stays the same}
11438 @end group
11439 @end smallexample
11441 @need 800
11442 @noindent
11443 which will first compute:
11445 @smallexample
11446 @group
11447 (triangle-recursive-helper (+ 0 0)  ; @r{sum}
11448                            (1+ 0)   ; @r{counter}
11449                            1)       ; @r{number}
11450 @exdent which is:
11452 (triangle-recursive-helper 0 1 1)
11453 @end group
11454 @end smallexample
11456 Again, @code{(> counter number)} will be false, so again, the Lisp
11457 interpreter will evaluate @code{triangle-recursive-helper}, creating a
11458 new instance with new arguments.
11460 @need 800
11461 This new instance will be;
11463 @smallexample
11464 @group
11465     (triangle-recursive-helper
11466      (+ sum counter)  ; @r{sum plus counter} @result{} @r{sum}
11467      (1+ counter)     ; @r{increment counter} @result{} @r{counter}
11468      number)          ; @r{number stays the same}
11470 @exdent which is:
11472 (triangle-recursive-helper 1 2 1)
11473 @end group
11474 @end smallexample
11476 In this case, the @code{(> counter number)} test will be true!  So the
11477 instance will return the value of the sum, which will be 1, as
11478 expected.
11480 Now, let's pass @code{triangle-initialization} an argument
11481 of 2, to find out how many pebbles there are in a triangle with two rows.
11483 That function calls @code{(triangle-recursive-helper 0 0 2)}.
11485 @need 800
11486 In stages, the instances called will be:
11488 @smallexample
11489 @group
11490                           @r{sum counter number}
11491 (triangle-recursive-helper 0    1       2)
11493 (triangle-recursive-helper 1    2       2)
11495 (triangle-recursive-helper 3    3       2)
11496 @end group
11497 @end smallexample
11499 When the last instance is called, the @code{(> counter number)} test
11500 will be true, so the instance will return the value of @code{sum},
11501 which will be 3.
11503 This kind of pattern helps when you are writing functions that can use
11504 many resources in a computer.
11506 @need 1500
11507 @node Looping exercise,  , Recursion, Loops & Recursion
11508 @section Looping Exercise
11510 @itemize @bullet
11511 @item
11512 Write a function similar to @code{triangle} in which each row has a
11513 value which is the square of the row number.  Use a @code{while} loop.
11515 @item
11516 Write a function similar to @code{triangle} that multiplies instead of
11517 adds the values.
11519 @item
11520 Rewrite these two functions recursively.  Rewrite these functions
11521 using @code{cond}.
11523 @c comma in printed title causes problem in Info cross reference
11524 @item
11525 Write a function for Texinfo mode that creates an index entry at the
11526 beginning of a paragraph for every @samp{@@dfn} within the paragraph.
11527 (In a Texinfo file, @samp{@@dfn} marks a definition.  For more
11528 information, see
11529 @ifinfo
11530 @ref{Indicating, , Indicating Definitions, texinfo}.)
11531 @end ifinfo
11532 @ifhtml
11533 @ref{Indicating, , Indicating, texinfo, Texinfo Manual}.)
11534 @end ifhtml
11535 @iftex
11536 ``Indicating Definitions, Commands, etc.'' in @cite{Texinfo, The GNU
11537 Documentation Format}.)
11538 @end iftex
11539 @end itemize
11541 @node Regexp Search, Counting Words, Loops & Recursion, Top
11542 @comment  node-name,  next,  previous,  up
11543 @chapter Regular Expression Searches
11544 @cindex Searches, illustrating
11545 @cindex Regular expression searches
11546 @cindex Patterns, searching for
11547 @cindex Motion by sentence and paragraph
11548 @cindex Sentences, movement by
11549 @cindex Paragraphs, movement by
11551 Regular expression searches are used extensively in GNU Emacs.  The
11552 two functions, @code{forward-sentence} and @code{forward-paragraph},
11553 illustrate these searches well.  They use regular expressions to find
11554 where to move point.  The phrase `regular expression' is often written
11555 as `regexp'.
11557 Regular expression searches are described in @ref{Regexp Search, ,
11558 Regular Expression Search, emacs, The GNU Emacs Manual}, as well as in
11559 @ref{Regular Expressions, , , elisp, The GNU Emacs Lisp Reference
11560 Manual}.  In writing this chapter, I am presuming that you have at
11561 least a mild acquaintance with them.  The major point to remember is
11562 that regular expressions permit you to search for patterns as well as
11563 for literal strings of characters.  For example, the code in
11564 @code{forward-sentence} searches for the pattern of possible
11565 characters that could mark the end of a sentence, and moves point to
11566 that spot.
11568 Before looking at the code for the @code{forward-sentence} function, it
11569 is worth considering what the pattern that marks the end of a sentence
11570 must be.  The pattern is discussed in the next section; following that
11571 is a description of the regular expression search function,
11572 @code{re-search-forward}.  The @code{forward-sentence} function
11573 is described in the section following.  Finally, the
11574 @code{forward-paragraph} function is described in the last section of
11575 this chapter.  @code{forward-paragraph} is a complex function that
11576 introduces several new features.
11578 @menu
11579 * sentence-end::                The regular expression for @code{sentence-end}.
11580 * re-search-forward::           Very similar to @code{search-forward}.
11581 * forward-sentence::            A straightforward example of regexp search.
11582 * forward-paragraph::           A somewhat complex example.
11583 * etags::                       How to create your own @file{TAGS} table.
11584 * Regexp Review::
11585 * re-search Exercises::
11586 @end menu
11588 @node sentence-end, re-search-forward, Regexp Search, Regexp Search
11589 @comment  node-name,  next,  previous,  up
11590 @section The Regular Expression for @code{sentence-end}
11591 @findex sentence-end
11593 The symbol @code{sentence-end} is bound to the pattern that marks the
11594 end of a sentence.  What should this regular expression be?
11596 Clearly, a sentence may be ended by a period, a question mark, or an
11597 exclamation mark.  Indeed, only clauses that end with one of those three
11598 characters should be considered the end of a sentence.  This means that
11599 the pattern should include the character set:
11601 @smallexample
11602 [.?!]
11603 @end smallexample
11605 However, we do not want @code{forward-sentence} merely to jump to a
11606 period, a question mark, or an exclamation mark, because such a character
11607 might be used in the middle of a sentence.  A period, for example, is
11608 used after abbreviations.  So other information is needed.
11610 According to convention, you type two spaces after every sentence, but
11611 only one space after a period, a question mark, or an exclamation mark in
11612 the body of a sentence.  So a period, a question mark, or an exclamation
11613 mark followed by two spaces is a good indicator of an end of sentence.
11614 However, in a file, the two spaces may instead be a tab or the end of a
11615 line.  This means that the regular expression should include these three
11616 items as alternatives.
11618 @need 800
11619 This group of alternatives will look like this:
11621 @smallexample
11622 @group
11623 \\($\\| \\|  \\)
11624        ^   ^^
11625       TAB  SPC
11626 @end group
11627 @end smallexample
11629 @noindent
11630 Here, @samp{$} indicates the end of the line, and I have pointed out
11631 where the tab and two spaces are inserted in the expression.  Both are
11632 inserted by putting the actual characters into the expression.
11634 Two backslashes, @samp{\\}, are required before the parentheses and
11635 vertical bars: the first backslash quotes the following backslash in
11636 Emacs; and the second indicates that the following character, the
11637 parenthesis or the vertical bar, is special.
11639 @need 1000
11640 Also, a sentence may be followed by one or more carriage returns, like
11641 this:
11643 @smallexample
11644 @group
11647 @end group
11648 @end smallexample
11650 @noindent
11651 Like tabs and spaces, a carriage return is inserted into a regular
11652 expression by inserting it literally.  The asterisk indicates that the
11653 @key{RET} is repeated zero or more times.
11655 But a sentence end does not consist only of a period, a question mark or
11656 an exclamation mark followed by appropriate space: a closing quotation
11657 mark or a closing brace of some kind may precede the space.  Indeed more
11658 than one such mark or brace may precede the space.  These require a
11659 expression that looks like this:
11661 @smallexample
11662 []\"')@}]*
11663 @end smallexample
11665 In this expression, the first @samp{]} is the first character in the
11666 expression; the second character is @samp{"}, which is preceded by a
11667 @samp{\} to tell Emacs the @samp{"} is @emph{not} special.  The last
11668 three characters are @samp{'}, @samp{)}, and @samp{@}}.
11670 All this suggests what the regular expression pattern for matching the
11671 end of a sentence should be; and, indeed, if we evaluate
11672 @code{sentence-end} we find that it returns the following value:
11674 @smallexample
11675 @group
11676 sentence-end
11677      @result{} "[.?!][]\"')@}]*\\($\\|     \\|  \\)[
11679 @end group
11680 @end smallexample
11682 @ignore
11684 @noindent
11685 (Note that here the @key{TAB}, two spaces, and  @key{RET} are shown
11686 literally in the pattern.)
11688 This regular expression can be decyphered as follows:
11690 @table @code
11691 @item [.?!]
11692 The first part of the pattern is the three characters, a period, a question
11693 mark and an exclamation mark, within square brackets.  The pattern must
11694 begin with one or other of these characters.
11696 @item []\"')@}]*
11697 The second part of the pattern is the group of closing braces and
11698 quotation marks, which can appear zero or more times.  These may follow
11699 the period, question mark or exclamation mark.  In a regular expression,
11700 the backslash, @samp{\}, followed by the double quotation mark,
11701 @samp{"}, indicates the class of string-quote characters.  Usually, the
11702 double quotation mark is the only character in this class.  The
11703 asterisk, @samp{*}, indicates that the items in the previous group (the
11704 group surrounded by square brackets, @samp{[]}) may be repeated zero or
11705 more times.
11707 @item \\($\\|   \\|  \\)
11708 The third part of the pattern is one or other of: either the end of a
11709 line, or two blank spaces, or a tab.  The double back-slashes are used
11710 to prevent Emacs from reading the parentheses and vertical bars as part
11711 of the search pattern; the parentheses are used to mark the group and
11712 the vertical bars are used to indicated that the patterns to either side
11713 of them are alternatives.  The dollar sign is used to indicate the end
11714 of a line and both the two spaces and the tab are each inserted as is to
11715 indicate what they are.
11717 @item [@key{RET}]*
11718 Finally, the last part of the pattern indicates that the end of the line
11719 or the whitespace following the period, question mark or exclamation
11720 mark may, but need not, be followed by one or more carriage returns.  In
11721 the pattern, the carriage return is inserted as an actual carriage
11722 return between square brackets but here it is shown as @key{RET}.
11723 @end table
11725 @end ignore
11727 @node re-search-forward, forward-sentence, sentence-end, Regexp Search
11728 @comment  node-name,  next,  previous,  up
11729 @section The @code{re-search-forward} Function
11730 @findex re-search-forward
11732 The @code{re-search-forward} function is very like the
11733 @code{search-forward} function.  (@xref{search-forward, , The
11734 @code{search-forward} Function}.)
11736 @code{re-search-forward} searches for a regular expression.  If the
11737 search is successful, it leaves point immediately after the last
11738 character in the target.  If the search is backwards, it leaves point
11739 just before the first character in the target.  You may tell
11740 @code{re-search-forward} to return @code{t} for true.  (Moving point
11741 is therefore a `side effect'.)
11743 Like @code{search-forward}, the @code{re-search-forward} function takes
11744 four arguments:
11746 @enumerate
11747 @item
11748 The first argument is the regular expression that the function searches
11749 for.  The regular expression will be a string between quotations marks.
11751 @item
11752 The optional second argument limits how far the function will search; it is a
11753 bound, which is specified as a position in the buffer.
11755 @item
11756 The optional third argument specifies how the function responds to
11757 failure: @code{nil} as the third argument causes the function to
11758 signal an error (and print a message) when the search fails; any other
11759 value causes it to return @code{nil} if the search fails and @code{t}
11760 if the search succeeds.
11762 @item
11763 The optional fourth argument is the repeat count.  A negative repeat
11764 count causes @code{re-search-forward} to search backwards.
11765 @end enumerate
11767 @need 800
11768 The template for @code{re-search-forward} looks like this:
11770 @smallexample
11771 @group
11772 (re-search-forward "@var{regular-expression}"
11773                 @var{limit-of-search}
11774                 @var{what-to-do-if-search-fails}
11775                 @var{repeat-count})
11776 @end group
11777 @end smallexample
11779 The second, third, and fourth arguments are optional.  However, if you
11780 want to pass a value to either or both of the last two arguments, you
11781 must also pass a value to all the preceding arguments.  Otherwise, the
11782 Lisp interpreter will mistake which argument you are passing the value
11785 @need 1200
11786 In the @code{forward-sentence} function, the regular expression will be
11787 the value of the variable @code{sentence-end}, namely:
11789 @smallexample
11790 @group
11791 "[.?!][]\"')@}]*\\($\\|  \\|  \\)[
11793 @end group
11794 @end smallexample
11796 @noindent
11797 The limit of the search will be the end of the paragraph (since a
11798 sentence cannot go beyond a paragraph).  If the search fails, the
11799 function will return @code{nil}; and the repeat count will be provided
11800 by the argument to the @code{forward-sentence} function.
11802 @node forward-sentence, forward-paragraph, re-search-forward, Regexp Search
11803 @comment  node-name,  next,  previous,  up
11804 @section @code{forward-sentence}
11805 @findex forward-sentence
11807 The command to move the cursor forward a sentence is a straightforward
11808 illustration of how to use regular expression searches in Emacs Lisp.
11809 Indeed, the function looks longer and more complicated than it is; this
11810 is because the function is designed to go backwards as well as forwards;
11811 and, optionally, over more than one sentence.  The function is usually
11812 bound to the key command @kbd{M-e}.
11814 @menu
11815 * Complete forward-sentence::
11816 * fwd-sentence while loops::    Two @code{while} loops.
11817 * fwd-sentence re-search::      A regular expression search.
11818 @end menu
11820 @node Complete forward-sentence, fwd-sentence while loops, forward-sentence, forward-sentence
11821 @ifnottex
11822 @unnumberedsubsec Complete @code{forward-sentence} function definition
11823 @end ifnottex
11825 @need 1250
11826 Here is the code for @code{forward-sentence}:
11828 @smallexample
11829 @group
11830 (defun forward-sentence (&optional arg)
11831   "Move forward to next sentence-end.  With argument, repeat.
11832 With negative argument, move backward repeatedly to sentence-beginning.
11833 Sentence ends are identified by the value of sentence-end
11834 treated as a regular expression.  Also, every paragraph boundary
11835 terminates sentences as well."
11836 @end group
11837 @group
11838   (interactive "p")
11839   (or arg (setq arg 1))
11840   (while (< arg 0)
11841     (let ((par-beg
11842            (save-excursion (start-of-paragraph-text) (point))))
11843       (if (re-search-backward
11844            (concat sentence-end "[^ \t\n]") par-beg t)
11845           (goto-char (1- (match-end 0)))
11846         (goto-char par-beg)))
11847     (setq arg (1+ arg)))
11848   (while (> arg 0)
11849     (let ((par-end
11850            (save-excursion (end-of-paragraph-text) (point))))
11851       (if (re-search-forward sentence-end par-end t)
11852           (skip-chars-backward " \t\n")
11853         (goto-char par-end)))
11854     (setq arg (1- arg))))
11855 @end group
11856 @end smallexample
11858 The function looks long at first sight and it is best to look at its
11859 skeleton first, and then its muscle.  The way to see the skeleton is to
11860 look at the expressions that start in the left-most columns:
11862 @smallexample
11863 @group
11864 (defun forward-sentence (&optional arg)
11865   "@var{documentation}@dots{}"
11866   (interactive "p")
11867   (or arg (setq arg 1))
11868   (while (< arg 0)
11869     @var{body-of-while-loop}
11870   (while (> arg 0)
11871     @var{body-of-while-loop}
11872 @end group
11873 @end smallexample
11875 This looks much simpler!  The function definition consists of
11876 documentation, an @code{interactive} expression, an @code{or}
11877 expression, and @code{while} loops.
11879 Let's look at each of these parts in turn.
11881 We note that the documentation is thorough and understandable.
11883 The function has an @code{interactive "p"} declaration.  This means
11884 that the processed prefix argument, if any, is passed to the
11885 function as its argument.  (This will be a number.)  If the function
11886 is not passed an argument (it is optional) then the argument
11887 @code{arg} will be bound to 1.  When @code{forward-sentence} is called
11888 non-interactively without an argument, @code{arg} is bound to
11889 @code{nil}.
11891 The @code{or} expression handles the prefix argument.  What it does is
11892 either leave the value of @code{arg} as it is, but only if @code{arg}
11893 is bound to a value; or it sets the value of @code{arg} to 1, in the
11894 case when @code{arg} is bound to @code{nil}.
11896 @node fwd-sentence while loops, fwd-sentence re-search, Complete forward-sentence, forward-sentence
11897 @unnumberedsubsec The @code{while} loops
11899 Two @code{while} loops follow the @code{or} expression.  The first
11900 @code{while} has a true-or-false-test that tests true if the prefix
11901 argument for @code{forward-sentence} is a negative number.  This is for
11902 going backwards.  The body of this loop is similar to the body of the
11903 second @code{while} clause, but it is not exactly the same.  We will
11904 skip this @code{while} loop and concentrate on the second @code{while}
11905 loop.
11907 @need 1500
11908 The second @code{while} loop is for moving point forward.  Its skeleton
11909 looks like this:
11911 @smallexample
11912 @group
11913 (while (> arg 0)            ; @r{true-or-false-test}
11914   (let @var{varlist}
11915     (if (@var{true-or-false-test})
11916         @var{then-part}
11917       @var{else-part}
11918   (setq arg (1- arg))))     ; @code{while} @r{loop decrementer}
11919 @end group
11920 @end smallexample
11922 The @code{while} loop is of the decrementing kind.
11923 (@xref{Decrementing Loop, , A Loop with a Decrementing Counter}.)  It
11924 has a true-or-false-test that tests true so long as the counter (in
11925 this case, the variable @code{arg}) is greater than zero; and it has a
11926 decrementer that subtracts 1 from the value of the counter every time
11927 the loop repeats.
11929 If no prefix argument is given to @code{forward-sentence}, which is
11930 the most common way the command is used, this @code{while} loop will
11931 run once, since the value of @code{arg} will be 1.
11933 The body of the @code{while} loop consists of a @code{let} expression,
11934 which creates and binds a local variable, and has, as its body, an
11935 @code{if} expression.
11937 @need 1250
11938 The body of the @code{while} loop looks like this:
11940 @smallexample
11941 @group
11942 (let ((par-end
11943        (save-excursion (end-of-paragraph-text) (point))))
11944   (if (re-search-forward sentence-end par-end t)
11945       (skip-chars-backward " \t\n")
11946     (goto-char par-end)))
11947 @end group
11948 @end smallexample
11950 The @code{let} expression creates and binds the local variable
11951 @code{par-end}.  As we shall see, this local variable is designed to
11952 provide a bound or limit to the regular expression search.  If the
11953 search fails to find a proper sentence ending in the paragraph, it will
11954 stop on reaching the end of the paragraph.
11956 But first, let us examine how @code{par-end} is bound to the value of
11957 the end of the paragraph.  What happens is that the @code{let} sets the
11958 value of @code{par-end} to the value returned when the Lisp interpreter
11959 evaluates the expression
11961 @smallexample
11962 @group
11963 (save-excursion (end-of-paragraph-text) (point))
11964 @end group
11965 @end smallexample
11967 @noindent
11968 In this expression, @code{(end-of-paragraph-text)} moves point to the
11969 end of the paragraph, @code{(point)} returns the value of point, and then
11970 @code{save-excursion} restores point to its original position.  Thus,
11971 the @code{let} binds @code{par-end} to the value returned by the
11972 @code{save-excursion} expression, which is the position of the end of
11973 the paragraph.  (The @code{(end-of-paragraph-text)} function uses
11974 @code{forward-paragraph}, which we will discuss shortly.)
11976 @need 1200
11977 Emacs next evaluates the body of the @code{let}, which is an @code{if}
11978 expression that looks like this:
11980 @smallexample
11981 @group
11982 (if (re-search-forward sentence-end par-end t) ; @r{if-part}
11983     (skip-chars-backward " \t\n")              ; @r{then-part}
11984   (goto-char par-end)))                        ; @r{else-part}
11985 @end group
11986 @end smallexample
11988 The @code{if} tests whether its first argument is true and if so,
11989 evaluates its then-part; otherwise, the Emacs Lisp interpreter
11990 evaluates the else-part.  The true-or-false-test of the @code{if}
11991 expression is the regular expression search.
11993 It may seem odd to have what looks like the `real work' of
11994 the @code{forward-sentence} function buried here, but this is a common
11995 way this kind of operation is carried out in Lisp.
11997 @node fwd-sentence re-search,  , fwd-sentence while loops, forward-sentence
11998 @unnumberedsubsec The regular expression search
12000 The @code{re-search-forward} function searches for the end of the
12001 sentence, that is, for the pattern defined by the @code{sentence-end}
12002 regular expression.  If the pattern is found---if the end of the sentence is
12003 found---then the @code{re-search-forward} function does two things:
12005 @enumerate
12006 @item
12007 The @code{re-search-forward} function carries out a side effect, which
12008 is to move point to the end of the occurrence found.
12010 @item
12011 The @code{re-search-forward} function returns a value of true.  This is
12012 the value received by the @code{if}, and means that the search was
12013 successful.
12014 @end enumerate
12016 @noindent
12017 The side effect, the movement of point, is completed before the
12018 @code{if} function is handed the value returned by the successful
12019 conclusion of the search.
12021 When the @code{if} function receives the value of true from a successful
12022 call to @code{re-search-forward}, the @code{if} evaluates the then-part,
12023 which is the expression @code{(skip-chars-backward " \t\n")}.  This
12024 expression moves backwards over any blank spaces, tabs or carriage
12025 returns until a printed character is found and then leaves point after
12026 the character.  Since point has already been moved to the end of the
12027 pattern that marks the end of the sentence, this action leaves point
12028 right after the closing printed character of the sentence, which is
12029 usually a period.
12031 On the other hand, if the @code{re-search-forward} function fails to
12032 find a pattern marking the end of the sentence, the function returns
12033 false.  The false then causes the @code{if} to evaluate its third
12034 argument, which is @code{(goto-char par-end)}:  it moves point to the
12035 end of the paragraph.
12037 Regular expression searches are exceptionally useful and the pattern
12038 illustrated by @code{re-search-forward}, in which the search is the
12039 test of an @code{if} expression, is handy.  You will see or write code
12040 incorporating this pattern often.
12042 @node forward-paragraph, etags, forward-sentence, Regexp Search
12043 @comment  node-name,  next,  previous,  up
12044 @section @code{forward-paragraph}: a Goldmine of Functions
12045 @findex forward-paragraph
12047 The @code{forward-paragraph} function moves point forward to the end
12048 of the paragraph.  It is usually bound to @kbd{M-@}} and makes use of a
12049 number of functions that are important in themselves, including
12050 @code{let*}, @code{match-beginning}, and @code{looking-at}.
12052 The function definition for @code{forward-paragraph} is considerably
12053 longer than the function definition for @code{forward-sentence}
12054 because it works with a paragraph, each line of which may begin with a
12055 fill prefix.
12057 A fill prefix consists of a string of characters that are repeated at
12058 the beginning of each line.  For example, in Lisp code, it is a
12059 convention to start each line of a paragraph-long comment with
12060 @samp{;;; }.  In Text mode, four blank spaces make up another common
12061 fill prefix, creating an indented paragraph.  (@xref{Fill Prefix, , ,
12062 emacs, The GNU Emacs Manual}, for more information about fill
12063 prefixes.)
12065 The existence of a fill prefix means that in addition to being able to
12066 find the end of a paragraph whose lines begin on the left-most
12067 column, the @code{forward-paragraph} function must be able to find the
12068 end of a paragraph when all or many of the lines in the buffer begin
12069 with the fill prefix.
12071 Moreover, it is sometimes practical to ignore a fill prefix that
12072 exists, especially when blank lines separate paragraphs.
12073 This is an added complication.
12075 @menu
12076 * forward-paragraph in brief::  Key parts of the function definition.
12077 * fwd-para let::                The @code{let*} expression.
12078 * fwd-para while::              The forward motion @code{while} loop.
12079 * fwd-para between paragraphs::  Movement between paragraphs.
12080 * fwd-para within paragraph::   Movement within paragraphs.
12081 * fwd-para no fill prefix::     When there is no fill prefix.
12082 * fwd-para with fill prefix::   When there is a fill prefix.
12083 * fwd-para summary::            Summary of @code{forward-paragraph} code.
12084 @end menu
12086 @node forward-paragraph in brief, fwd-para let, forward-paragraph, forward-paragraph
12087 @ifnottex
12088 @unnumberedsubsec Shortened @code{forward-paragraph} function definition
12089 @end ifnottex
12091 Rather than print all of the @code{forward-paragraph} function, we
12092 will only print parts of it.  Read without preparation, the function
12093 can be daunting!
12095 @need 800
12096 In outline, the function looks like this:
12098 @smallexample
12099 @group
12100 (defun forward-paragraph (&optional arg)
12101   "@var{documentation}@dots{}"
12102   (interactive "p")
12103   (or arg (setq arg 1))
12104   (let*
12105       @var{varlist}
12106     (while (< arg 0)        ; @r{backward-moving-code}
12107       @dots{}
12108       (setq arg (1+ arg)))
12109     (while (> arg 0)        ; @r{forward-moving-code}
12110       @dots{}
12111       (setq arg (1- arg)))))
12112 @end group
12113 @end smallexample
12115 The first parts of the function are routine: the function's argument
12116 list consists of one optional argument.  Documentation follows.
12118 The lower case @samp{p} in the @code{interactive} declaration means
12119 that the processed prefix argument, if any, is passed to the function.
12120 This will be a number, and is the repeat count of how many paragraphs
12121 point will move.  The @code{or} expression in the next line handles
12122 the common case when no argument is passed to the function, which occurs
12123 if the function is called from other code rather than interactively.
12124 This case was described earlier.  (@xref{forward-sentence, The
12125 @code{forward-sentence} function}.)  Now we reach the end of the
12126 familiar part of this function.
12128 @node fwd-para let, fwd-para while, forward-paragraph in brief, forward-paragraph
12129 @unnumberedsubsec The @code{let*} expression
12131 The next line of the @code{forward-paragraph} function begins a
12132 @code{let*} expression.  This is a different kind of expression than
12133 we have seen so far.  The symbol is @code{let*} not @code{let}.
12135 The @code{let*} special form is like @code{let} except that Emacs sets
12136 each variable in sequence, one after another, and variables in the
12137 latter part of the varlist can make use of the values to which Emacs
12138 set variables in the earlier part of the varlist.
12140 In the @code{let*} expression in this function, Emacs binds two
12141 variables: @code{fill-prefix-regexp} and @code{paragraph-separate}.
12142 The value to which @code{paragraph-separate} is bound depends on the
12143 value of @code{fill-prefix-regexp}.
12145 @need 1200
12146 Let's look at each in turn.  The symbol @code{fill-prefix-regexp} is
12147 set to the value returned by evaluating the following list:
12149 @smallexample
12150 @group
12151 (and fill-prefix
12152      (not (equal fill-prefix ""))
12153      (not paragraph-ignore-fill-prefix)
12154      (regexp-quote fill-prefix))
12155 @end group
12156 @end smallexample
12158 @noindent
12159 This is an expression whose first element is the @code{and} special form.
12161 As we learned earlier (@pxref{kill-new function, , The @code{kill-new}
12162 function}), the @code{and} special form evaluates each of its
12163 arguments until one of the arguments returns a value of @code{nil}, in
12164 which case the @code{and} expression returns @code{nil}; however, if
12165 none of the arguments returns a value of @code{nil}, the value
12166 resulting from evaluating the last argument is returned.  (Since such
12167 a value is not @code{nil}, it is considered true in Lisp.)  In other
12168 words, an @code{and} expression returns a true value only if all its
12169 arguments are true.
12170 @findex and
12172 In this case, the variable @code{fill-prefix-regexp} is bound to a
12173 non-@code{nil} value only if the following four expressions produce a
12174 true (i.e., a non-@code{nil}) value when they are evaluated; otherwise,
12175 @code{fill-prefix-regexp} is bound to @code{nil}.
12177 @table @code
12178 @item fill-prefix
12179 When this variable is evaluated, the value of the fill prefix, if any,
12180 is returned.  If there is no fill prefix, this variable returns
12181 @code{nil}.
12183 @item (not (equal fill-prefix "")
12184 This expression checks whether an existing fill prefix is an empty
12185 string, that is, a string with no characters in it.  An empty string is
12186 not a useful fill prefix.
12188 @item (not paragraph-ignore-fill-prefix)
12189 This expression returns @code{nil} if the variable
12190 @code{paragraph-ignore-fill-prefix} has been turned on by being set to a
12191 true value such as @code{t}.
12193 @item (regexp-quote fill-prefix)
12194 This is the last argument to the @code{and} special form.  If all the
12195 arguments to the @code{and} are true, the value resulting from
12196 evaluating this expression will be returned by the @code{and} expression
12197 and bound to the variable @code{fill-prefix-regexp},
12198 @end table
12200 @findex regexp-quote
12201 @noindent
12202 The result of evaluating this @code{and} expression successfully is that
12203 @code{fill-prefix-regexp} will be bound to the value of
12204 @code{fill-prefix} as modified by the @code{regexp-quote} function.
12205 What @code{regexp-quote} does is read a string and return a regular
12206 expression that will exactly match the string and match nothing else.
12207 This means that @code{fill-prefix-regexp} will be set to a value that
12208 will exactly match the fill prefix if the fill prefix exists.
12209 Otherwise, the variable will be set to @code{nil}.
12211 The second local variable in the @code{let*} expression is
12212 @code{paragraph-separate}.  It is bound to the value returned by
12213 evaluating the expression:
12215 @smallexample
12216 @group
12217 (if fill-prefix-regexp
12218     (concat paragraph-separate
12219             "\\|^" fill-prefix-regexp "[ \t]*$")
12220   paragraph-separate)))
12221 @end group
12222 @end smallexample
12224 This expression shows why @code{let*} rather than @code{let} was used.
12225 The true-or-false-test for the @code{if} depends on whether the variable
12226 @code{fill-prefix-regexp} evaluates to @code{nil} or some other value.
12228 If @code{fill-prefix-regexp} does not have a value, Emacs evaluates
12229 the else-part of the @code{if} expression and binds
12230 @code{paragraph-separate} to its local value.
12231 (@code{paragraph-separate} is a regular expression that matches what
12232 separates paragraphs.)
12234 But if @code{fill-prefix-regexp} does have a value, Emacs evaluates
12235 the then-part of the @code{if} expression and binds
12236 @code{paragraph-separate} to a regular expression that includes the
12237 @code{fill-prefix-regexp} as part of the pattern.
12239 Specifically, @code{paragraph-separate} is set to the original value
12240 of the paragraph separate regular expression concatenated with an
12241 alternative expression that consists of the @code{fill-prefix-regexp}
12242 followed by a blank line.  The @samp{^} indicates that the
12243 @code{fill-prefix-regexp} must begin a line, and the optional
12244 whitespace to the end of the line is defined by @w{@code{"[ \t]*$"}}.)
12245 The @samp{\\|} defines this portion of the regexp as an alternative to
12246 @code{paragraph-separate}.
12248 Now we get into the body of the @code{let*}.  The first part of the body
12249 of the @code{let*} deals with the case when the function is given a
12250 negative argument and is therefore moving backwards.  We will skip this
12251 section.
12253 @node fwd-para while, fwd-para between paragraphs, fwd-para let, forward-paragraph
12254 @unnumberedsubsec The forward motion @code{while} loop
12256 The second part of the body of the @code{let*} deals with forward
12257 motion.  It is a @code{while} loop that repeats itself so long as the
12258 value of @code{arg} is greater than zero.  In the most common use of
12259 the function, the value of the argument is 1, so the body of the
12260 @code{while} loop is evaluated exactly once, and the cursor moves
12261 forward one paragraph.
12263 This part handles three situations: when point is between paragraphs,
12264 when point is within a paragraph and there is a fill prefix, and
12265 when point is within a paragraph and there is no fill prefix.
12267 @need 800
12268 The @code{while} loop looks like this:
12270 @smallexample
12271 @group
12272 (while (> arg 0)
12273   (beginning-of-line)
12275   ;; @r{between paragraphs}
12276   (while (prog1 (and (not (eobp))
12277                      (looking-at paragraph-separate))
12278            (forward-line 1)))
12279 @end group
12281 @group
12282   ;; @r{within paragraphs, with a fill prefix}
12283   (if fill-prefix-regexp
12284       ;; @r{There is a fill prefix; it overrides paragraph-start.}
12285       (while (and (not (eobp))
12286                   (not (looking-at paragraph-separate))
12287                   (looking-at fill-prefix-regexp))
12288         (forward-line 1))
12289 @end group
12291 @group
12292     ;; @r{within paragraphs, no fill prefix}
12293     (if (re-search-forward paragraph-start nil t)
12294         (goto-char (match-beginning 0))
12295       (goto-char (point-max))))
12297   (setq arg (1- arg)))
12298 @end group
12299 @end smallexample
12301 We can see immediately that this is a decrementing counter @code{while}
12302 loop, using the expression @code{(setq arg (1- arg))} as the decrementer.
12304 @need 800
12305 The body of the loop consists of three expressions:
12307 @smallexample
12308 @group
12309 ;; @r{between paragraphs}
12310 (beginning-of-line)
12311 (while
12312     @var{body-of-while})
12313 @end group
12315 @group
12316 ;; @r{within paragraphs, with fill prefix}
12317 (if @var{true-or-false-test}
12318     @var{then-part}
12319 @end group
12321 @group
12322 ;; @r{within paragraphs, no fill prefix}
12323   @var{else-part}
12324 @end group
12325 @end smallexample
12327 @noindent
12328 When the Emacs Lisp interpreter evaluates the body of the
12329 @code{while} loop, the first thing it does is evaluate the
12330 @code{(beginning-of-line)} expression and move point to the beginning
12331 of the line.  Then there is an inner @code{while} loop.  This
12332 @code{while} loop is designed to move the cursor out of the blank
12333 space between paragraphs, if it should happen to be there.  Finally,
12334 there is an @code{if} expression that actually moves point to the end
12335 of the paragraph.
12337 @node fwd-para between paragraphs, fwd-para within paragraph, fwd-para while, forward-paragraph
12338 @unnumberedsubsec Between paragraphs
12340 First, let us look at the inner @code{while} loop.  This loop handles
12341 the case when point is between paragraphs; it uses three functions
12342 that are new to us: @code{prog1}, @code{eobp} and @code{looking-at}.
12343 @findex prog1
12344 @findex eobp
12345 @findex looking-at
12347 @itemize @bullet
12348 @item
12349 @code{prog1} is similar to the @code{progn} special form,
12350 except that @code{prog1} evaluates its arguments in sequence and then
12351 returns the value of its first argument as the value of the whole
12352 expression.  (@code{progn} returns the value of its last argument as the
12353 value of the expression.) The second and subsequent arguments to
12354 @code{prog1} are evaluated only for their side effects.
12356 @item
12357 @code{eobp} is an abbreviation of @samp{End Of Buffer P} and is a
12358 function that returns true if point is at the end of the buffer.
12360 @item
12361 @code{looking-at} is a function that returns true if the text following
12362 point matches the regular expression passed @code{looking-at} as its
12363 argument.
12364 @end itemize
12366 @need 800
12367 The @code{while} loop we are studying looks like this:
12369 @smallexample
12370 @group
12371 (while (prog1 (and (not (eobp))
12372                    (looking-at paragraph-separate))
12373               (forward-line 1)))
12374 @end group
12375 @end smallexample
12377 @need 1200
12378 @noindent
12379 This is a @code{while} loop with no body!  The true-or-false-test of the
12380 loop is the expression:
12382 @smallexample
12383 @group
12384 (prog1 (and (not (eobp))
12385             (looking-at paragraph-separate))
12386        (forward-line 1))
12387 @end group
12388 @end smallexample
12390 @noindent
12391 The first argument to the @code{prog1} is the @code{and} expression.  It
12392 has within in it a test of whether point is at the end of the buffer and
12393 also a test of whether the pattern following point matches the regular
12394 expression for separating paragraphs.
12396 If the cursor is not at the end of the buffer and if the characters
12397 following the cursor mark the separation between two paragraphs, then
12398 the @code{and} expression is true.  After evaluating the @code{and}
12399 expression, the Lisp interpreter evaluates the second argument to
12400 @code{prog1}, which is @code{forward-line}.  This moves point forward
12401 one line.  The value returned by the @code{prog1} however, is the
12402 value of its first argument, so the @code{while} loop continues so
12403 long as point is not at the end of the buffer and is between
12404 paragraphs.  When, finally, point is moved to a paragraph, the
12405 @code{and} expression tests false.  Note however, that the
12406 @code{forward-line} command is carried out anyhow.  This means that
12407 when point is moved from between paragraphs to a paragraph, it is left
12408 at the beginning of the second line of the paragraph.
12410 @node fwd-para within paragraph, fwd-para no fill prefix, fwd-para between paragraphs, forward-paragraph
12411 @unnumberedsubsec Within paragraphs
12413 The next expression in the outer @code{while} loop is an @code{if}
12414 expression.  The Lisp interpreter evaluates the then-part of the
12415 @code{if} when the @code{fill-prefix-regexp} variable has a value other
12416 than @code{nil}, and it evaluates the else-part when the value of
12417 @code{if fill-prefix-regexp} is @code{nil}, that is, when there is no
12418 fill prefix.
12420 @node fwd-para no fill prefix, fwd-para with fill prefix, fwd-para within paragraph, forward-paragraph
12421 @unnumberedsubsec No fill prefix
12423 It is simplest to look at the code for the case when there is no fill
12424 prefix first.  This code consists of yet another inner @code{if}
12425 expression, and reads as follows:
12427 @smallexample
12428 @group
12429 (if (re-search-forward paragraph-start nil t)
12430     (goto-char (match-beginning 0))
12431   (goto-char (point-max)))
12432 @end group
12433 @end smallexample
12435 @noindent
12436 This expression actually does the work that most people think of as
12437 the primary purpose of the @code{forward-paragraph} command: it causes
12438 a regular expression search to occur that searches forward to the
12439 start of the next paragraph and if it is found, moves point there; but
12440 if the start of another paragraph if not found, it moves point to the
12441 end of the accessible region of the buffer.
12443 The only unfamiliar part of this is the use of @code{match-beginning}.
12444 This is another function that is new to us.  The
12445 @code{match-beginning} function returns a number specifying the
12446 location of the start of the text that was matched by the last regular
12447 expression search.
12449 The @code{match-beginning} function is used here because of a
12450 characteristic of a forward search: a successful forward search,
12451 regardless of whether it is a plain search or a regular expression
12452 search, will move point to the end of the text that is found.  In this
12453 case, a successful search will move point to the end of the pattern for
12454 @code{paragraph-start}, which will be the beginning of the next
12455 paragraph rather than the end of the current one.
12457 However, we want to put point at the end of the current paragraph, not at
12458 the beginning of the next one.  The two positions may be different,
12459 because there may be several blank lines between paragraphs.
12461 @findex match-beginning
12462 When given an argument of 0, @code{match-beginning} returns the position
12463 that is the start of the text that the most recent regular
12464 expression search matched.  In this case, the most recent regular
12465 expression search is the one looking for @code{paragraph-start}, so
12466 @code{match-beginning} returns the beginning position of the pattern,
12467 rather than the end of the pattern.  The beginning position is the end
12468 of the paragraph.
12470 (Incidentally, when passed a positive number as an argument, the
12471 @code{match-beginning} function will place point at that parenthesized
12472 expression in the last regular expression.  It is a useful function.)
12474 @node fwd-para with fill prefix, fwd-para summary, fwd-para no fill prefix, forward-paragraph
12475 @unnumberedsubsec With a fill prefix
12477 The inner @code{if} expression just discussed is the else-part of an enclosing
12478 @code{if} expression which tests whether there is a fill prefix.  If
12479 there is a fill prefix, the then-part of this @code{if} is evaluated.
12480 It looks like this:
12482 @smallexample
12483 @group
12484 (while (and (not (eobp))
12485             (not (looking-at paragraph-separate))
12486             (looking-at fill-prefix-regexp))
12487   (forward-line 1))
12488 @end group
12489 @end smallexample
12491 @noindent
12492 What this expression does is move point forward line by line so long
12493 as three conditions are true:
12495 @enumerate
12496 @item
12497 Point is not at the end of the buffer.
12499 @item
12500 The text following point does not separate paragraphs.
12502 @item
12503 The pattern following point is the fill prefix regular expression.
12504 @end enumerate
12506 The last condition may be puzzling, until you remember that point was
12507 moved to the beginning of the line early in the @code{forward-paragraph}
12508 function.  This means that if the text has a fill prefix, the
12509 @code{looking-at} function will see it.
12511 @node fwd-para summary,  , fwd-para with fill prefix, forward-paragraph
12512 @unnumberedsubsec Summary
12514 In summary, when moving forward, the @code{forward-paragraph} function
12515 does the following:
12517 @itemize @bullet
12518 @item
12519 Move point to the beginning of the line.
12521 @item
12522 Skip over lines between paragraphs.
12524 @item
12525 Check whether there is a fill prefix, and if there is:
12527 @itemize ---
12529 @item
12530 Go forward line by line so long as the line is not a paragraph
12531 separating line.
12532 @end itemize
12534 @item
12535 But if there is no fill prefix,
12537 @itemize ---
12539 @item
12540 Search for the next paragraph start pattern.
12542 @item
12543 Go to the beginning of the paragraph start pattern, which will be the
12544 end of the previous paragraph.
12546 @item
12547 Or else go to the end of the accessible portion of the buffer.
12548 @end itemize
12549 @end itemize
12551 @need 1200
12552 For review, here is the code we have just been discussing, formatted
12553 for clarity:
12555 @smallexample
12556 @group
12557 (interactive "p")
12558 (or arg (setq arg 1))
12559 (let* (
12560        (fill-prefix-regexp
12561         (and fill-prefix (not (equal fill-prefix ""))
12562              (not paragraph-ignore-fill-prefix)
12563              (regexp-quote fill-prefix)))
12564 @end group
12566 @group
12567        (paragraph-separate
12568         (if fill-prefix-regexp
12569             (concat paragraph-separate
12570                     "\\|^"
12571                     fill-prefix-regexp
12572                     "[ \t]*$")
12573           paragraph-separate)))
12575   @var{omitted-backward-moving-code} @dots{}
12576 @end group
12578 @group
12579   (while (> arg 0)                ; @r{forward-moving-code}
12580     (beginning-of-line)
12582     (while (prog1 (and (not (eobp))
12583                        (looking-at paragraph-separate))
12584              (forward-line 1)))
12585 @end group
12587 @group
12588     (if fill-prefix-regexp
12589         (while (and (not (eobp))  ; @r{then-part}
12590                     (not (looking-at paragraph-separate))
12591                     (looking-at fill-prefix-regexp))
12592           (forward-line 1))
12593 @end group
12594 @group
12595                                   ; @r{else-part: the inner-if}
12596       (if (re-search-forward paragraph-start nil t)
12597           (goto-char (match-beginning 0))
12598         (goto-char (point-max))))
12600     (setq arg (1- arg)))))        ; @r{decrementer}
12601 @end group
12602 @end smallexample
12604 The full definition for the @code{forward-paragraph} function not only
12605 includes this code for going forwards, but also code for going backwards.
12607 If you are reading this inside of GNU Emacs and you want to see the
12608 whole function, you can type @kbd{C-h f} (@code{describe-function})
12609 and the name of the function.  This gives you the function
12610 documentation and the name of the library containing the function's
12611 source.  Place point over the name of the library and press the RET
12612 key; you will be taken directly to the source.  (Be sure to install
12613 your sources!  Without them, you are like a person who tries to drive
12614 a car with his eyes shut!)
12616 @c !!! again, 21.0.100 tags table location in this paragraph
12617 Or -- a good habit to get into -- you can type @kbd{M-.}
12618 (@code{find-tag}) and the name of the function when prompted for it.
12619 This will take you directly to the source.  If the @code{find-tag}
12620 function first asks you for the name of a @file{TAGS} table, give it
12621 the name of the @file{TAGS} file such as
12622 @file{/usr/local/share/emacs/21.0.100/lisp/TAGS}.  (The exact path to your
12623 @file{TAGS} file depends on how your copy of Emacs was installed.)
12625 You can also create your own @file{TAGS} file for directories that
12626 lack one.
12627 @ifnottex
12628 @xref{etags, , Create Your Own @file{TAGS} File}.
12629 @end ifnottex
12631 @node etags, Regexp Review, forward-paragraph, Regexp Search
12632 @section Create Your Own @file{TAGS} File
12633 @findex etags
12634 @cindex @file{TAGS} file, create own
12636 The @kbd{M-.} (@code{find-tag}) command takes you directly to the
12637 source for a function, variable, node, or other source.  The function
12638 depends on tags tables to tell it where to go.
12640 You often need to build and install tags tables yourself.  They are
12641 not built automatically.  A tags table is called a @file{TAGS} file;
12642 the name is in upper case letters.
12644 You can create a @file{TAGS} file by calling the @code{etags} program
12645 that comes as a part of the Emacs distribution.  Usually, @code{etags}
12646 is compiled and installed when Emacs is built.  (@code{etags} is not
12647 an Emacs Lisp function or a part of Emacs; it is a C program.)
12649 @need 1250
12650 To create a @file{TAGS} file, first switch to the directory in which
12651 you want to create the file.  In Emacs you can do this with the
12652 @kbd{M-x cd} command, or by visiting a file in the directory, or by
12653 listing the directory with @kbd{C-x d} (@code{dired}).  Then run the
12654 compile command, with @w{@code{etags *.el}} as the command to execute
12656 @smallexample
12657 M-x compile RET etags *.el RET
12658 @end smallexample
12660 @noindent
12661 to create a @file{TAGS} file.
12663 For example, if you have a large number of files in your
12664 @file{~/emacs} directory, as I do---I have 137 @file{.el} files in it,
12665 of which I load 12---you can create a @file{TAGS} file for the Emacs
12666 Lisp files in that directory.
12668 @need 1250
12669 The @code{etags} program takes all the
12670 usual shell `wildcards'.  For example, if you have two directories for
12671 which you want a single @file{TAGS file}, type
12672 @w{@code{etags *.el ../elisp/*.el}},
12673 where @file{../elisp/} is the second directory:
12675 @smallexample
12676 M-x compile RET etags *.el ../elisp/*.el RET
12677 @end smallexample
12679 @need 1250
12680 Type
12682 @smallexample
12683 M-x compile RET etags --help RET
12684 @end smallexample
12686 @noindent
12687 to see a list of the options accepted by @code{etags} as well as a
12688 list of supported languages.
12690 The @code{etags} program handles more than 20 languages, including
12691 Emacs Lisp, Common Lisp, Scheme, C, C++, Ada, Fortran, Java, LaTeX,
12692 Pascal, Perl, Python, Texinfo, makefiles, and most assemblers.  The
12693 program has no switches for specifying the language; it recognizes the
12694 language in an input file according to its file name and contents.
12696 @file{etags} is very helpful when you are writing code yourself and
12697 want to refer back to functions you have already written.  Just run
12698 @code{etags} again at intervals as you write new functions, so they
12699 become part of the @file{TAGS} file.
12701 If you think an appropriate @file{TAGS} file already exists for what
12702 you want, but do not know where it is, you can use the @code{locate}
12703 program to attempt to find it.
12705 Type @w{@kbd{M-x locate RET TAGS RET}} and Emacs will list for you the
12706 full path names of all your @file{TAGS} files.  On my system, this
12707 command lists 34 @file{TAGS} files.  On the other hand, a `plain
12708 vanilla' system I recently installed did not contain any @file{TAGS}
12709 files.
12711 If the tags table you want has been created, you can use the @code{M-x
12712 visit-tags-table} command to specify it.  Otherwise, you will need to
12713 create the tag table yourself and then use @code{M-x
12714 visit-tags-table}.
12716 @subsubheading Building Tags in the Emacs sources
12717 @cindex Building Tags in the Emacs sources
12718 @cindex Tags in the Emacs sources
12719 @findex make tags
12721 The GNU Emacs sources come with a @file{Makefile} that contains a
12722 sophisticated @code{etags} command that creates, collects, and merges
12723 tags tables from all over the Emacs sources and puts the information
12724 into one @file{TAGS} file in the @file{src/} directory below the top
12725 level of your Emacs source directory.
12727 @need 1250
12728 To build this @file{TAGS} file, go to the top level of your Emacs
12729 source directory and run the compile command @code{make tags}:
12731 @smallexample
12732 M-x compile RET make tags RET
12733 @end smallexample
12735 @noindent
12736 (The @code{make tags} command works well with the GNU Emacs sources,
12737 as well as with some other source packages.)
12739 For more information, see @ref{Tags, , Tag Tables, emacs, The GNU Emacs
12740 Manual}.
12742 @node Regexp Review, re-search Exercises, etags, Regexp Search
12743 @comment  node-name,  next,  previous,  up
12744 @section Review
12746 Here is a brief summary of some recently introduced functions.
12748 @table @code
12749 @item while
12750 Repeatedly evaluate the body of the expression so long as the first
12751 element of the body tests true.  Then return @code{nil}.  (The
12752 expression is evaluated only for its side effects.)
12754 @need 1250
12755 For example:
12757 @smallexample
12758 @group
12759 (let ((foo 2))
12760   (while (> foo 0)
12761     (insert (format "foo is %d.\n" foo))
12762     (setq foo (1- foo))))
12764      @result{}      foo is 2.
12765              foo is 1.
12766              nil
12767 @end group
12768 @end smallexample
12769 @noindent
12770 (The @code{insert} function inserts its arguments at point; the
12771 @code{format} function returns a string formatted from its arguments
12772 the way @code{message} formats its arguments; @code{\n} produces a new
12773 line.)
12775 @item re-search-forward
12776 Search for a pattern, and if the pattern is found, move point to rest
12777 just after it.
12779 @noindent
12780 Takes four arguments, like @code{search-forward}:
12782 @enumerate
12783 @item
12784 A regular expression that specifies the pattern to search for.
12786 @item
12787 Optionally, the limit of the search.
12789 @item
12790 Optionally, what to do if the search fails, return @code{nil} or an
12791 error message.
12793 @item
12794 Optionally, how many times to repeat the search; if negative, the
12795 search goes backwards.
12796 @end enumerate
12798 @item let*
12799 Bind some variables locally to particular values,
12800 and then evaluate the remaining arguments, returning the value of the
12801 last one.  While binding the local variables, use the local values of
12802 variables bound earlier, if any.
12804 @need 1250
12805 For example:
12807 @smallexample
12808 @group
12809 (let* ((foo 7)
12810       (bar (* 3 foo)))
12811   (message "`bar' is %d." bar))
12812      @result{} `bar' is 21.
12813 @end group
12814 @end smallexample
12816 @item match-beginning
12817 Return the position of the start of the text found by the last regular
12818 expression search.
12820 @item looking-at
12821 Return @code{t} for true if the text after point matches the argument,
12822 which should be a regular expression.
12824 @item eobp
12825 Return @code{t} for true if point is at the end of the accessible part
12826 of a buffer.  The end of the accessible part is the end of the buffer
12827 if the buffer is not narrowed; it is the end of the narrowed part if
12828 the buffer is narrowed.
12830 @item prog1
12831 Evaluate each argument in sequence and then return the value of the
12832 @emph{first}.
12834 @need 1250
12835 For example:
12837 @smallexample
12838 @group
12839 (prog1 1 2 3 4)
12840      @result{} 1
12841 @end group
12842 @end smallexample
12843 @end table
12845 @need 1500
12846 @node re-search Exercises,  , Regexp Review, Regexp Search
12847 @section Exercises with @code{re-search-forward}
12849 @itemize @bullet
12850 @item
12851 Write a function to search for a regular expression that matches two
12852 or more blank lines in sequence.
12854 @item
12855 Write a function to search for duplicated words, such as `the the'.
12856 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
12857 Manual}, for information on how to write a regexp (a regular
12858 expression) to match a string that is composed of two identical
12859 halves.  You can devise several regexps; some are better than others.
12860 The function I use is described in an appendix, along with several
12861 regexps.  @xref{the-the, , @code{the-the} Duplicated Words Function}.
12862 @end itemize
12864 @node Counting Words, Words in a defun, Regexp Search, Top
12865 @chapter Counting: Repetition and Regexps
12866 @cindex Repetition for word counting
12867 @cindex Regular expressions for word counting
12869 Repetition and regular expression searches are powerful tools that you
12870 often use when you write code in Emacs Lisp.  This chapter illustrates
12871 the use of regular expression searches through the construction of
12872 word count commands using @code{while} loops and recursion.
12874 @menu
12875 * Why Count Words::
12876 * count-words-region::          Use a regexp, but find a problem.
12877 * recursive-count-words::       Start with case of no words in region.
12878 * Counting Exercise::
12879 @end menu
12881 @node Why Count Words, count-words-region, Counting Words, Counting Words
12882 @ifnottex
12883 @unnumberedsec Counting words
12884 @end ifnottex
12886 The standard Emacs distribution contains a function for counting the
12887 number of lines within a region.  However, there is no corresponding
12888 function for counting words.
12890 Certain types of writing ask you to count words.  Thus, if you write
12891 an essay, you may be limited to 800 words; if you write a novel, you
12892 may discipline yourself to write 1000 words a day.  It seems odd to me
12893 that Emacs lacks a word count command.  Perhaps people use Emacs
12894 mostly for code or types of documentation that do not require word
12895 counts; or perhaps they restrict themselves to the operating system
12896 word count command, @code{wc}.  Alternatively, people may follow
12897 the publishers' convention and compute a word count by dividing the
12898 number of characters in a document by five.  In any event, here are
12899 commands to count words.
12901 @node count-words-region, recursive-count-words, Why Count Words, Counting Words
12902 @comment  node-name,  next,  previous,  up
12903 @section The @code{count-words-region} Function
12904 @findex count-words-region
12906 A word count command could count words in a line, paragraph, region,
12907 or buffer.  What should the command cover?  You could design the
12908 command to count the number of words in a complete buffer.  However,
12909 the Emacs tradition encourages flexibility---you may want to count
12910 words in just a section, rather than all of a buffer.  So it makes
12911 more sense to design the command to count the number of words in a
12912 region.  Once you have a @code{count-words-region} command, you can,
12913 if you wish, count words in a whole buffer by marking it with @kbd{C-x
12914 h} (@code{mark-whole-buffer}).
12916 Clearly, counting words is a repetitive act: starting from the
12917 beginning of the region, you count the first word, then the second
12918 word, then the third word, and so on, until you reach the end of the
12919 region.  This means that word counting is ideally suited to recursion
12920 or to a @code{while} loop.
12922 @menu
12923 * Design count-words-region::   The definition using a @code{while} loop.
12924 * Whitespace Bug::              The Whitespace Bug in @code{count-words-region}.
12925 @end menu
12927 @node Design count-words-region, Whitespace Bug, count-words-region, count-words-region
12928 @ifnottex
12929 @unnumberedsubsec Designing @code{count-words-region}
12930 @end ifnottex
12932 First, we will implement the word count command with a @code{while}
12933 loop, then with recursion.  The command will, of course, be
12934 interactive.
12936 @need 800
12937 The template for an interactive function definition is, as always:
12939 @smallexample
12940 @group
12941 (defun @var{name-of-function} (@var{argument-list})
12942   "@var{documentation}@dots{}"
12943   (@var{interactive-expression}@dots{})
12944   @var{body}@dots{})
12945 @end group
12946 @end smallexample
12948 What we need to do is fill in the slots.
12950 The name of the function should be self-explanatory and similar to the
12951 existing @code{count-lines-region} name.  This makes the name easier
12952 to remember.  @code{count-words-region} is a good choice.
12954 The function counts words within a region.  This means that the
12955 argument list must contain symbols that are bound to the two
12956 positions, the beginning and end of the region.  These two positions
12957 can be called @samp{beginning} and @samp{end} respectively.  The first
12958 line of the documentation should be a single sentence, since that is
12959 all that is printed as documentation by a command such as
12960 @code{apropos}.  The interactive expression will be of the form
12961 @samp{(interactive "r")}, since that will cause Emacs to pass the
12962 beginning and end of the region to the function's argument list.  All
12963 this is routine.
12965 The body of the function needs to be written to do three tasks:
12966 first, to set up conditions under which the @code{while} loop can
12967 count words, second, to run the @code{while} loop, and third, to send
12968 a message to the user.
12970 When a user calls @code{count-words-region}, point may be at the
12971 beginning or the end of the region.  However, the counting process
12972 must start at the beginning of the region.  This means we will want
12973 to put point there if it is not already there.  Executing
12974 @code{(goto-char beginning)} ensures this.  Of course, we will want to
12975 return point to its expected position when the function finishes its
12976 work.  For this reason, the body must be enclosed in a
12977 @code{save-excursion} expression.
12979 The central part of the body of the function consists of a
12980 @code{while} loop in which one expression jumps point forward word by
12981 word, and another expression counts those jumps.  The true-or-false-test
12982 of the @code{while} loop should test true so long as point should jump
12983 forward, and false when point is at the end of the region.
12985 We could use @code{(forward-word 1)} as the expression for moving point
12986 forward word by word, but it is easier to see what Emacs identifies as a
12987 `word' if we use a regular expression search.
12989 A regular expression search that finds the pattern for which it is
12990 searching leaves point after the last character matched.  This means
12991 that a succession of successful word searches will move point forward
12992 word by word.
12994 As a practical matter, we want the regular expression search to jump
12995 over whitespace and punctuation between words as well as over the
12996 words themselves.  A regexp that refuses to jump over interword
12997 whitespace would never jump more than one word!  This means that
12998 the regexp should include the whitespace and punctuation that follows
12999 a word, if any, as well as the word itself.  (A word may end a buffer
13000 and not have any following whitespace or punctuation, so that part of
13001 the regexp must be optional.)
13003 Thus, what we want for the regexp is a pattern defining one or more
13004 word constituent characters followed, optionally, by one or more
13005 characters that are not word constituents.  The regular expression for
13006 this is:
13008 @smallexample
13009 \w+\W*
13010 @end smallexample
13012 @noindent
13013 The buffer's syntax table determines which characters are and are not
13014 word constituents.  (@xref{Syntax, , What Constitutes a Word or
13015 Symbol?}, for more about syntax.  Also, see @ref{Syntax, Syntax, The
13016 Syntax Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, ,
13017 Syntax Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
13019 @need 800
13020 The search expression looks like this:
13022 @smallexample
13023 (re-search-forward "\\w+\\W*")
13024 @end smallexample
13026 @noindent
13027 (Note that paired backslashes precede the @samp{w} and @samp{W}.  A
13028 single backslash has special meaning to the Emacs Lisp interpreter.  It
13029 indicates that the following character is interpreted differently than
13030 usual.  For example, the two characters, @samp{\n}, stand for
13031 @samp{newline}, rather than for a backslash followed by @samp{n}.  Two
13032 backslashes in a row stand for an ordinary, `unspecial' backslash.)
13034 We need a counter to count how many words there are; this variable
13035 must first be set to 0 and then incremented each time Emacs goes
13036 around the @code{while} loop.  The incrementing expression is simply:
13038 @smallexample
13039 (setq count (1+ count))
13040 @end smallexample
13042 Finally, we want to tell the user how many words there are in the
13043 region.  The @code{message} function is intended for presenting this
13044 kind of information to the user.  The message has to be phrased so
13045 that it reads properly regardless of how many words there are in the
13046 region: we don't want to say that ``there are 1 words in the region''.
13047 The conflict between singular and plural is ungrammatical.  We can
13048 solve this problem by using a conditional expression that evaluates
13049 different messages depending on the number of words in the region.
13050 There are three possibilities: no words in the region, one word in the
13051 region, and more than one word.  This means that the @code{cond}
13052 special form is appropriate.
13054 @need 1500
13055 All this leads to the following function definition:
13057 @smallexample
13058 @group
13059 ;;; @r{First version; has bugs!}
13060 (defun count-words-region (beginning end)
13061   "Print number of words in the region.
13062 Words are defined as at least one word-constituent
13063 character followed by at least one character that
13064 is not a word-constituent.  The buffer's syntax
13065 table determines which characters these are."
13066   (interactive "r")
13067   (message "Counting words in region ... ")
13068 @end group
13070 @group
13071 ;;; @r{1. Set up appropriate conditions.}
13072   (save-excursion
13073     (goto-char beginning)
13074     (let ((count 0))
13075 @end group
13077 @group
13078 ;;; @r{2. Run the} while @r{loop.}
13079       (while (< (point) end)
13080         (re-search-forward "\\w+\\W*")
13081         (setq count (1+ count)))
13082 @end group
13084 @group
13085 ;;; @r{3. Send a message to the user.}
13086       (cond ((zerop count)
13087              (message
13088               "The region does NOT have any words."))
13089             ((= 1 count)
13090              (message
13091               "The region has 1 word."))
13092             (t
13093              (message
13094               "The region has %d words." count))))))
13095 @end group
13096 @end smallexample
13098 @noindent
13099 As written, the function works, but not in all circumstances.
13101 @node Whitespace Bug,  , Design count-words-region, count-words-region
13102 @comment  node-name,  next,  previous,  up
13103 @subsection The Whitespace Bug in @code{count-words-region}
13105 The @code{count-words-region} command described in the preceding
13106 section has two bugs, or rather, one bug with two manifestations.
13107 First, if you mark a region containing only whitespace in the middle
13108 of some text, the @code{count-words-region} command tells you that the
13109 region contains one word!  Second, if you mark a region containing
13110 only whitespace at the end of the buffer or the accessible portion of
13111 a narrowed buffer, the command displays an error message that looks
13112 like this:
13114 @smallexample
13115 Search failed: "\\w+\\W*"
13116 @end smallexample
13118 If you are reading this in Info in GNU Emacs, you can test for these
13119 bugs yourself.
13121 First, evaluate the function in the usual manner to install it.
13122 @ifinfo
13123 Here is a copy of the definition.  Place your cursor after the closing
13124 parenthesis and type @kbd{C-x C-e} to install it.
13126 @smallexample
13127 @group
13128 ;; @r{First version; has bugs!}
13129 (defun count-words-region (beginning end)
13130   "Print number of words in the region.
13131 Words are defined as at least one word-constituent character followed
13132 by at least one character that is not a word-constituent.  The buffer's
13133 syntax table determines which characters these are."
13134 @end group
13135 @group
13136   (interactive "r")
13137   (message "Counting words in region ... ")
13138 @end group
13140 @group
13141 ;;; @r{1. Set up appropriate conditions.}
13142   (save-excursion
13143     (goto-char beginning)
13144     (let ((count 0))
13145 @end group
13147 @group
13148 ;;; @r{2. Run the} while @r{loop.}
13149       (while (< (point) end)
13150         (re-search-forward "\\w+\\W*")
13151         (setq count (1+ count)))
13152 @end group
13154 @group
13155 ;;; @r{3. Send a message to the user.}
13156       (cond ((zerop count)
13157              (message "The region does NOT have any words."))
13158             ((= 1 count) (message "The region has 1 word."))
13159             (t (message "The region has %d words." count))))))
13160 @end group
13161 @end smallexample
13162 @end ifinfo
13164 @need 1000
13165 If you wish, you can also install this keybinding by evaluating it:
13167 @smallexample
13168 (global-set-key "\C-c=" 'count-words-region)
13169 @end smallexample
13171 To conduct the first test, set mark and point to the beginning and end
13172 of the following line and then type @kbd{C-c =} (or @kbd{M-x
13173 count-words-region} if you have not bound @kbd{C-c =}):
13175 @smallexample
13176     one   two  three
13177 @end smallexample
13179 @noindent
13180 Emacs will tell you, correctly, that the region has three words.
13182 Repeat the test, but place mark at the beginning of the line and place
13183 point just @emph{before} the word @samp{one}.  Again type the command
13184 @kbd{C-c =} (or @kbd{M-x count-words-region}).  Emacs should tell you
13185 that the region has no words, since it is composed only of the
13186 whitespace at the beginning of the line.  But instead Emacs tells you
13187 that the region has one word!
13189 For the third test, copy the sample line to the end of the
13190 @file{*scratch*} buffer and then type several spaces at the end of the
13191 line.  Place mark right after the word @samp{three} and point at the
13192 end of line.  (The end of the line will be the end of the buffer.)
13193 Type @kbd{C-c =} (or @kbd{M-x count-words-region}) as you did before.
13194 Again, Emacs should tell you that the region has no words, since it is
13195 composed only of the whitespace at the end of the line.  Instead,
13196 Emacs displays an error message saying @samp{Search failed}.
13198 The two bugs stem from the same problem.
13200 Consider the first manifestation of the bug, in which the command
13201 tells you that the whitespace at the beginning of the line contains
13202 one word.  What happens is this: The @code{M-x count-words-region}
13203 command moves point to the beginning of the region.  The @code{while}
13204 tests whether the value of point is smaller than the value of
13205 @code{end}, which it is.  Consequently, the regular expression search
13206 looks for and finds the first word.  It leaves point after the word.
13207 @code{count} is set to one.  The @code{while} loop repeats; but this
13208 time the value of point is larger than the value of @code{end}, the
13209 loop is exited; and the function displays a message saying the number
13210 of words in the region is one.  In brief, the regular expression
13211 search looks for and finds the word even though it is outside
13212 the marked region.
13214 In the second manifestation of the bug, the region is whitespace at
13215 the end of the buffer.  Emacs says @samp{Search failed}.  What happens
13216 is that the true-or-false-test in the @code{while} loop tests true, so
13217 the search expression is executed.  But since there are no more words
13218 in the buffer, the search fails.
13220 In both manifestations of the bug, the search extends or attempts to
13221 extend outside of the region.
13223 The solution is to limit the search to the region---this is a fairly
13224 simple action, but as you may have come to expect, it is not quite as
13225 simple as you might think.
13227 As we have seen, the @code{re-search-forward} function takes a search
13228 pattern as its first argument.  But in addition to this first,
13229 mandatory argument, it accepts three optional arguments.  The optional
13230 second argument bounds the search.  The optional third argument, if
13231 @code{t}, causes the function to return @code{nil} rather than signal
13232 an error if the search fails.  The optional fourth argument is a
13233 repeat count.  (In Emacs, you can see a function's documentation by
13234 typing @kbd{C-h f}, the name of the function, and then @key{RET}.)
13236 In the @code{count-words-region} definition, the value of the end of
13237 the region is held by the variable @code{end} which is passed as an
13238 argument to the function.  Thus, we can add @code{end} as an argument
13239 to the regular expression search expression:
13241 @smallexample
13242 (re-search-forward "\\w+\\W*" end)
13243 @end smallexample
13245 However, if you make only this change to the @code{count-words-region}
13246 definition and then test the new version of the definition on a
13247 stretch of whitespace, you will receive an error message saying
13248 @samp{Search failed}.
13250 What happens is this: the search is limited to the region, and fails
13251 as you expect because there are no word-constituent characters in the
13252 region.  Since it fails, we receive an error message.  But we do not
13253 want to receive an error message in this case; we want to receive the
13254 message that "The region does NOT have any words."
13256 The solution to this problem is to provide @code{re-search-forward}
13257 with a third argument of @code{t}, which causes the function to return
13258 @code{nil} rather than signal an error if the search fails.
13260 However, if you make this change and try it, you will see the message
13261 ``Counting words in region ... '' and @dots{} you will keep on seeing
13262 that message @dots{}, until you type @kbd{C-g} (@code{keyboard-quit}).
13264 Here is what happens: the search is limited to the region, as before,
13265 and it fails because there are no word-constituent characters in the
13266 region, as expected.  Consequently, the @code{re-search-forward}
13267 expression returns @code{nil}.  It does nothing else.  In particular,
13268 it does not move point, which it does as a side effect if it finds the
13269 search target.  After the @code{re-search-forward} expression returns
13270 @code{nil}, the next expression in the @code{while} loop is evaluated.
13271 This expression increments the count.  Then the loop repeats.  The
13272 true-or-false-test tests true because the value of point is still less
13273 than the value of end, since the @code{re-search-forward} expression
13274 did not move point. @dots{} and the cycle repeats @dots{}
13276 The @code{count-words-region} definition requires yet another
13277 modification, to cause the true-or-false-test of the @code{while} loop
13278 to test false if the search fails.  Put another way, there are two
13279 conditions that must be satisfied in the true-or-false-test before the
13280 word count variable is incremented: point must still be within the
13281 region and the search expression must have found a word to count.
13283 Since both the first condition and the second condition must be true
13284 together, the two expressions, the region test and the search
13285 expression, can be joined with an @code{and} special form and embedded in
13286 the @code{while} loop as the true-or-false-test, like this:
13288 @smallexample
13289 (and (< (point) end) (re-search-forward "\\w+\\W*" end t))
13290 @end smallexample
13292 @c colon in printed section title causes problem in Info cross reference
13293 @c also trouble with an overfull hbox
13294 @iftex
13295 @noindent
13296 (For information about @code{and}, see
13297 @ref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
13298 Functions}.)
13299 @end iftex
13300 @ifinfo
13301 @noindent
13302 (@xref{forward-paragraph}, for information about @code{and}.)
13303 @end ifinfo
13305 The @code{re-search-forward} expression returns @code{t} if the search
13306 succeeds and as a side effect moves point.  Consequently, as words are
13307 found, point is moved through the region.  When the search
13308 expression fails to find another word, or when point reaches the end
13309 of the region, the true-or-false-test tests false, the @code{while}
13310 loop exists, and the @code{count-words-region} function displays one
13311 or other of its messages.
13313 After incorporating these final changes, the @code{count-words-region}
13314 works without bugs (or at least, without bugs that I have found!).
13315 Here is what it looks like:
13317 @smallexample
13318 @group
13319 ;;; @r{Final version:} @code{while}
13320 (defun count-words-region (beginning end)
13321   "Print number of words in the region."
13322   (interactive "r")
13323   (message "Counting words in region ... ")
13324 @end group
13326 @group
13327 ;;; @r{1. Set up appropriate conditions.}
13328   (save-excursion
13329     (let ((count 0))
13330       (goto-char beginning)
13331 @end group
13333 @group
13334 ;;; @r{2. Run the} while @r{loop.}
13335       (while (and (< (point) end)
13336                   (re-search-forward "\\w+\\W*" end t))
13337         (setq count (1+ count)))
13338 @end group
13340 @group
13341 ;;; @r{3. Send a message to the user.}
13342       (cond ((zerop count)
13343              (message
13344               "The region does NOT have any words."))
13345             ((= 1 count)
13346              (message
13347               "The region has 1 word."))
13348             (t
13349              (message
13350               "The region has %d words." count))))))
13351 @end group
13352 @end smallexample
13354 @node recursive-count-words, Counting Exercise, count-words-region, Counting Words
13355 @comment  node-name,  next,  previous,  up
13356 @section Count Words Recursively
13357 @cindex Count words recursively
13358 @cindex Recursively counting words
13359 @cindex Words, counted recursively
13361 You can write the function for counting words recursively as well as
13362 with a @code{while} loop.  Let's see how this is done.
13364 First, we need to recognize that the @code{count-words-region}
13365 function has three jobs: it sets up the appropriate conditions for
13366 counting to occur; it counts the words in the region; and it sends a
13367 message to the user telling how many words there are.
13369 If we write a single recursive function to do everything, we will
13370 receive a message for every recursive call.  If the region contains 13
13371 words, we will receive thirteen messages, one right after the other.
13372 We don't want this!  Instead, we must write two functions to do the
13373 job, one of which (the recursive function) will be used inside of the
13374 other.  One function will set up the conditions and display the
13375 message; the other will return the word count.
13377 Let us start with the function that causes the message to be displayed.
13378 We can continue to call this @code{count-words-region}.
13380 This is the function that the user will call.  It will be interactive.
13381 Indeed, it will be similar to our previous versions of this
13382 function, except that it will call @code{recursive-count-words} to
13383 determine how many words are in the region.
13385 @need 1250
13386 We can readily construct a template for this function, based on our
13387 previous versions:
13389 @smallexample
13390 @group
13391 ;; @r{Recursive version; uses regular expression search}
13392 (defun count-words-region (beginning end)
13393   "@var{documentation}@dots{}"
13394   (@var{interactive-expression}@dots{})
13395 @end group
13396 @group
13398 ;;; @r{1. Set up appropriate conditions.}
13399   (@var{explanatory message})
13400   (@var{set-up functions}@dots{}
13401 @end group
13402 @group
13404 ;;; @r{2. Count the words.}
13405     @var{recursive call}
13406 @end group
13407 @group
13409 ;;; @r{3. Send a message to the user.}
13410     @var{message providing word count}))
13411 @end group
13412 @end smallexample
13414 The definition looks straightforward, except that somehow the count
13415 returned by the recursive call must be passed to the message
13416 displaying the word count.  A little thought suggests that this can be
13417 done by making use of a @code{let} expression: we can bind a variable
13418 in the varlist of a @code{let} expression to the number of words in
13419 the region, as returned by the recursive call; and then the
13420 @code{cond} expression, using binding, can display the value to the
13421 user.
13423 Often, one thinks of the binding within a @code{let} expression as
13424 somehow secondary to the `primary' work of a function.  But in this
13425 case, what you might consider the `primary' job of the function,
13426 counting words, is done within the @code{let} expression.
13428 @need 1250
13429 Using @code{let}, the function definition looks like this:
13431 @smallexample
13432 @group
13433 (defun count-words-region (beginning end)
13434   "Print number of words in the region."
13435   (interactive "r")
13436 @end group
13438 @group
13439 ;;; @r{1. Set up appropriate conditions.}
13440   (message "Counting words in region ... ")
13441   (save-excursion
13442     (goto-char beginning)
13443 @end group
13445 @group
13446 ;;; @r{2. Count the words.}
13447     (let ((count (recursive-count-words end)))
13448 @end group
13450 @group
13451 ;;; @r{3. Send a message to the user.}
13452       (cond ((zerop count)
13453              (message
13454               "The region does NOT have any words."))
13455             ((= 1 count)
13456              (message
13457               "The region has 1 word."))
13458             (t
13459              (message
13460               "The region has %d words." count))))))
13461 @end group
13462 @end smallexample
13464 Next, we need to write the recursive counting function.
13466 A recursive function has at least three parts: the `do-again-test', the
13467 `next-step-expression', and the recursive call.
13469 The do-again-test determines whether the function will or will not be
13470 called again.  Since we are counting words in a region and can use a
13471 function that moves point forward for every word, the do-again-test
13472 can check whether point is still within the region.  The do-again-test
13473 should find the value of point and determine whether point is before,
13474 at, or after the value of the end of the region.  We can use the
13475 @code{point} function to locate point.  Clearly, we must pass the
13476 value of the end of the region to the recursive counting function as an
13477 argument.
13479 In addition, the do-again-test should also test whether the search finds a
13480 word.  If it does not, the function should not call itself again.
13482 The next-step-expression changes a value so that when the recursive
13483 function is supposed to stop calling itself, it stops.  More
13484 precisely, the next-step-expression changes a value so that at the
13485 right time, the do-again-test stops the recursive function from
13486 calling itself again.  In this case, the next-step-expression can be
13487 the expression that moves point forward, word by word.
13489 The third part of a recursive function is the recursive call.
13491 Somewhere, also, we also need a part that does the `work' of the
13492 function, a part that does the counting.  A vital part!
13494 @need 1250
13495 But already, we have an outline of the recursive counting function:
13497 @smallexample
13498 @group
13499 (defun recursive-count-words (region-end)
13500   "@var{documentation}@dots{}"
13501    @var{do-again-test}
13502    @var{next-step-expression}
13503    @var{recursive call})
13504 @end group
13505 @end smallexample
13507 Now we need to fill in the slots.  Let's start with the simplest cases
13508 first:  if point is at or beyond the end of the region, there cannot
13509 be any words in the region, so the function should return zero.
13510 Likewise, if the search fails, there are no words to count, so the
13511 function should return zero.
13513 On the other hand, if point is within the region and the search
13514 succeeds, the function should call itself again.
13516 @need 800
13517 Thus, the do-again-test should look like this:
13519 @smallexample
13520 @group
13521 (and (< (point) region-end)
13522      (re-search-forward "\\w+\\W*" region-end t))
13523 @end group
13524 @end smallexample
13526 Note that the search expression is part of the do-again-test---the
13527 function returns @code{t} if its search succeeds and @code{nil} if it
13528 fails.  (@xref{Whitespace Bug, , The Whitespace Bug in
13529 @code{count-words-region}}, for an explanation of how
13530 @code{re-search-forward} works.)
13532 The do-again-test is the true-or-false test of an @code{if} clause.
13533 Clearly, if the do-again-test succeeds, the then-part of the @code{if}
13534 clause should call the function again; but if it fails, the else-part
13535 should return zero since either point is outside the region or the
13536 search failed because there were no words to find.
13538 But before considering the recursive call, we need to consider the
13539 next-step-expression.  What is it?  Interestingly, it is the search
13540 part of the do-again-test.
13542 In addition to returning @code{t} or @code{nil} for the
13543 do-again-test, @code{re-search-forward} moves point forward as a side
13544 effect of a successful search.  This is the action that changes the
13545 value of point so that the recursive function stops calling itself
13546 when point completes its movement through the region.  Consequently,
13547 the @code{re-search-forward} expression is the next-step-expression.
13549 @need 1200
13550 In outline, then, the body of the @code{recursive-count-words}
13551 function looks like this:
13553 @smallexample
13554 @group
13555 (if @var{do-again-test-and-next-step-combined}
13556     ;; @r{then}
13557     @var{recursive-call-returning-count}
13558   ;; @r{else}
13559   @var{return-zero})
13560 @end group
13561 @end smallexample
13563 How to incorporate the mechanism that counts?
13565 If you are not used to writing recursive functions, a question like
13566 this can be troublesome.  But it can and should be approached
13567 systematically.
13569 We know that the counting mechanism should be associated in some way
13570 with the recursive call.  Indeed, since the next-step-expression moves
13571 point forward by one word, and since a recursive call is made for
13572 each word, the counting mechanism must be an expression that adds one
13573 to the value returned by a call to @code{recursive-count-words}.
13575 Consider several cases:
13577 @itemize @bullet
13578 @item
13579 If there are two words in the region, the function should return
13580 a value resulting from adding one to the value returned when it counts
13581 the first word, plus the number returned when it counts the remaining
13582 words in the region, which in this case is one.
13584 @item
13585 If there is one word in the region, the function should return
13586 a value resulting from adding one to the value returned when it counts
13587 that word, plus the number returned when it counts the remaining
13588 words in the region, which in this case is zero.
13590 @item
13591 If there are no words in the region, the function should return zero.
13592 @end itemize
13594 From the sketch we can see that the else-part of the @code{if} returns
13595 zero for the case of no words.  This means that the then-part of the
13596 @code{if} must return a value resulting from adding one to the value
13597 returned from a count of the remaining words.
13599 @need 1200
13600 The expression will look like this, where @code{1+} is a function that
13601 adds one to its argument.
13603 @smallexample
13604 (1+ (recursive-count-words region-end))
13605 @end smallexample
13607 @need 1200
13608 The whole @code{recursive-count-words} function will then look like
13609 this:
13611 @smallexample
13612 @group
13613 (defun recursive-count-words (region-end)
13614   "@var{documentation}@dots{}"
13616 ;;; @r{1. do-again-test}
13617   (if (and (< (point) region-end)
13618            (re-search-forward "\\w+\\W*" region-end t))
13619 @end group
13621 @group
13622 ;;; @r{2. then-part: the recursive call}
13623       (1+ (recursive-count-words region-end))
13625 ;;; @r{3. else-part}
13626     0))
13627 @end group
13628 @end smallexample
13630 @need 1250
13631 Let's examine how this works:
13633 If there are no words in the region, the else part of the @code{if}
13634 expression is evaluated and consequently the function returns zero.
13636 If there is one word in the region, the value of point is less than
13637 the value of @code{region-end} and the search succeeds.  In this case,
13638 the true-or-false-test of the @code{if} expression tests true, and the
13639 then-part of the @code{if} expression is evaluated.  The counting
13640 expression is evaluated.  This expression returns a value (which will
13641 be the value returned by the whole function) that is the sum of one
13642 added to the value returned by a recursive call.
13644 Meanwhile, the next-step-expression has caused point to jump over the
13645 first (and in this case only) word in the region.  This means that
13646 when @code{(recursive-count-words region-end)} is evaluated a second
13647 time, as a result of the recursive call, the value of point will be
13648 equal to or greater than the value of region end.  So this time,
13649 @code{recursive-count-words} will return zero.  The zero will be added
13650 to one, and the original evaluation of @code{recursive-count-words}
13651 will return one plus zero, which is one, which is the correct amount.
13653 Clearly, if there are two words in the region, the first call to
13654 @code{recursive-count-words} returns one added to the value returned
13655 by calling @code{recursive-count-words} on a region containing the
13656 remaining word---that is, it adds one to one, producing two, which is
13657 the correct amount.
13659 Similarly, if there are three words in the region, the first call to
13660 @code{recursive-count-words} returns one added to the value returned
13661 by calling @code{recursive-count-words} on a region containing the
13662 remaining two words---and so on and so on.
13664 @need 1250
13665 @noindent
13666 With full documentation the two functions look like this:
13668 @need 1250
13669 @noindent
13670 The recursive function:
13672 @findex recursive-count-words
13673 @smallexample
13674 @group
13675 (defun recursive-count-words (region-end)
13676   "Number of words between point and REGION-END."
13677 @end group
13679 @group
13680 ;;; @r{1. do-again-test}
13681   (if (and (< (point) region-end)
13682            (re-search-forward "\\w+\\W*" region-end t))
13683 @end group
13685 @group
13686 ;;; @r{2. then-part: the recursive call}
13687       (1+ (recursive-count-words region-end))
13689 ;;; @r{3. else-part}
13690     0))
13691 @end group
13692 @end smallexample
13694 @need 800
13695 @noindent
13696 The wrapper:
13698 @smallexample
13699 @group
13700 ;;; @r{Recursive version}
13701 (defun count-words-region (beginning end)
13702   "Print number of words in the region.
13703 @end group
13705 @group
13706 Words are defined as at least one word-constituent
13707 character followed by at least one character that is
13708 not a word-constituent.  The buffer's syntax table
13709 determines which characters these are."
13710 @end group
13711 @group
13712   (interactive "r")
13713   (message "Counting words in region ... ")
13714   (save-excursion
13715     (goto-char beginning)
13716     (let ((count (recursive-count-words end)))
13717 @end group
13718 @group
13719       (cond ((zerop count)
13720              (message
13721               "The region does NOT have any words."))
13722 @end group
13723 @group
13724             ((= 1 count)
13725              (message "The region has 1 word."))
13726             (t
13727              (message
13728               "The region has %d words." count))))))
13729 @end group
13730 @end smallexample
13732 @node Counting Exercise,  , recursive-count-words, Counting Words
13733 @section Exercise: Counting Punctuation
13735 Using a @code{while} loop, write a function to count the number of
13736 punctuation marks in a region---period, comma, semicolon, colon,
13737 exclamation mark, and question mark.  Do the same using recursion.
13739 @node Words in a defun, Readying a Graph, Counting Words, Top
13740 @chapter Counting Words in a @code{defun}
13741 @cindex Counting words in a @code{defun}
13742 @cindex Word counting in a @code{defun}
13744 Our next project is to count the number of words in a function
13745 definition.  Clearly, this can be done using some variant of
13746 @code{count-word-region}.  @xref{Counting Words, , Counting Words:
13747 Repetition and Regexps}.  If we are just going to count the words in
13748 one definition, it is easy enough to mark the definition with the
13749 @kbd{C-M-h} (@code{mark-defun}) command, and then call
13750 @code{count-word-region}.
13752 However, I am more ambitious: I want to count the words and symbols in
13753 every definition in the Emacs sources and then print a graph that
13754 shows how many functions there are of each length: how many contain 40
13755 to 49 words or symbols, how many contain 50 to 59 words or symbols,
13756 and so on.  I have often been curious how long a typical function is,
13757 and this will tell.
13759 @menu
13760 * Divide and Conquer::
13761 * Words and Symbols::           What to count?
13762 * Syntax::                      What constitutes a word or symbol?
13763 * count-words-in-defun::        Very like @code{count-words}.
13764 * Several defuns::              Counting several defuns in a file.
13765 * Find a File::                 Do you want to look at a file?
13766 * lengths-list-file::           A list of the lengths of many definitions.
13767 * Several files::               Counting in definitions in different files.
13768 * Several files recursively::   Recursively counting in different files.
13769 * Prepare the data::            Prepare the data for display in a graph.
13770 @end menu
13772 @node Divide and Conquer, Words and Symbols, Words in a defun, Words in a defun
13773 @ifnottex
13774 @unnumberedsec Divide and Conquer
13775 @end ifnottex
13777 Described in one phrase, the histogram project is daunting; but
13778 divided into numerous small steps, each of which we can take one at a
13779 time, the project becomes less fearsome.  Let us consider what the
13780 steps must be:
13782 @itemize @bullet
13783 @item
13784 First, write a function to count the words in one definition.  This
13785 includes the problem of handling symbols as well as words.
13787 @item
13788 Second, write a function to list the numbers of words in each function
13789 in a file.  This function can use the @code{count-words-in-defun}
13790 function.
13792 @item
13793 Third, write a function to list the numbers of words in each function
13794 in each of several files.  This entails automatically finding the
13795 various files, switching to them, and counting the words in the
13796 definitions within them.
13798 @item
13799 Fourth, write a function to convert the list of numbers that we
13800 created in step three to a form that will be suitable for printing as
13801 a graph.
13803 @item
13804 Fifth, write a function to print the results as a graph.
13805 @end itemize
13807 This is quite a project!  But if we take each step slowly, it will not
13808 be difficult.
13810 @node Words and Symbols, Syntax, Divide and Conquer, Words in a defun
13811 @section What to Count?
13812 @cindex Words and symbols in defun
13814 When we first start thinking about how to count the words in a
13815 function definition, the first question is (or ought to be) what are
13816 we going to count?  When we speak of `words' with respect to a Lisp
13817 function definition, we are actually speaking, in large part, of
13818 `symbols'.  For example, the following @code{multiply-by-seven}
13819 function contains the five symbols @code{defun},
13820 @code{multiply-by-seven}, @code{number}, @code{*}, and @code{7}.  In
13821 addition, in the documentation string, it contains the four words
13822 @samp{Multiply}, @samp{NUMBER}, @samp{by}, and @samp{seven}.  The
13823 symbol @samp{number} is repeated, so the definition contains a total
13824 of ten words and symbols.
13826 @smallexample
13827 @group
13828 (defun multiply-by-seven (number)
13829   "Multiply NUMBER by seven."
13830   (* 7 number))
13831 @end group
13832 @end smallexample
13834 @noindent
13835 However, if we mark the @code{multiply-by-seven} definition with
13836 @kbd{C-M-h} (@code{mark-defun}), and then call
13837 @code{count-words-region} on it, we will find that
13838 @code{count-words-region} claims the definition has eleven words, not
13839 ten!  Something is wrong!
13841 The problem is twofold: @code{count-words-region} does not count the
13842 @samp{*} as a word, and it counts the single symbol,
13843 @code{multiply-by-seven}, as containing three words.  The hyphens are
13844 treated as if they were interword spaces rather than intraword
13845 connectors: @samp{multiply-by-seven} is counted as if it were written
13846 @samp{multiply by seven}.
13848 The cause of this confusion is the regular expression search within
13849 the @code{count-words-region} definition that moves point forward word
13850 by word.  In the canonical version of @code{count-words-region}, the
13851 regexp is:
13853 @smallexample
13854 "\\w+\\W*"
13855 @end smallexample
13857 @noindent
13858 This regular expression is a pattern defining one or more word
13859 constituent characters possibly followed by one or more characters
13860 that are not word constituents.  What is meant by `word constituent
13861 characters' brings us to the issue of syntax, which is worth a section
13862 of its own.
13864 @node Syntax, count-words-in-defun, Words and Symbols, Words in a defun
13865 @section What Constitutes a Word or Symbol?
13866 @cindex Syntax categories and tables
13868 Emacs treats different characters as belonging to different
13869 @dfn{syntax categories}.  For example, the regular expression,
13870 @samp{\\w+}, is a pattern specifying one or more @emph{word
13871 constituent} characters.  Word constituent characters are members of
13872 one syntax category.  Other syntax categories include the class of
13873 punctuation characters, such as the period and the comma, and the
13874 class of whitespace characters, such as the blank space and the tab
13875 character.  (For more information, see @ref{Syntax, Syntax, The Syntax
13876 Table, emacs, The GNU Emacs Manual}, and @ref{Syntax Tables, , Syntax
13877 Tables, elisp, The GNU Emacs Lisp Reference Manual}.)
13879 Syntax tables specify which characters belong to which categories.
13880 Usually, a hyphen is not specified as a `word constituent character'.
13881 Instead, it is specified as being in the `class of characters that are
13882 part of symbol names but not words.'  This means that the
13883 @code{count-words-region} function treats it in the same way it treats
13884 an interword white space, which is why @code{count-words-region}
13885 counts @samp{multiply-by-seven} as three words.
13887 There are two ways to cause Emacs to count @samp{multiply-by-seven} as
13888 one symbol: modify the syntax table or modify the regular expression.
13890 We could redefine a hyphen as a word constituent character by
13891 modifying the syntax table that Emacs keeps for each mode.  This
13892 action would serve our purpose, except that a hyphen is merely the
13893 most common character within symbols that is not typically a word
13894 constituent character; there are others, too.
13896 Alternatively, we can redefine the regular expression used in the
13897 @code{count-words} definition so as to include symbols.  This
13898 procedure has the merit of clarity, but the task is a little tricky.
13900 @need 1200
13901 The first part is simple enough: the pattern must match ``at least one
13902 character that is a word or symbol constituent''.  Thus:
13904 @smallexample
13905 "\\(\\w\\|\\s_\\)+"
13906 @end smallexample
13908 @noindent
13909 The @samp{\\(} is the first part of the grouping construct that
13910 includes the @samp{\\w} and the @samp{\\s_} as alternatives, separated
13911 by the @samp{\\|}.  The @samp{\\w} matches any word-constituent
13912 character and the @samp{\\s_} matches any character that is part of a
13913 symbol name but not a word-constituent character.  The @samp{+}
13914 following the group indicates that the word or symbol constituent
13915 characters must be matched at least once.
13917 However, the second part of the regexp is more difficult to design.
13918 What we want is to follow the first part with ``optionally one or more
13919 characters that are not constituents of a word or symbol''.  At first,
13920 I thought I could define this with the following:
13922 @smallexample
13923 "\\(\\W\\|\\S_\\)*"
13924 @end smallexample
13926 @noindent
13927 The upper case @samp{W} and @samp{S} match characters that are
13928 @emph{not} word or symbol constituents.  Unfortunately, this
13929 expression matches any character that is either not a word constituent
13930 or not a symbol constituent.  This matches any character!
13932 I then noticed that every word or symbol in my test region was
13933 followed by white space (blank space, tab, or newline).  So I tried
13934 placing a pattern to match one or more blank spaces after the pattern
13935 for one or more word or symbol constituents.  This failed, too.  Words
13936 and symbols are often separated by whitespace, but in actual code
13937 parentheses may follow symbols and punctuation may follow words.  So
13938 finally, I designed a pattern in which the word or symbol constituents
13939 are followed optionally by characters that are not white space and
13940 then followed optionally by white space.
13942 @need 800
13943 Here is the full regular expression:
13945 @smallexample
13946 "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
13947 @end smallexample
13949 @node count-words-in-defun, Several defuns, Syntax, Words in a defun
13950 @section The @code{count-words-in-defun} Function
13951 @cindex Counting words in a @code{defun}
13953 We have seen that there are several ways to write a
13954 @code{count-word-region} function.  To write a
13955 @code{count-words-in-defun}, we need merely adapt one of these
13956 versions.
13958 The version that uses a @code{while} loop is easy to understand, so I
13959 am going to adapt that.  Because @code{count-words-in-defun} will be
13960 part of a more complex program, it need not be interactive and it need
13961 not display a message but just return the count.  These considerations
13962 simplify the definition a little.
13964 On the other hand, @code{count-words-in-defun} will be used within a
13965 buffer that contains function definitions.  Consequently, it is
13966 reasonable to ask that the function determine whether it is called
13967 when point is within a function definition, and if it is, to return
13968 the count for that definition.  This adds complexity to the
13969 definition, but saves us from needing to pass arguments to the
13970 function.
13972 @need 1250
13973 These considerations lead us to prepare the following template:
13975 @smallexample
13976 @group
13977 (defun count-words-in-defun ()
13978   "@var{documentation}@dots{}"
13979   (@var{set up}@dots{}
13980      (@var{while loop}@dots{})
13981    @var{return count})
13982 @end group
13983 @end smallexample
13985 @noindent
13986 As usual, our job is to fill in the slots.
13988 First, the set up.
13990 We are presuming that this function will be called within a buffer
13991 containing function definitions.  Point will either be within a
13992 function definition or not.  For @code{count-words-in-defun} to work,
13993 point must move to the beginning of the definition, a counter must
13994 start at zero, and the counting loop must stop when point reaches the
13995 end of the definition.
13997 The @code{beginning-of-defun} function searches backwards for an
13998 opening delimiter such as a @samp{(} at the beginning of a line, and
13999 moves point to that position, or else to the limit of the search.  In
14000 practice, this means that @code{beginning-of-defun} moves point to the
14001 beginning of an enclosing or preceding function definition, or else to
14002 the beginning of the buffer.  We can use @code{beginning-of-defun} to
14003 place point where we wish to start.
14005 The @code{while} loop requires a counter to keep track of the words or
14006 symbols being counted.  A @code{let} expression can be used to create
14007 a local variable for this purpose, and bind it to an initial value of zero.
14009 The @code{end-of-defun} function works like @code{beginning-of-defun}
14010 except that it moves point to the end of the definition.
14011 @code{end-of-defun} can be used as part of an expression that
14012 determines the position of the end of the definition.
14014 The set up for @code{count-words-in-defun} takes shape rapidly: first
14015 we move point to the beginning of the definition, then we create a
14016 local variable to hold the count, and finally, we record the position
14017 of the end of the definition so the @code{while} loop will know when to stop
14018 looping.
14020 @need 1250
14021 The code looks like this:
14023 @smallexample
14024 @group
14025 (beginning-of-defun)
14026 (let ((count 0)
14027       (end (save-excursion (end-of-defun) (point))))
14028 @end group
14029 @end smallexample
14031 @noindent
14032 The code is simple.  The only slight complication is likely to concern
14033 @code{end}: it is bound to the position of the end of the definition
14034 by a @code{save-excursion} expression that returns the value of point
14035 after @code{end-of-defun} temporarily moves it to the end of the
14036 definition.
14038 The second part of the @code{count-words-in-defun}, after the set up,
14039 is the @code{while} loop.
14041 The loop must contain an expression that jumps point forward word by
14042 word and symbol by symbol, and another expression that counts the
14043 jumps.  The true-or-false-test for the @code{while} loop should test
14044 true so long as point should jump forward, and false when point is at
14045 the end of the definition.  We have already redefined the regular
14046 expression for this (@pxref{Syntax}), so the loop is straightforward:
14048 @smallexample
14049 @group
14050 (while (and (< (point) end)
14051             (re-search-forward
14052              "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*" end t)
14053   (setq count (1+ count)))
14054 @end group
14055 @end smallexample
14057 The third part of the function definition returns the count of words
14058 and symbols.  This part is the last expression within the body of the
14059 @code{let} expression, and can be, very simply, the local variable
14060 @code{count}, which when evaluated returns the count.
14062 @need 1250
14063 Put together, the @code{count-words-in-defun} definition looks like this:
14065 @findex count-words-in-defun
14066 @smallexample
14067 @group
14068 (defun count-words-in-defun ()
14069   "Return the number of words and symbols in a defun."
14070   (beginning-of-defun)
14071   (let ((count 0)
14072         (end (save-excursion (end-of-defun) (point))))
14073 @end group
14074 @group
14075     (while
14076         (and (< (point) end)
14077              (re-search-forward
14078               "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
14079               end t))
14080       (setq count (1+ count)))
14081     count))
14082 @end group
14083 @end smallexample
14085 How to test this?  The function is not interactive, but it is easy to
14086 put a wrapper around the function to make it interactive; we can use
14087 almost the same code as for the recursive version of
14088 @code{count-words-region}:
14090 @smallexample
14091 @group
14092 ;;; @r{Interactive version.}
14093 (defun count-words-defun ()
14094   "Number of words and symbols in a function definition."
14095   (interactive)
14096   (message
14097    "Counting words and symbols in function definition ... ")
14098 @end group
14099 @group
14100   (let ((count (count-words-in-defun)))
14101     (cond
14102      ((zerop count)
14103       (message
14104        "The definition does NOT have any words or symbols."))
14105 @end group
14106 @group
14107      ((= 1 count)
14108       (message
14109        "The definition has 1 word or symbol."))
14110      (t
14111       (message
14112        "The definition has %d words or symbols." count)))))
14113 @end group
14114 @end smallexample
14116 @need 800
14117 @noindent
14118 Let's re-use @kbd{C-c =} as a convenient keybinding:
14120 @smallexample
14121 (global-set-key "\C-c=" 'count-words-defun)
14122 @end smallexample
14124 Now we can try out @code{count-words-defun}: install both
14125 @code{count-words-in-defun} and @code{count-words-defun}, and set the
14126 keybinding, and then place the cursor within the following definition:
14128 @smallexample
14129 @group
14130 (defun multiply-by-seven (number)
14131   "Multiply NUMBER by seven."
14132   (* 7 number))
14133      @result{} 10
14134 @end group
14135 @end smallexample
14137 @noindent
14138 Success!  The definition has 10 words and symbols.
14140 The next problem is to count the numbers of words and symbols in
14141 several definitions within a single file.
14143 @node Several defuns, Find a File, count-words-in-defun, Words in a defun
14144 @section Count Several @code{defuns} Within a File
14146 A file such as @file{simple.el} may have 80 or more function
14147 definitions within it.  Our long term goal is to collect statistics on
14148 many files, but as a first step, our immediate goal is to collect
14149 statistics on one file.
14151 The information will be a series of numbers, each number being the
14152 length of a function definition.  We can store the numbers in a list.
14154 We know that we will want to incorporate the information regarding one
14155 file with information about many other files; this means that the
14156 function for counting definition lengths within one file need only
14157 return the list of lengths.  It need not and should not display any
14158 messages.
14160 The word count commands contain one expression to jump point forward
14161 word by word and another expression to count the jumps.  The function
14162 to return the lengths of definitions can be designed to work the same
14163 way, with one expression to jump point forward definition by
14164 definition and another expression to construct the lengths' list.
14166 This statement of the problem makes it elementary to write the
14167 function definition.  Clearly, we will start the count at the
14168 beginning of the file, so the first command will be @code{(goto-char
14169 (point-min))}.  Next, we start the @code{while} loop; and the
14170 true-or-false test of the loop can be a regular expression search for
14171 the next function definition---so long as the search succeeds, point
14172 is moved forward and then the body of the loop is evaluated.  The body
14173 needs an expression that constructs the lengths' list.  @code{cons},
14174 the list construction command, can be used to create the list.  That
14175 is almost all there is to it.
14177 @need 800
14178 Here is what this fragment of code looks like:
14180 @smallexample
14181 @group
14182 (goto-char (point-min))
14183 (while (re-search-forward "^(defun" nil t)
14184   (setq lengths-list
14185         (cons (count-words-in-defun) lengths-list)))
14186 @end group
14187 @end smallexample
14189 What we have left out is the mechanism for finding the file that
14190 contains the function definitions.
14192 In previous examples, we either used this, the Info file, or we
14193 switched back and forth to some other buffer, such as the
14194 @file{*scratch*} buffer.
14196 Finding a file is a new process that we have not yet discussed.
14198 @node Find a File, lengths-list-file, Several defuns, Words in a defun
14199 @comment  node-name,  next,  previous,  up
14200 @section Find a File
14201 @cindex Find a File
14203 To find a file in Emacs, you use the @kbd{C-x C-f} (@code{find-file})
14204 command.  This command is almost, but not quite right for the lengths
14205 problem.
14207 @need 1200
14208 Let's look at the source for @code{find-file} (you can use the
14209 @code{find-tag} command or @kbd{C-h f} (@code{describe-function}) to
14210 find the source of a function):
14212 @smallexample
14213 @group
14214 (defun find-file (filename)
14215   "Edit file FILENAME.
14216 Switch to a buffer visiting file FILENAME,
14217 creating one if none already exists."
14218   (interactive "FFind file: ")
14219   (switch-to-buffer (find-file-noselect filename)))
14220 @end group
14221 @end smallexample
14223 The definition possesses short but complete documentation and an
14224 interactive specification that prompts you for a file name when you
14225 use the command interactively.  The body of the definition contains
14226 two functions, @code{find-file-noselect} and @code{switch-to-buffer}.
14228 According to its documentation as shown by @kbd{C-h f} (the
14229 @code{describe-function} command), the @code{find-file-noselect}
14230 function reads the named file into a buffer and returns the buffer.
14231 However, the buffer is not selected.  Emacs does not switch its
14232 attention (or yours if you are using @code{find-file-noselect}) to the
14233 named buffer.  That is what @code{switch-to-buffer} does: it switches
14234 the buffer to which Emacs attention is directed; and it switches the
14235 buffer displayed in the window to the new buffer.  We have discussed
14236 buffer switching elsewhere.  (@xref{Switching Buffers}.)
14238 In this histogram project, we do not need to display each file on the
14239 screen as the program determines the length of each definition within
14240 it.  Instead of employing @code{switch-to-buffer}, we can work with
14241 @code{set-buffer}, which redirects the attention of the computer
14242 program to a different buffer but does not redisplay it on the screen.
14243 So instead of calling on @code{find-file} to do the job, we must write
14244 our own expression.
14246 The task is easy: use  @code{find-file-noselect} and @code{set-buffer}.
14248 @node lengths-list-file, Several files, Find a File, Words in a defun
14249 @section @code{lengths-list-file} in Detail
14251 The core of the @code{lengths-list-file} function is a @code{while}
14252 loop containing a function to move point forward `defun by defun' and
14253 a function to count the number of words and symbols in each defun.
14254 This core must be surrounded by functions that do various other tasks,
14255 including finding the file, and ensuring that point starts out at the
14256 beginning of the file.  The function definition looks like this:
14257 @findex lengths-list-file
14259 @smallexample
14260 @group
14261 (defun lengths-list-file (filename)
14262   "Return list of definitions' lengths within FILE.
14263 The returned list is a list of numbers.
14264 Each number is the number of words or
14265 symbols in one function definition."
14266 @end group
14267 @group
14268   (message "Working on `%s' ... " filename)
14269   (save-excursion
14270     (let ((buffer (find-file-noselect filename))
14271           (lengths-list))
14272       (set-buffer buffer)
14273       (setq buffer-read-only t)
14274       (widen)
14275       (goto-char (point-min))
14276       (while (re-search-forward "^(defun" nil t)
14277         (setq lengths-list
14278               (cons (count-words-in-defun) lengths-list)))
14279       (kill-buffer buffer)
14280       lengths-list)))
14281 @end group
14282 @end smallexample
14284 @noindent
14285 The function is passed one argument, the name of the file on which it
14286 will work.  It has four lines of documentation, but no interactive
14287 specification.  Since people worry that a computer is broken if they
14288 don't see anything going on, the first line of the body is a
14289 message.
14291 The next line contains a @code{save-excursion} that returns Emacs'
14292 attention to the current buffer when the function completes.  This is
14293 useful in case you embed this function in another function that
14294 presumes point is restored to the original buffer.
14296 In the varlist of the @code{let} expression, Emacs finds the file and
14297 binds the local variable @code{buffer} to the buffer containing the
14298 file.  At the same time, Emacs creates @code{lengths-list} as a local
14299 variable.
14301 Next, Emacs switches its attention to the buffer.
14303 In the following line, Emacs makes the buffer read-only.  Ideally,
14304 this line is not necessary.  None of the functions for counting words
14305 and symbols in a function definition should change the buffer.
14306 Besides, the buffer is not going to be saved, even if it were changed.
14307 This line is entirely the consequence of great, perhaps excessive,
14308 caution.  The reason for the caution is that this function and those
14309 it calls work on the sources for Emacs and it is very inconvenient if
14310 they are inadvertently modified.  It goes without saying that I did
14311 not realize a need for this line until an experiment went awry and
14312 started to modify my Emacs source files @dots{}
14314 Next comes a call to widen the buffer if it is narrowed.  This
14315 function is usually not needed---Emacs creates a fresh buffer if none
14316 already exists; but if a buffer visiting the file already exists Emacs
14317 returns that one.  In this case, the buffer may be narrowed and must
14318 be widened.  If we wanted to be fully `user-friendly', we would
14319 arrange to save the restriction and the location of point, but we
14320 won't.
14322 The @code{(goto-char (point-min))} expression moves point to the
14323 beginning of the buffer.
14325 Then comes a @code{while} loop in which the `work' of the function is
14326 carried out.  In the loop, Emacs determines the length of each
14327 definition and constructs a lengths' list containing the information.
14329 Emacs kills the buffer after working through it.  This is to save
14330 space inside of Emacs.  My version of Emacs 19 contained over 300
14331 source files of interest; Emacs 21 contains over 800 source files.
14332 Another function will apply @code{lengths-list-file} to each of the
14333 files.
14335 Finally, the last expression within the @code{let} expression is the
14336 @code{lengths-list} variable; its value is returned as the value of
14337 the whole function.
14339 You can try this function by installing it in the usual fashion.  Then
14340 place your cursor after the following expression and type @kbd{C-x
14341 C-e} (@code{eval-last-sexp}).
14343 @c !!! 21.0.100 lisp sources location here
14344 @smallexample
14345 (lengths-list-file
14346  "/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el")
14347 @end smallexample
14349 @c was: (lengths-list-file "../lisp/debug.el")
14350 @c !!!  as of 21, Info file is in
14351 @c /usr/share/info/emacs-lisp-intro.info.gz
14352 @c but debug.el is in  /usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14354 @noindent
14355 (You may need to change the pathname of the file; the one here worked
14356 with GNU Emacs version 21.0.100.  To change the expression, copy it to
14357 the @file{*scratch*} buffer and edit it.
14359 @need 1200
14360 @noindent
14361 (Also, to see the full length of the list, rather than a truncated
14362 version, you may have to evaluate the following:
14364 @smallexample
14365 (custom-set-variables '(eval-expression-print-length nil))
14366 @end smallexample
14368 @noindent
14369 (@xref{defcustom, , Setting Variables with @code{defcustom}}.
14370 Then evaluate the @code{lengths-list-file} expression.)
14372 @need 1200
14373 The lengths' list for @file{debug.el} takes less than a second to
14374 produce and looks like this:
14376 @smallexample
14377 (77 95 85 87 131 89 50 25 44 44 68 35 64 45 17 34 167 457)
14378 @end smallexample
14380 @need 1500
14381 (Using my old machine, the version 19 lengths' list for @file{debug.el}
14382 took seven seconds to produce and looked like this:
14384 @smallexample
14385 (75 41 80 62 20 45 44 68 45 12 34 235)
14386 @end smallexample
14388 (The newer version of  @file{debug.el} contains more defuns than the
14389 earlier one; and my new machine is much faster than the old one.)
14391 Note that the length of the last definition in the file is first in
14392 the list.
14394 @node Several files, Several files recursively, lengths-list-file, Words in a defun
14395 @section Count Words in @code{defuns} in Different Files
14397 In the previous section, we created a function that returns a list of
14398 the lengths of each definition in a file.  Now, we want to define a
14399 function to return a master list of the lengths of the definitions in
14400 a list of files.
14402 Working on each of a list of files is a repetitious act, so we can use
14403 either a @code{while} loop or recursion.
14405 @menu
14406 * lengths-list-many-files::     Return a list of the lengths of defuns.
14407 * append::                      Attach one list to another.
14408 @end menu
14410 @node lengths-list-many-files, append, Several files, Several files
14411 @ifnottex
14412 @unnumberedsubsec Determine the lengths of @code{defuns}
14413 @end ifnottex
14415 The design using a @code{while} loop is routine.  The argument passed
14416 the function is a list of files.  As we saw earlier (@pxref{Loop
14417 Example}), you can write a @code{while} loop so that the body of the
14418 loop is evaluated if such a list contains elements, but to exit the
14419 loop if the list is empty.  For this design to work, the body of the
14420 loop must contain an expression that shortens the list each time the
14421 body is evaluated, so that eventually the list is empty.  The usual
14422 technique is to set the value of the list to the value of the @sc{cdr}
14423 of the list each time the body is evaluated.
14425 @need 800
14426 The template looks like this:
14428 @smallexample
14429 @group
14430 (while @var{test-whether-list-is-empty}
14431   @var{body}@dots{}
14432   @var{set-list-to-cdr-of-list})
14433 @end group
14434 @end smallexample
14436 Also, we remember that a @code{while} loop returns @code{nil} (the
14437 result of evaluating the true-or-false-test), not the result of any
14438 evaluation within its body.  (The evaluations within the body of the
14439 loop are done for their side effects.)  However, the expression that
14440 sets the lengths' list is part of the body---and that is the value
14441 that we want returned by the function as a whole.  To do this, we
14442 enclose the @code{while} loop within a @code{let} expression, and
14443 arrange that the last element of the @code{let} expression contains
14444 the value of the lengths' list.  (@xref{Incrementing Example, , Loop
14445 Example with an Incrementing Counter}.)
14447 @findex lengths-list-many-files
14448 @need 1250
14449 These considerations lead us directly to the function itself:
14451 @smallexample
14452 @group
14453 ;;; @r{Use @code{while} loop.}
14454 (defun lengths-list-many-files (list-of-files)
14455   "Return list of lengths of defuns in LIST-OF-FILES."
14456 @end group
14457 @group
14458   (let (lengths-list)
14460 ;;; @r{true-or-false-test}
14461     (while list-of-files
14462       (setq lengths-list
14463             (append
14464              lengths-list
14466 ;;; @r{Generate a lengths' list.}
14467              (lengths-list-file
14468               (expand-file-name (car list-of-files)))))
14469 @end group
14471 @group
14472 ;;; @r{Make files' list shorter.}
14473       (setq list-of-files (cdr list-of-files)))
14475 ;;; @r{Return final value of lengths' list.}
14476     lengths-list))
14477 @end group
14478 @end smallexample
14480 @code{expand-file-name} is a built-in function that converts a file
14481 name to the absolute, long, path name form of the directory in which
14482 the function is called.
14484 @c !!! 21.0.100 lisp sources location here
14485 @need 1500
14486 Thus, if @code{expand-file-name} is called on @code{debug.el} when
14487 Emacs is visiting the
14488 @file{/usr/local/share/emacs/21.0.100/lisp/emacs-lisp/} directory,
14490 @smallexample
14491 debug.el
14492 @end smallexample
14494 @need 800
14495 @noindent
14496 becomes
14498 @c !!! 21.0.100 lisp sources location here
14499 @smallexample
14500 /usr/local/share/emacs/21.0.100/lisp/emacs-lisp/debug.el
14501 @end smallexample
14503 The only other new element of this function definition is the as yet
14504 unstudied function @code{append}, which merits a short section for
14505 itself.
14507 @node append,  , lengths-list-many-files, Several files
14508 @subsection The @code{append} Function
14510 @need 800
14511 The @code{append} function attaches one list to another.  Thus,
14513 @smallexample
14514 (append '(1 2 3 4) '(5 6 7 8))
14515 @end smallexample
14517 @need 800
14518 @noindent
14519 produces the list
14521 @smallexample
14522 (1 2 3 4 5 6 7 8)
14523 @end smallexample
14525 This is exactly how we want to attach two lengths' lists produced by
14526 @code{lengths-list-file} to each other.  The results contrast with
14527 @code{cons},
14529 @smallexample
14530 (cons '(1 2 3 4) '(5 6 7 8))
14531 @end smallexample
14533 @need 1250
14534 @noindent
14535 which constructs a new list in which the first argument to @code{cons}
14536 becomes the first element of the new list:
14538 @smallexample
14539 ((1 2 3 4) 5 6 7 8)
14540 @end smallexample
14542 @node Several files recursively, Prepare the data, Several files, Words in a defun
14543 @section Recursively Count Words in Different Files
14545 Besides a @code{while} loop, you can work on each of a list of files
14546 with recursion.  A recursive version of @code{lengths-list-many-files}
14547 is short and simple.
14549 The recursive function has the usual parts: the `do-again-test', the
14550 `next-step-expression', and the recursive call.  The `do-again-test'
14551 determines whether the function should call itself again, which it
14552 will do if the @code{list-of-files} contains any remaining elements;
14553 the `next-step-expression' resets the @code{list-of-files} to the
14554 @sc{cdr} of itself, so eventually the list will be empty; and the
14555 recursive call calls itself on the shorter list.  The complete
14556 function is shorter than this description!
14557 @findex recursive-lengths-list-many-files
14559 @smallexample
14560 @group
14561 (defun recursive-lengths-list-many-files (list-of-files)
14562   "Return list of lengths of each defun in LIST-OF-FILES."
14563   (if list-of-files                     ; @r{do-again-test}
14564       (append
14565        (lengths-list-file
14566         (expand-file-name (car list-of-files)))
14567        (recursive-lengths-list-many-files
14568         (cdr list-of-files)))))
14569 @end group
14570 @end smallexample
14572 @noindent
14573 In a sentence, the function returns the lengths' list for the first of
14574 the @code{list-of-files} appended to the result of calling itself on
14575 the rest of the @code{list-of-files}.
14577 Here is a test of @code{recursive-lengths-list-many-files}, along with
14578 the results of running @code{lengths-list-file} on each of the files
14579 individually.
14581 Install @code{recursive-lengths-list-many-files} and
14582 @code{lengths-list-file}, if necessary, and then evaluate the
14583 following expressions.  You may need to change the files' pathnames;
14584 those here work when this Info file and the Emacs sources are located
14585 in their customary places.  To change the expressions, copy them to
14586 the @file{*scratch*} buffer, edit them, and then evaluate them.
14588 The results are shown after the @samp{@result{}}.  (These results are
14589 for files from Emacs Version 21.0.100; files from other versions of
14590 Emacs may produce different results.)
14592 @c !!! 21.0.100 lisp sources location here
14593 @smallexample
14594 @group
14595 (cd "/usr/local/share/emacs/21.0.100/")
14597 (lengths-list-file "./lisp/macros.el")
14598      @result{} (273 263 456 90)
14599 @end group
14601 @group
14602 (lengths-list-file "./lisp/mail/mailalias.el")
14603      @result{} (38 32 26 77 174 180 321 198 324)
14604 @end group
14606 @group
14607 (lengths-list-file "./lisp/makesum.el")
14608      @result{} (85 181)
14609 @end group
14611 @group
14612 (recursive-lengths-list-many-files
14613  '("./lisp/macros.el"
14614    "./lisp/mail/mailalias.el"
14615    "./lisp/makesum.el"))
14616        @result{} (273 263 456 90 38 32 26 77 174 180 321 198 324 85 181)
14617 @end group
14618 @end smallexample
14620 The @code{recursive-lengths-list-many-files} function produces the
14621 output we want.
14623 The next step is to prepare the data in the list for display in a graph.
14625 @node Prepare the data,  , Several files recursively, Words in a defun
14626 @section Prepare the Data for Display in a Graph
14628 The @code{recursive-lengths-list-many-files} function returns a list
14629 of numbers.  Each number records the length of a function definition.
14630 What we need to do now is transform this data into a list of numbers
14631 suitable for generating a graph.  The new list will tell how many
14632 functions definitions contain less than 10 words and
14633 symbols, how many contain between 10 and 19 words and symbols, how
14634 many contain between 20 and 29 words and symbols, and so on.
14636 In brief, we need to go through the lengths' list produced by the
14637 @code{recursive-lengths-list-many-files} function and count the number
14638 of defuns within each range of lengths, and produce a list of those
14639 numbers.
14641 Based on what we have done before, we can readily foresee that it
14642 should not be too hard to write a function that `@sc{cdr}s' down the
14643 lengths' list, looks at each element, determines which length range it
14644 is in, and increments a counter for that range.
14646 However, before beginning to write such a function, we should consider
14647 the advantages of sorting the lengths' list first, so the numbers are
14648 ordered from smallest to largest.  First, sorting will make it easier
14649 to count the numbers in each range, since two adjacent numbers will
14650 either be in the same length range or in adjacent ranges.  Second, by
14651 inspecting a sorted list, we can discover the highest and lowest
14652 number, and thereby determine the largest and smallest length range
14653 that we will need.
14655 @menu
14656 * Sorting::                     Sorting lists.
14657 * Files List::                  Making a list of files.
14658 * Counting function definitions::
14659 @end menu
14661 @node Sorting, Files List, Prepare the data, Prepare the data
14662 @subsection Sorting Lists
14663 @findex sort
14665 Emacs contains a function to sort lists, called (as you might guess)
14666 @code{sort}.  The @code{sort} function takes two arguments, the list
14667 to be sorted, and a predicate that determines whether the first of
14668 two list elements is ``less'' than the second.
14670 As we saw earlier (@pxref{Wrong Type of Argument, , Using the Wrong
14671 Type Object as an Argument}), a predicate is a function that
14672 determines whether some property is true or false.  The @code{sort}
14673 function will reorder a list according to whatever property the
14674 predicate uses; this means that @code{sort} can be used to sort
14675 non-numeric lists by non-numeric criteria---it can, for example,
14676 alphabetize a list.
14678 @need 1250
14679 The @code{<} function is used when sorting a numeric list.  For example,
14681 @smallexample
14682 (sort '(4 8 21 17 33 7 21 7) '<)
14683 @end smallexample
14685 @need 800
14686 @noindent
14687 produces this:
14689 @smallexample
14690 (4 7 7 8 17 21 21 33)
14691 @end smallexample
14693 @noindent
14694 (Note that in this example, both the arguments are quoted so that the
14695 symbols are not evaluated before being passed to @code{sort} as
14696 arguments.)
14698 Sorting the list returned by the
14699 @code{recursive-lengths-list-many-files} function is straightforward;
14700 it uses the @code{<} function:
14702 @smallexample
14703 @group
14704 (sort
14705  (recursive-lengths-list-many-files
14706   '("../lisp/macros.el"
14707     "../lisp/mailalias.el"
14708     "../lisp/makesum.el"))
14709  '<
14710 @end group
14711 @end smallexample
14713 @need 800
14714 @noindent
14715 which produces:
14717 @smallexample
14718 (85 86 116 122 154 176 179 265)
14719 @end smallexample
14721 @noindent
14722 (Note that in this example, the first argument to @code{sort} is not
14723 quoted, since the expression must be evaluated so as to produce the
14724 list that is passed to @code{sort}.)
14726 @node Files List, Counting function definitions, Sorting, Prepare the data
14727 @subsection Making a List of Files
14729 The @code{recursive-lengths-list-many-files} function requires a list
14730 of files as its argument.  For our test examples, we constructed such
14731 a list by hand; but the Emacs Lisp source directory is too large for
14732 us to do for that.  Instead, we will write a function to do the job
14733 for us.  In this function, we will use both a @code{while} loop and a
14734 recursive call.
14736 @findex directory-files
14737 We did not have to write a function like this for older versions of
14738 GNU Emacs, since they placed all the @samp{.el} files in one
14739 directory.  Instead, we were able to use the @code{directory-files}
14740 function, which lists the names of files that match a specified
14741 pattern within a single directory.
14743 However, recent versions of Emacs place Emacs Lisp files in
14744 sub-directories of the top level @file{lisp} directory.  This
14745 re-arrangement eases navigation.  For example, all the mail related
14746 files are in a @file{lisp} sub-directory called @file{mail}.  But at
14747 the same time, this arrangement forces us to create a file listing
14748 function that descends into the sub-directories.
14750 @findex files-in-below-directory
14751 We can create this function, called @code{files-in-below-directory},
14752 using familiar functions such as @code{car}, @code{nthcdr}, and
14753 @code{substring} in conjunction with an existing function called
14754 @code{directory-files-and-attributes}.  This latter function not only
14755 lists all the filenames in a directory, including the names
14756 of sub-directories, but also their attributes.
14758 To restate our goal: to create a function that will enable us
14759 to feed filenames to @code{recursive-lengths-list-many-files}
14760 as a list that looks like this (but with more elements):
14762 @smallexample
14763 @group
14764 ("../lisp/macros.el"
14765  "../lisp/mail/rmail.el"
14766  "../lisp/makesum.el")
14767 @end group
14768 @end smallexample
14770 The @code{directory-files-and-attributes} function returns a list of
14771 lists.  Each of the lists within the main list consists of 13
14772 elements.  The first element is a string that contains the name of the
14773 file -- which, in GNU/Linux, may be a `directory file', that is to
14774 say, a file with the special attributes of a directory.  The second
14775 element of the list is @code{t} for a directory, a string
14776 for symbolic link (the string is the name linked to), or @code{nil}.
14778 For example, the first @samp{.el} file in the @file{lisp/} directory
14779 is @file{abbrev.el}.  Its name is
14780 @file{/usr/local/share/emacs/21.0.100/lisp/abbrev.el} and it is not a
14781 directory or a symbolic link.
14783 @need 1000
14784 This is how @code{directory-files-and-attributes} lists that file and
14785 its attributes:
14787 @smallexample
14788 @group
14789 ("/usr/local/share/emacs/21.0.100/lisp/abbrev.el"
14792 1000
14794 @end group
14795 @group
14796 (15019 32380)
14797 (14883 48041)
14798 (15214 49336)
14799 11583
14800 "-rw-rw-r--"
14801 @end group
14802 @group
14804 341385
14805 776)
14806 @end group
14807 @end smallexample
14809 @need 1200
14810 On the other hand, @file{mail/} is a directory within the @file{lisp/}
14811 directory.  The beginning of its listing looks like this:
14813 @smallexample
14814 @group
14815 ("/usr/local/share/emacs/21.0.100/lisp/mail"
14817 @dots{}
14819 @end group
14820 @end smallexample
14822 (Look at the documentation of @code{file-attributes} to learn about
14823 the different attributes.  Bear in mind that the
14824 @code{file-attributes} function does not list the filename, so its
14825 first element is @code{directory-files-and-attributes}'s second
14826 element.)
14828 We will want our new function, @code{files-in-below-directory}, to
14829 list the @samp{.el} files in the directory it is told to check, and in
14830 any directories below that directory.
14832 This gives us a hint on how to construct
14833 @code{files-in-below-directory}:  within a directory, the function
14834 should add @samp{.el} filenames to a list; and if, within a directory,
14835 the function comes upon a sub-directory, it should go into that
14836 sub-directory and repeat its actions.
14838 However, we should note that every directory contains a name that
14839 refers to itself, called @file{.}, (``dot'') and a name that refers to
14840 its parent directory, called @file{..} (``double dot'').  (In
14841 @file{/}, the root directory, @file{..} refers to itself, since
14842 @file{/} has no parent.)  Clearly, we do not want our
14843 @code{files-in-below-directory} function to enter those directories,
14844 since they always lead us, directly or indirectly, to the current
14845 directory.
14847 Consequently, our @code{files-in-below-directory} function must do
14848 several tasks:
14850 @itemize @bullet
14851 @item
14852 Check to see whether it is looking at a filename that ends in
14853 @samp{.el}; and if so, add its name to a list.
14855 @item
14856 Check to see whether it is looking at a filename that is the name of a
14857 directory; and if so,
14859 @itemize @minus
14860 @item
14861 Check to see whether it is looking at @file{.}  or @file{..}; and if
14862 so skip it.
14864 @item
14865 Or else, go into that directory and repeat the process.
14866 @end itemize
14867 @end itemize
14869 Let's write a function definition to do these tasks.  We will use a
14870 @code{while} loop to move from one filename to another within a
14871 directory, checking what needs to be done; and we will use a recursive
14872 call to repeat the actions on each sub-directory.  The recursive
14873 pattern is `accumulate'
14874 (@pxref{Accumulate, , Recursive Pattern: @emph{accumulate}}),
14875 using @code{append} as the combiner.
14877 @ignore
14878 (directory-files "/usr/local/share/emacs/21.0.100/lisp/" t "\\.el$")
14879 (shell-command "find /usr/local/share/emacs/21.0.100/lisp/ -name '*.el'")
14880 @end ignore
14882 @c  /usr/local/share/emacs/21.0.100/lisp/
14884 @need 800
14885 Here is the function:
14887 @smallexample
14888 @group
14889 (defun files-in-below-directory (directory)
14890   "List the .el files in DIRECTORY and in its sub-directories."
14891   ;; Although the function will be used non-interactively,
14892   ;; it will be easier to test if we make it interactive.
14893   ;; The directory will have a name such as
14894   ;;  "/usr/local/share/emacs/21.0.100/lisp/"
14895   (interactive "DDirectory name: ")
14896 @end group
14897 @group
14898   (let (el-files-list
14899         (current-directory-list
14900          (directory-files-and-attributes directory t)))
14901     ;; while we are in the current directory
14902     (while current-directory-list
14903 @end group
14904 @group
14905       (cond
14906        ;; check to see whether filename ends in `.el'
14907        ;; and if so, append its name to a list.
14908        ((equal ".el" (substring (car (car current-directory-list)) -3))
14909         (setq el-files-list
14910               (cons (car (car current-directory-list)) el-files-list)))
14911 @end group
14912 @group
14913        ;; check whether filename is that of a directory
14914        ((eq t (car (cdr (car current-directory-list))))
14915         ;; decide whether to skip or recurse
14916         (if
14917             (equal (or "." "..")
14918                    (substring (car (car current-directory-list)) -1))
14919             ;; then do nothing if filename is that of
14920             ;;   current directory or parent
14921             ()
14922 @end group
14923 @group
14924           ;; else descend into the directory and repeat the process
14925           (setq el-files-list
14926                 (append
14927                  (files-in-below-directory
14928                   (car (car current-directory-list)))
14929                  el-files-list)))))
14930       ;; move to the next filename in the list; this also
14931       ;; shortens the list so the while loop eventually comes to an end
14932       (setq current-directory-list (cdr current-directory-list)))
14933     ;; return the filenames
14934     el-files-list))
14935 @end group
14936 @end smallexample
14938 @c (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14940 The @code{files-in-below-directory} @code{directory-files} function
14941 takes one argument, the name of a directory.
14943 @need 1250
14944 Thus, on my system,
14946 @c !!! 21.0.100 lisp sources location here
14947 @smallexample
14948 @group
14949 (length
14950  (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/"))
14951 @end group
14952 @end smallexample
14954 @noindent
14955 tells me that my version 21.0.100 Lisp sources directory contains 754
14956 @samp{.el} files.
14958 @code{files-in-below-directory} returns a list in reverse alphabetical
14959 order.  An expression to sort the list in alphabetical order looks
14960 like this:
14962 @smallexample
14963 @group
14964 (sort
14965  (files-in-below-directory "/usr/local/share/emacs/21.0.100/lisp/")
14966  'string-lessp)
14967 @end group
14968 @end smallexample
14970 @ignore
14971 (defun test ()
14972   "Test how long it takes to find lengths of all elisp defuns."
14973   (insert "\n" (current-time-string) "\n")
14974   (sit-for 0)
14975   (sort
14976    (recursive-lengths-list-many-files
14977     '("../lisp/macros.el"
14978       "../lisp/mailalias.el"
14979       "../lisp/makesum.el"))
14980    '<)
14981   (insert (format "%s" (current-time-string))))
14983 @end ignore
14985 @node Counting function definitions,  , Files List, Prepare the data
14986 @subsection Counting function definitions
14988 Our immediate goal is to generate a list that tells us how many
14989 function definitions contain fewer than 10 words and symbols, how many
14990 contain between 10 and 19 words and symbols, how many contain between
14991 20 and 29 words and symbols, and so on.
14993 With a sorted list of numbers, this is easy: count how many elements
14994 of the list are smaller than 10, then, after moving past the numbers
14995 just counted, count how many are smaller than 20, then, after moving
14996 past the numbers just counted, count how many are smaller than 30, and
14997 so on.  Each of the numbers, 10, 20, 30, 40, and the like, is one
14998 larger than the top of that range.  We can call the list of such
14999 numbers the @code{top-of-ranges} list.
15001 @need 1200
15002 If we wished, we could generate this list automatically, but it is
15003 simpler to write a list manually.  Here it is:
15004 @vindex top-of-ranges
15006 @smallexample
15007 @group
15008 (defvar top-of-ranges
15009  '(10  20  30  40  50
15010    60  70  80  90 100
15011   110 120 130 140 150
15012   160 170 180 190 200
15013   210 220 230 240 250
15014   260 270 280 290 300)
15015  "List specifying ranges for `defuns-per-range'.")
15016 @end group
15017 @end smallexample
15019 To change the ranges, we edit this list.
15021 Next, we need to write the function that creates the list of the
15022 number of definitions within each range.  Clearly, this function must
15023 take the @code{sorted-lengths} and the @code{top-of-ranges} lists
15024 as arguments.
15026 The @code{defuns-per-range} function must do two things again and
15027 again: it must count the number of definitions within a range
15028 specified by the current top-of-range value; and it must shift to the
15029 next higher value in the @code{top-of-ranges} list after counting the
15030 number of definitions in the current range.  Since each of these
15031 actions is repetitive, we can use @code{while} loops for the job.
15032 One loop counts the number of definitions in the range defined by the
15033 current top-of-range value, and the other loop selects each of the
15034 top-of-range values in turn.
15036 Several entries of the @code{sorted-lengths} list are counted for each
15037 range; this means that the loop for the @code{sorted-lengths} list
15038 will be inside the loop for the @code{top-of-ranges} list, like a
15039 small gear inside a big gear.
15041 The inner loop counts the number of definitions within the range.  It
15042 is a simple counting loop of the type we have seen before.
15043 (@xref{Incrementing Loop, , A loop with an incrementing counter}.)
15044 The true-or-false test of the loop tests whether the value from the
15045 @code{sorted-lengths} list is smaller than the current value of the
15046 top of the range.  If it is, the function increments the counter and
15047 tests the next value from the @code{sorted-lengths} list.
15049 @need 1250
15050 The inner loop looks like this:
15052 @smallexample
15053 @group
15054 (while @var{length-element-smaller-than-top-of-range}
15055   (setq number-within-range (1+ number-within-range))
15056   (setq sorted-lengths (cdr sorted-lengths)))
15057 @end group
15058 @end smallexample
15060 The outer loop must start with the lowest value of the
15061 @code{top-of-ranges} list, and then be set to each of the succeeding
15062 higher values in turn.  This can be done with a loop like this:
15064 @smallexample
15065 @group
15066 (while top-of-ranges
15067   @var{body-of-loop}@dots{}
15068   (setq top-of-ranges (cdr top-of-ranges)))
15069 @end group
15070 @end smallexample
15072 @need 1200
15073 Put together, the two loops look like this:
15075 @smallexample
15076 @group
15077 (while top-of-ranges
15079   ;; @r{Count the number of elements within the current range.}
15080   (while @var{length-element-smaller-than-top-of-range}
15081     (setq number-within-range (1+ number-within-range))
15082     (setq sorted-lengths (cdr sorted-lengths)))
15084   ;; @r{Move to next range.}
15085   (setq top-of-ranges (cdr top-of-ranges)))
15086 @end group
15087 @end smallexample
15089 In addition, in each circuit of the outer loop, Emacs should record
15090 the number of definitions within that range (the value of
15091 @code{number-within-range}) in a list.  We can use @code{cons} for
15092 this purpose.  (@xref{cons, , @code{cons}}.)
15094 The @code{cons} function works fine, except that the list it
15095 constructs will contain the number of definitions for the highest
15096 range at its beginning and the number of definitions for the lowest
15097 range at its end.  This is because @code{cons} attaches new elements
15098 of the list to the beginning of the list, and since the two loops are
15099 working their way through the lengths' list from the lower end first,
15100 the @code{defuns-per-range-list} will end up largest number first.
15101 But we will want to print our graph with smallest values first and the
15102 larger later.  The solution is to reverse the order of the
15103 @code{defuns-per-range-list}.  We can do this using the
15104 @code{nreverse} function, which reverses the order of a list.
15105 @findex nreverse
15107 @need 800
15108 For example,
15110 @smallexample
15111 (nreverse '(1 2 3 4))
15112 @end smallexample
15114 @need 800
15115 @noindent
15116 produces:
15118 @smallexample
15119 (4 3 2 1)
15120 @end smallexample
15122 Note that the @code{nreverse} function is ``destructive''---that is,
15123 it changes the list to which it is applied; this contrasts with the
15124 @code{car} and @code{cdr} functions, which are non-destructive.  In
15125 this case, we do not want the original @code{defuns-per-range-list},
15126 so it does not matter that it is destroyed.  (The @code{reverse}
15127 function provides a reversed copy of a list, leaving the original list
15128 as is.)
15129 @findex reverse
15131 @need 1250
15132 Put all together, the @code{defuns-per-range} looks like this:
15134 @smallexample
15135 @group
15136 (defun defuns-per-range (sorted-lengths top-of-ranges)
15137   "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
15138   (let ((top-of-range (car top-of-ranges))
15139         (number-within-range 0)
15140         defuns-per-range-list)
15141 @end group
15143 @group
15144     ;; @r{Outer loop.}
15145     (while top-of-ranges
15146 @end group
15148 @group
15149       ;; @r{Inner loop.}
15150       (while (and
15151               ;; @r{Need number for numeric test.}
15152               (car sorted-lengths)
15153               (< (car sorted-lengths) top-of-range))
15154 @end group
15156 @group
15157         ;; @r{Count number of definitions within current range.}
15158         (setq number-within-range (1+ number-within-range))
15159         (setq sorted-lengths (cdr sorted-lengths)))
15161       ;; @r{Exit inner loop but remain within outer loop.}
15162 @end group
15164 @group
15165       (setq defuns-per-range-list
15166             (cons number-within-range defuns-per-range-list))
15167       (setq number-within-range 0)      ; @r{Reset count to zero.}
15168 @end group
15170 @group
15171       ;; @r{Move to next range.}
15172       (setq top-of-ranges (cdr top-of-ranges))
15173       ;; @r{Specify next top of range value.}
15174       (setq top-of-range (car top-of-ranges)))
15175 @end group
15177 @group
15178     ;; @r{Exit outer loop and count the number of defuns larger than}
15179     ;; @r{  the largest top-of-range value.}
15180     (setq defuns-per-range-list
15181           (cons
15182            (length sorted-lengths)
15183            defuns-per-range-list))
15184 @end group
15186 @group
15187     ;; @r{Return a list of the number of definitions within each range,}
15188     ;; @r{  smallest to largest.}
15189     (nreverse defuns-per-range-list)))
15190 @end group
15191 @end smallexample
15193 @need 1200
15194 @noindent
15195 The function is straightforward except for one subtle feature.  The
15196 true-or-false test of the inner loop looks like this:
15198 @smallexample
15199 @group
15200 (and (car sorted-lengths)
15201      (< (car sorted-lengths) top-of-range))
15202 @end group
15203 @end smallexample
15205 @need 800
15206 @noindent
15207 instead of like this:
15209 @smallexample
15210 (< (car sorted-lengths) top-of-range)
15211 @end smallexample
15213 The purpose of the test is to determine whether the first item in the
15214 @code{sorted-lengths} list is less than the value of the top of the
15215 range.
15217 The simple version of the test works fine unless the
15218 @code{sorted-lengths} list has a @code{nil} value.  In that case, the
15219 @code{(car sorted-lengths)} expression function returns
15220 @code{nil}.  The @code{<} function cannot compare a number to
15221 @code{nil}, which is an empty list, so Emacs signals an error and
15222 stops the function from attempting to continue to execute.
15224 The @code{sorted-lengths} list always becomes @code{nil} when the
15225 counter reaches the end of the list.  This means that any attempt to
15226 use the @code{defuns-per-range} function with the simple version of
15227 the test will fail.
15229 We solve the problem by using the @code{(car sorted-lengths)}
15230 expression in conjunction with the @code{and} expression.  The
15231 @code{(car sorted-lengths)} expression returns a non-@code{nil}
15232 value so long as the list has at least one number within it, but
15233 returns @code{nil} if the list is empty.  The @code{and} expression
15234 first evaluates the @code{(car sorted-lengths)} expression, and
15235 if it is @code{nil}, returns false @emph{without} evaluating the
15236 @code{<} expression.  But if the @code{(car sorted-lengths)}
15237 expression returns a non-@code{nil} value, the @code{and} expression
15238 evaluates the @code{<} expression, and returns that value as the value
15239 of the @code{and} expression.
15241 @c colon in printed section title causes problem in Info cross reference
15242 This way, we avoid an error.
15243 @iftex
15244 @xref{forward-paragraph, , @code{forward-paragraph}: a Goldmine of
15245 Functions}, for more information about @code{and}.
15246 @end iftex
15247 @ifinfo
15248 @xref{forward-paragraph}, for more information about @code{and}.
15249 @end ifinfo
15251 Here is a short test of the @code{defuns-per-range} function.  First,
15252 evaluate the expression that binds (a shortened)
15253 @code{top-of-ranges} list to the list of values, then evaluate the
15254 expression for binding the @code{sorted-lengths} list, and then
15255 evaluate the @code{defuns-per-range} function.
15257 @smallexample
15258 @group
15259 ;; @r{(Shorter list than we will use later.)}
15260 (setq top-of-ranges
15261  '(110 120 130 140 150
15262    160 170 180 190 200))
15264 (setq sorted-lengths
15265       '(85 86 110 116 122 129 154 176 179 200 265 300 300))
15267 (defuns-per-range sorted-lengths top-of-ranges)
15268 @end group
15269 @end smallexample
15271 @need 800
15272 @noindent
15273 The list returned looks like this:
15275 @smallexample
15276 (2 2 2 0 0 1 0 2 0 0 4)
15277 @end smallexample
15279 @noindent
15280 Indeed, there are two elements of the @code{sorted-lengths} list
15281 smaller than 110, two elements between 110 and 119, two elements
15282 between 120 and 129, and so on.  There are four elements with a value
15283 of 200 or larger.
15285 @c The next step is to turn this numbers' list into a graph.
15287 @node Readying a Graph, Emacs Initialization, Words in a defun, Top
15288 @chapter Readying a Graph
15289 @cindex Readying a graph
15290 @cindex Graph prototype
15291 @cindex Prototype graph
15292 @cindex Body of graph
15294 Our goal is to construct a graph showing the numbers of function
15295 definitions of various lengths in the Emacs lisp sources.
15297 As a practical matter, if you were creating a graph, you would
15298 probably use a program such as @code{gnuplot} to do the job.
15299 (@code{gnuplot} is nicely integrated into GNU Emacs.)  In this case,
15300 however, we create one from scratch, and in the process we will
15301 re-acquaint ourselves with some of what we learned before and learn
15302 more.
15304 In this chapter, we will first write a simple graph printing function.
15305 This first definition will be a @dfn{prototype}, a rapidly written
15306 function that enables us to reconnoiter this unknown graph-making
15307 territory.  We will discover dragons, or find that they are myth.
15308 After scouting the terrain, we will feel more confident and enhance
15309 the function to label the axes automatically.
15311 @menu
15312 * Columns of a graph::
15313 * graph-body-print::            How to print the body of a graph.
15314 * recursive-graph-body-print::
15315 * Printed Axes::
15316 * Line Graph Exercise::
15317 @end menu
15319 @node Columns of a graph, graph-body-print, Readying a Graph, Readying a Graph
15320 @ifnottex
15321 @unnumberedsec Printing the Columns of a Graph
15322 @end ifnottex
15324 Since Emacs is designed to be flexible and work with all kinds of
15325 terminals, including character-only terminals, the graph will need to
15326 be made from one of the `typewriter' symbols.  An asterisk will do; as
15327 we enhance the graph-printing function, we can make the choice of
15328 symbol a user option.
15330 We can call this function @code{graph-body-print}; it will take a
15331 @code{numbers-list} as its only argument.  At this stage, we will not
15332 label the graph, but only print its body.
15334 The @code{graph-body-print} function inserts a vertical column of
15335 asterisks for each element in the @code{numbers-list}.  The height of
15336 each line is determined by the value of that element of the
15337 @code{numbers-list}.
15339 Inserting columns is a repetitive act; that means that this function can
15340 be written either with a @code{while} loop or recursively.
15342 Our first challenge is to discover how to print a column of asterisks.
15343 Usually, in Emacs, we print characters onto a screen horizontally,
15344 line by line, by typing.  We have two routes we can follow: write our
15345 own column-insertion function or discover whether one exists in Emacs.
15347 To see whether there is one in Emacs, we can use the @kbd{M-x apropos}
15348 command.  This command is like the @kbd{C-h a} (command-apropos)
15349 command, except that the latter finds only those functions that are
15350 commands.  The @kbd{M-x apropos} command lists all symbols that match
15351 a regular expression, including functions that are not interactive.
15352 @findex apropos
15354 What we want to look for is some command that prints or inserts
15355 columns.  Very likely, the name of the function will contain either
15356 the word `print' or the word `insert' or the word `column'.
15357 Therefore, we can simply type @kbd{M-x apropos RET
15358 print\|insert\|column RET} and look at the result.  On my system, this
15359 command takes quite some time, and then produces a list of 79
15360 functions and variables.  Scanning down the list, the only function
15361 that looks as if it might do the job is @code{insert-rectangle}.
15363 @need 1200
15364 Indeed, this is the function we want; its documentation says:
15366 @smallexample
15367 @group
15368 insert-rectangle:
15369 Insert text of RECTANGLE with upper left corner at point.
15370 RECTANGLE's first line is inserted at point,
15371 its second line is inserted at a point vertically under point, etc.
15372 RECTANGLE should be a list of strings.
15373 @end group
15374 @end smallexample
15376 We can run a quick test, to make sure it does what we expect of it.
15378 Here is the result of placing the cursor after the
15379 @code{insert-rectangle} expression and typing @kbd{C-u C-x C-e}
15380 (@code{eval-last-sexp}).  The function inserts the strings
15381 @samp{"first"}, @samp{"second"}, and @samp{"third"} at and below
15382 point.  Also the function returns @code{nil}.
15384 @smallexample
15385 @group
15386 (insert-rectangle '("first" "second" "third"))first
15387                                               second
15388                                               third
15390 @end group
15391 @end smallexample
15393 @noindent
15394 Of course, we won't be inserting the text of the
15395 @code{insert-rectangle} expression itself into the buffer in which we
15396 are making the graph, but will call the function from our program.  We
15397 shall, however, have to make sure that point is in the buffer at the
15398 place where the @code{insert-rectangle} function will insert its
15399 column of strings.
15401 If you are reading this in Info, you can see how this works by
15402 switching to another buffer, such as the @file{*scratch*} buffer,
15403 placing point somewhere in the buffer, typing @kbd{M-:},
15404 typing the @code{insert-rectangle} expression into the minibuffer at
15405 the prompt, and then typing @key{RET}.  This causes Emacs to evaluate
15406 the expression in the minibuffer, but to use as the value of point the
15407 position of point in the @file{*scratch*} buffer.  (@kbd{M-:}
15408 is the keybinding for @code{eval-expression}.)
15410 We find when we do this that point ends up at the end of the last
15411 inserted line---that is to say, this function moves point as a
15412 side-effect.  If we were to repeat the command, with point at this
15413 position, the next insertion would be below and to the right of the
15414 previous insertion.  We don't want this!  If we are going to make a
15415 bar graph, the columns need to be beside each other.
15417 So we discover that each cycle of the column-inserting @code{while}
15418 loop must reposition point to the place we want it, and that place
15419 will be at the top, not the bottom, of the column.  Moreover, we
15420 remember that when we print a graph, we do not expect all the columns
15421 to be the same height.  This means that the top of each column may be
15422 at a different height from the previous one.  We cannot simply
15423 reposition point to the same line each time, but moved over to the
15424 right---or perhaps we can@dots{}
15426 We are planning to make the columns of the bar graph out of asterisks.
15427 The number of asterisks in the column is the number specified by the
15428 current element of the @code{numbers-list}.  We need to construct a
15429 list of asterisks of the right length for each call to
15430 @code{insert-rectangle}.  If this list consists solely of the requisite
15431 number of asterisks, then we will have position point the right number
15432 of lines above the base for the graph to print correctly.  This could
15433 be difficult.
15435 Alternatively, if we can figure out some way to pass
15436 @code{insert-rectangle} a list of the same length each time, then we
15437 can place point on the same line each time, but move it over one
15438 column to the right for each new column.  If we do this, however, some
15439 of the entries in the list passed to @code{insert-rectangle} must be
15440 blanks rather than asterisks.  For example, if the maximum height of
15441 the graph is 5, but the height of the column is 3, then
15442 @code{insert-rectangle} requires an argument that looks like this:
15444 @smallexample
15445 (" " " " "*" "*" "*")
15446 @end smallexample
15448 This last proposal is not so difficult, so long as we can determine
15449 the column height.  There are two ways for us to specify the column
15450 height: we can arbitrarily state what it will be, which would work
15451 fine for graphs of that height; or we can search through the list of
15452 numbers and use the maximum height of the list as the maximum height
15453 of the graph.  If the latter operation were difficult, then the former
15454 procedure would be easiest, but there is a function built into Emacs
15455 that determines the maximum of its arguments.  We can use that
15456 function.  The function is called @code{max} and it returns the
15457 largest of all its arguments, which must be numbers.  Thus, for
15458 example,
15460 @smallexample
15461 (max  3 4 6 5 7 3)
15462 @end smallexample
15464 @noindent
15465 returns 7.  (A corresponding function called @code{min} returns the
15466 smallest of all its arguments.)
15467 @findex max
15468 @findex min
15470 However, we cannot simply call @code{max} on the @code{numbers-list};
15471 the @code{max} function expects numbers as its argument, not a list of
15472 numbers.  Thus, the following expression,
15474 @smallexample
15475 (max  '(3 4 6 5 7 3))
15476 @end smallexample
15478 @need 800
15479 @noindent
15480 produces the following error message;
15482 @smallexample
15483 Wrong type of argument:  number-or-marker-p, (3 4 6 5 7 3)
15484 @end smallexample
15486 @findex apply
15487 We need a function that passes a list of arguments to a function.
15488 This function is @code{apply}.  This function `applies' its first
15489 argument (a function) to its remaining arguments, the last of which
15490 may be a list.
15492 @need 1250
15493 For example,
15495 @smallexample
15496 (apply 'max 3 4 7 3 '(4 8 5))
15497 @end smallexample
15499 @noindent
15500 returns 8.
15502 (Incidentally, I don't know how you would learn of this function
15503 without a book such as this.  It is possible to discover other
15504 functions, like @code{search-forward} or @code{insert-rectangle}, by
15505 guessing at a part of their names and then using @code{apropos}.  Even
15506 though its base in metaphor is clear---`apply' its first argument to
15507 the rest---I doubt a novice would come up with that particular word
15508 when using @code{apropos} or other aid.  Of course, I could be wrong;
15509 after all, the function was first named by someone who had to invent
15510 it.)
15512 The second and subsequent arguments to @code{apply} are optional, so
15513 we can use @code{apply} to call a function and pass the elements of a
15514 list to it, like this, which also returns 8:
15516 @smallexample
15517 (apply 'max '(4 8 5))
15518 @end smallexample
15520 This latter way is how we will use @code{apply}.  The
15521 @code{recursive-lengths-list-many-files} function returns a numbers'
15522 list to which we can apply @code{max} (we could also apply @code{max} to
15523 the sorted numbers' list; it does not matter whether the list is
15524 sorted or not.)
15526 @need 800
15527 Hence, the operation for finding the maximum height of the graph is this:
15529 @smallexample
15530 (setq max-graph-height (apply 'max numbers-list))
15531 @end smallexample
15533 Now we can return to the question of how to create a list of strings
15534 for a column of the graph.  Told the maximum height of the graph
15535 and the number of asterisks that should appear in the column, the
15536 function should return a list of strings for the
15537 @code{insert-rectangle} command to insert.
15539 Each column is made up of asterisks or blanks.  Since the function is
15540 passed the value of the height of the column and the number of
15541 asterisks in the column, the number of blanks can be found by
15542 subtracting the number of asterisks from the height of the column.
15543 Given the number of blanks and the number of asterisks, two
15544 @code{while} loops can be used to construct the list:
15546 @smallexample
15547 @group
15548 ;;; @r{First version.}
15549 (defun column-of-graph (max-graph-height actual-height)
15550   "Return list of strings that is one column of a graph."
15551   (let ((insert-list nil)
15552         (number-of-top-blanks
15553          (- max-graph-height actual-height)))
15554 @end group
15556 @group
15557     ;; @r{Fill in asterisks.}
15558     (while (> actual-height 0)
15559       (setq insert-list (cons "*" insert-list))
15560       (setq actual-height (1- actual-height)))
15561 @end group
15563 @group
15564     ;; @r{Fill in blanks.}
15565     (while (> number-of-top-blanks 0)
15566       (setq insert-list (cons " " insert-list))
15567       (setq number-of-top-blanks
15568             (1- number-of-top-blanks)))
15569 @end group
15571 @group
15572     ;; @r{Return whole list.}
15573     insert-list))
15574 @end group
15575 @end smallexample
15577 If you install this function and then evaluate the following
15578 expression you will see that it returns the list as desired:
15580 @smallexample
15581 (column-of-graph 5 3)
15582 @end smallexample
15584 @need 800
15585 @noindent
15586 returns
15588 @smallexample
15589 (" " " " "*" "*" "*")
15590 @end smallexample
15592 As written, @code{column-of-graph} contains a major flaw: the symbols
15593 used for the blank and for the marked entries in the column are
15594 `hard-coded' as a space and asterisk.  This is fine for a prototype,
15595 but you, or another user, may wish to use other symbols.  For example,
15596 in testing the graph function, you many want to use a period in place
15597 of the space, to make sure the point is being repositioned properly
15598 each time the @code{insert-rectangle} function is called; or you might
15599 want to substitute a @samp{+} sign or other symbol for the asterisk.
15600 You might even want to make a graph-column that is more than one
15601 display column wide.  The program should be more flexible.  The way to
15602 do that is to replace the blank and the asterisk with two variables
15603 that we can call @code{graph-blank} and @code{graph-symbol} and define
15604 those variables separately.
15606 Also, the documentation is not well written.  These considerations
15607 lead us to the second version of the function:
15609 @smallexample
15610 @group
15611 (defvar graph-symbol "*"
15612   "String used as symbol in graph, usually an asterisk.")
15613 @end group
15615 @group
15616 (defvar graph-blank " "
15617   "String used as blank in graph, usually a blank space.
15618 graph-blank must be the same number of columns wide
15619 as graph-symbol.")
15620 @end group
15621 @end smallexample
15623 @noindent
15624 (For an explanation of @code{defvar}, see
15625 @ref{defvar, , Initializing a Variable with @code{defvar}}.)
15627 @smallexample
15628 @group
15629 ;;; @r{Second version.}
15630 (defun column-of-graph (max-graph-height actual-height)
15631   "Return MAX-GRAPH-HEIGHT strings; ACTUAL-HEIGHT are graph-symbols.
15633 @end group
15634 @group
15635 The graph-symbols are contiguous entries at the end
15636 of the list.
15637 The list will be inserted as one column of a graph.
15638 The strings are either graph-blank or graph-symbol."
15639 @end group
15641 @group
15642   (let ((insert-list nil)
15643         (number-of-top-blanks
15644          (- max-graph-height actual-height)))
15645 @end group
15647 @group
15648     ;; @r{Fill in @code{graph-symbols}.}
15649     (while (> actual-height 0)
15650       (setq insert-list (cons graph-symbol insert-list))
15651       (setq actual-height (1- actual-height)))
15652 @end group
15654 @group
15655     ;; @r{Fill in @code{graph-blanks}.}
15656     (while (> number-of-top-blanks 0)
15657       (setq insert-list (cons graph-blank insert-list))
15658       (setq number-of-top-blanks
15659             (1- number-of-top-blanks)))
15661     ;; @r{Return whole list.}
15662     insert-list))
15663 @end group
15664 @end smallexample
15666 If we wished, we could rewrite @code{column-of-graph} a third time to
15667 provide optionally for a line graph as well as for a bar graph.  This
15668 would not be hard to do.  One way to think of a line graph is that it
15669 is no more than a bar graph in which the part of each bar that is
15670 below the top is blank.  To construct a column for a line graph, the
15671 function first constructs a list of blanks that is one shorter than
15672 the value, then it uses @code{cons} to attach a graph symbol to the
15673 list; then it uses @code{cons} again to attach the `top blanks' to
15674 the list.
15676 It is easy to see how to write such a function, but since we don't
15677 need it, we will not do it.  But the job could be done, and if it were
15678 done, it would be done with @code{column-of-graph}.  Even more
15679 important, it is worth noting that few changes would have to be made
15680 anywhere else.  The enhancement, if we ever wish to make it, is
15681 simple.
15683 Now, finally, we come to our first actual graph printing function.
15684 This prints the body of a graph, not the labels for the vertical and
15685 horizontal axes, so we can call this @code{graph-body-print}.
15687 @node graph-body-print, recursive-graph-body-print, Columns of a graph, Readying a Graph
15688 @section The @code{graph-body-print} Function
15689 @findex graph-body-print
15691 After our preparation in the preceding section, the
15692 @code{graph-body-print} function is straightforward.  The function
15693 will print column after column of asterisks and blanks, using the
15694 elements of a numbers' list to specify the number of asterisks in each
15695 column.  This is a repetitive act, which means we can use a
15696 decrementing @code{while} loop or recursive function for the job.  In
15697 this section, we will write the definition using a @code{while} loop.
15699 The @code{column-of-graph} function requires the height of the graph
15700 as an argument, so we should determine and record that as a local variable.
15702 This leads us to the following template for the @code{while} loop
15703 version of this function:
15705 @smallexample
15706 @group
15707 (defun graph-body-print (numbers-list)
15708   "@var{documentation}@dots{}"
15709   (let ((height  @dots{}
15710          @dots{}))
15711 @end group
15713 @group
15714     (while numbers-list
15715       @var{insert-columns-and-reposition-point}
15716       (setq numbers-list (cdr numbers-list)))))
15717 @end group
15718 @end smallexample
15720 @noindent
15721 We need to fill in the slots of the template.
15723 Clearly, we can use the @code{(apply 'max numbers-list)} expression to
15724 determine the height of the graph.
15726 The @code{while} loop will cycle through the @code{numbers-list} one
15727 element at a time.  As it is shortened by the @code{(setq numbers-list
15728 (cdr numbers-list))} expression, the @sc{car} of each instance of the
15729 list is the value of the argument for @code{column-of-graph}.
15731 At each cycle of the @code{while} loop, the @code{insert-rectangle}
15732 function inserts the list returned by @code{column-of-graph}.  Since
15733 the @code{insert-rectangle} function moves point to the lower right of
15734 the inserted rectangle, we need to save the location of point at the
15735 time the rectangle is inserted, move back to that position after the
15736 rectangle is inserted, and then move horizontally to the next place
15737 from which @code{insert-rectangle} is called.
15739 If the inserted columns are one character wide, as they will be if
15740 single blanks and asterisks are used, the repositioning command is
15741 simply @code{(forward-char 1)}; however, the width of a column may be
15742 greater than one.  This means that the repositioning command should be
15743 written @code{(forward-char symbol-width)}.  The @code{symbol-width}
15744 itself is the length of a @code{graph-blank} and can be found using
15745 the expression @code{(length graph-blank)}.  The best place to bind
15746 the @code{symbol-width} variable to the value of the width of graph
15747 column is in the varlist of the @code{let} expression.
15749 @need 1250
15750 These considerations lead to the following function definition:
15752 @smallexample
15753 @group
15754 (defun graph-body-print (numbers-list)
15755   "Print a bar graph of the NUMBERS-LIST.
15756 The numbers-list consists of the Y-axis values."
15758   (let ((height (apply 'max numbers-list))
15759         (symbol-width (length graph-blank))
15760         from-position)
15761 @end group
15763 @group
15764     (while numbers-list
15765       (setq from-position (point))
15766       (insert-rectangle
15767        (column-of-graph height (car numbers-list)))
15768       (goto-char from-position)
15769       (forward-char symbol-width)
15770 @end group
15771 @group
15772       ;; @r{Draw graph column by column.}
15773       (sit-for 0)
15774       (setq numbers-list (cdr numbers-list)))
15775 @end group
15776 @group
15777     ;; @r{Place point for X axis labels.}
15778     (forward-line height)
15779     (insert "\n")
15781 @end group
15782 @end smallexample
15784 @noindent
15785 The one unexpected expression in this function is the
15786 @w{@code{(sit-for 0)}} expression in the @code{while} loop.  This
15787 expression makes the graph printing operation more interesting to
15788 watch than it would be otherwise.  The expression causes Emacs to
15789 `sit' or do nothing for a zero length of time and then redraw the
15790 screen.  Placed here, it causes Emacs to redraw the screen column by
15791 column.  Without it, Emacs would not redraw the screen until the
15792 function exits.
15794 We can test @code{graph-body-print} with a short list of numbers.
15796 @enumerate
15797 @item
15798 Install @code{graph-symbol}, @code{graph-blank},
15799 @code{column-of-graph}, which are in
15800 @iftex
15801 @ref{Readying a Graph, , Readying a Graph},
15802 @end iftex
15803 @ifinfo
15804 @ref{Columns of a graph},
15805 @end ifinfo
15806 and @code{graph-body-print}.
15808 @need 800
15809 @item
15810 Copy the following expression:
15812 @smallexample
15813 (graph-body-print '(1 2 3 4 6 4 3 5 7 6 5 2 3))
15814 @end smallexample
15816 @item
15817 Switch to the @file{*scratch*} buffer and place the cursor where you
15818 want the graph to start.
15820 @item
15821 Type @kbd{M-:} (@code{eval-expression}).
15823 @item
15824 Yank the @code{graph-body-print} expression into the minibuffer
15825 with @kbd{C-y} (@code{yank)}.
15827 @item
15828 Press @key{RET} to evaluate the @code{graph-body-print} expression.
15829 @end enumerate
15831 @need 800
15832 Emacs will print a graph like this:
15834 @smallexample
15835 @group
15836                     *
15837                 *   **
15838                 *  ****
15839                *** ****
15840               ********* *
15841              ************
15842             *************
15843 @end group
15844 @end smallexample
15846 @node recursive-graph-body-print, Printed Axes, graph-body-print, Readying a Graph
15847 @section The @code{recursive-graph-body-print} Function
15848 @findex recursive-graph-body-print
15850 The @code{graph-body-print} function may also be written recursively.
15851 The recursive solution is divided into two parts: an outside `wrapper'
15852 that uses a @code{let} expression to determine the values of several
15853 variables that need only be found once, such as the maximum height of
15854 the graph, and an inside function that is called recursively to print
15855 the graph.
15857 @need 1250
15858 The `wrapper' is uncomplicated:
15860 @smallexample
15861 @group
15862 (defun recursive-graph-body-print (numbers-list)
15863   "Print a bar graph of the NUMBERS-LIST.
15864 The numbers-list consists of the Y-axis values."
15865   (let ((height (apply 'max numbers-list))
15866         (symbol-width (length graph-blank))
15867         from-position)
15868     (recursive-graph-body-print-internal
15869      numbers-list
15870      height
15871      symbol-width)))
15872 @end group
15873 @end smallexample
15875 The recursive function is a little more difficult.  It has four parts:
15876 the `do-again-test', the printing code, the recursive call, and the
15877 `next-step-expression'.  The `do-again-test' is an @code{if}
15878 expression that determines whether the @code{numbers-list} contains
15879 any remaining elements; if it does, the function prints one column of
15880 the graph using the printing code and calls itself again.  The
15881 function calls itself again according to the value produced by the
15882 `next-step-expression' which causes the call to act on a shorter
15883 version of the @code{numbers-list}.
15885 @smallexample
15886 @group
15887 (defun recursive-graph-body-print-internal
15888   (numbers-list height symbol-width)
15889   "Print a bar graph.
15890 Used within recursive-graph-body-print function."
15891 @end group
15893 @group
15894   (if numbers-list
15895       (progn
15896         (setq from-position (point))
15897         (insert-rectangle
15898          (column-of-graph height (car numbers-list)))
15899 @end group
15900 @group
15901         (goto-char from-position)
15902         (forward-char symbol-width)
15903         (sit-for 0)     ; @r{Draw graph column by column.}
15904         (recursive-graph-body-print-internal
15905          (cdr numbers-list) height symbol-width))))
15906 @end group
15907 @end smallexample
15909 @need 1250
15910 After installation, this expression can be tested; here is a sample:
15912 @smallexample
15913 (recursive-graph-body-print '(3 2 5 6 7 5 3 4 6 4 3 2 1))
15914 @end smallexample
15916 @need 800
15917 Here is what @code{recursive-graph-body-print} produces:
15919 @smallexample
15920 @group
15921                 *
15922                **   *
15923               ****  *
15924               **** ***
15925             * *********
15926             ************
15927             *************
15928 @end group
15929 @end smallexample
15931 Either of these two functions, @code{graph-body-print} or
15932 @code{recursive-graph-body-print}, create the body of a graph.
15934 @node Printed Axes, Line Graph Exercise, recursive-graph-body-print, Readying a Graph
15935 @section Need for Printed Axes
15937 A graph needs printed axes, so you can orient yourself.  For a do-once
15938 project, it may be reasonable to draw the axes by hand using Emacs'
15939 Picture mode; but a graph drawing function may be used more than once.
15941 For this reason, I have written enhancements to the basic
15942 @code{print-graph-body} function that automatically print labels for
15943 the horizontal and vertical axes.  Since the label printing functions
15944 do not contain much new material, I have placed their description in
15945 an appendix.  @xref{Full Graph, , A Graph with Labelled Axes}.
15947 @node Line Graph Exercise,  , Printed Axes, Readying a Graph
15948 @section Exercise
15950 Write a line graph version of the graph printing functions.
15952 @node Emacs Initialization, Debugging, Readying a Graph, Top
15953 @chapter Your @file{.emacs} File
15954 @cindex @file{.emacs} file
15955 @cindex Customizing your @file{.emacs} file
15956 @cindex Initialization file
15958 ``You don't have to like Emacs to like it'' -- this seemingly
15959 paradoxical statement is the secret of GNU Emacs.  The plain, `out of
15960 the box' Emacs is a generic tool.  Most people who use it, customize
15961 it to suit themselves.
15963 GNU Emacs is mostly written in Emacs Lisp; this means that by writing
15964 expressions in Emacs Lisp you can change or extend Emacs.
15966 @menu
15967 * Default Configuration::
15968 * Site-wide Init::              You can write site-wide init files.
15969 * defcustom::                   Emacs will write code for you.
15970 * Beginning a .emacs File::     How to write a @code{.emacs file}.
15971 * Text and Auto-fill::          Automatically wrap lines.
15972 * Mail Aliases::                Use abbreviations for email addresses.
15973 * Indent Tabs Mode::            Don't use tabs with @TeX{}
15974 * Keybindings::                 Create some personal keybindings.
15975 * Keymaps::                     More about key binding.
15976 * Loading Files::               Load (i.e., evaluate) files automatically.
15977 * Autoload::                    Make functions available.
15978 * Simple Extension::            Define a function; bind it to a key.
15979 * X11 Colors::                  Colors in version 19 in X.
15980 * Miscellaneous::
15981 * Mode Line::                   How to customize your mode line.
15982 @end menu
15984 @node Default Configuration, Site-wide Init, Emacs Initialization, Emacs Initialization
15985 @ifnottex
15986 @unnumberedsec Emacs' Default Configuration
15987 @end ifnottex
15989 There are those who appreciate Emacs' default configuration.  After
15990 all, Emacs starts you in C mode when you edit a C file, starts you in
15991 Fortran mode when you edit a Fortran file, and starts you in
15992 Fundamental mode when you edit an unadorned file.  This all makes
15993 sense, if you do not know who is going to use Emacs.  Who knows what a
15994 person hopes to do with an unadorned file?  Fundamental mode is the
15995 right default for such a file, just as C mode is the right default for
15996 editing C code.  But when you do know who is going to use Emacs---you,
15997 yourself---then it makes sense to customize Emacs.
15999 For example, I seldom want Fundamental mode when I edit an
16000 otherwise undistinguished file; I want Text mode.  This is why I
16001 customize Emacs: so it suits me.
16003 You can customize and extend Emacs by writing or adapting a
16004 @file{~/.emacs} file.  This is your personal initialization file; its
16005 contents, written in Emacs Lisp, tell Emacs what to do.@footnote{You
16006 may also add @file{.el} to @file{~/.emacs} and call it a
16007 @file{~/.emacs.el} file.  In the past, you were forbidden to type the
16008 extra keystrokes that the name @file{~/.emacs.el} requires, but now
16009 you may.  The new format is consistent with the Emacs Lisp file
16010 naming conventions; the old format saves typing.}
16012 A @file{~/.emacs} file contains Emacs Lisp code.  You can write this
16013 code yourself; or you can use Emacs' @code{customize} feature to write
16014 the code for you.  You can combine your own expressions and
16015 auto-written Customize expressions in your @file{.emacs} file.
16017 (I myself prefer to write my own expressions, except for those,
16018 particularly fonts, that I find easier to manipulate using the
16019 @code{customize} command.  I combine the two methods.)
16021 Most of this chapter is about writing expressions yourself.  It
16022 describes a simple @file{.emacs} file; for more information, see
16023 @ref{Init File, , The Init File, emacs, The GNU Emacs Manual}, and
16024 @ref{Init File, , The Init File, elisp, The GNU Emacs Lisp Reference
16025 Manual}.
16027 @node Site-wide Init, defcustom, Default Configuration, Emacs Initialization
16028 @section Site-wide Initialization Files
16030 @cindex @file{default.el} init file
16031 @cindex @file{site-init.el} init file
16032 @cindex @file{site-load.el} init file
16033 In addition to your personal initialization file, Emacs automatically
16034 loads various site-wide initialization files, if they exist.  These
16035 have the same form as your @file{.emacs} file, but are loaded by
16036 everyone.
16038 Two site-wide initialization files, @file{site-load.el} and
16039 @file{site-init.el}, are loaded into Emacs and then `dumped' if a
16040 `dumped' version of Emacs is created, as is most common.  (Dumped
16041 copies of Emacs load more quickly.  However, once a file is loaded and
16042 dumped, a change to it does not lead to a change in Emacs unless you
16043 load it yourself or re-dump Emacs.  @xref{Building Emacs, , Building
16044 Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the
16045 @file{INSTALL} file.)
16047 Three other site-wide initialization files are loaded automatically
16048 each time you start Emacs, if they exist.  These are
16049 @file{site-start.el}, which is loaded @emph{before} your @file{.emacs}
16050 file, and @file{default.el}, and the terminal type file, which are both
16051 loaded @emph{after} your @file{.emacs} file.
16053 Settings and definitions in your @file{.emacs} file will overwrite
16054 conflicting settings and definitions in a @file{site-start.el} file,
16055 if it exists; but the settings and definitions in a @file{default.el}
16056 or terminal type file will overwrite those in your @file{.emacs} file.
16057 (You can prevent interference from a terminal type file by setting
16058 @code{term-file-prefix} to @code{nil}.  @xref{Simple Extension, , A
16059 Simple Extension}.)
16061 @c Rewritten to avoid overfull hbox.
16062 The @file{INSTALL} file that comes in the distribution contains
16063 descriptions of the @file{site-init.el} and @file{site-load.el} files.
16065 The @file{loadup.el}, @file{startup.el}, and @file{loaddefs.el} files
16066 control loading.  These files are in the @file{lisp} directory of the
16067 Emacs distribution and are worth perusing.
16069 The @file{loaddefs.el} file contains a good many suggestions as to
16070 what to put into your own @file{.emacs} file, or into a site-wide
16071 initialization file.
16073 @node defcustom, Beginning a .emacs File, Site-wide Init, Emacs Initialization
16074 @section Specifying Variables using @code{defcustom}
16075 @findex defcustom
16077 You can specify variables using @code{defcustom} so that you and
16078 others can then use Emacs' @code{customize} feature to set their
16079 values.  (You cannot use @code{customize} to write function
16080 definitions; but you can write @code{defuns} in your @file{.emacs}
16081 file.  Indeed, you can write any Lisp expression in your @file{.emacs}
16082 file.)
16084 The @code{customize} feature depends on the @code{defcustom} special
16085 form.  Although you can use @code{defvar} or @code{setq} for variables
16086 that users set, the @code{defcustom} special form is designed for the
16087 job.
16089 You can use your knowledge of @code{defvar} for writing the
16090 first three arguments for @code{defcustom}.  The first argument to
16091 @code{defcustom} is the name of the variable.  The second argument is
16092 the variable's initial value, if any; and this value is set only if
16093 the value has not already been set.  The third argument is the
16094 documentation.
16096 The fourth and subsequent arguments to @code{defcustom} specify types
16097 and options; these are not featured in @code{defvar}.  (These
16098 arguments are optional.)
16100 Each of these arguments consists of a keyword followed by a value.
16101 Each keyword starts with the character @code{:}.
16103 @need 1250
16104 For example, the customizable user option variable
16105 @code{text-mode-hook} looks like this:
16107 @smallexample
16108 @group
16109 (defcustom text-mode-hook nil
16110   "Normal hook run when entering Text mode and many related modes."
16111   :type 'hook
16112   :options '(turn-on-auto-fill flyspell-mode)
16113   :group 'data)
16114 @end group
16115 @end smallexample
16117 @noindent
16118 The name of the variable is @code{text-mode-hook}; it has no default
16119 value; and its documentation string tells you what it does.
16121 The @code{:type} keyword tells Emacs what kind of data
16122 @code{text-mode-hook} should be set to and how to display the value in
16123 a Customization buffer.
16125 The @code{:options} keyword specifies a suggested list of values for
16126 the variable.  Currently, you can use @code{:options} only for a hook.
16127 The list is only a suggestion; it is not exclusive; a person who sets
16128 the variable may set it to other values; the list shown following the
16129 @code{:options} keyword is intended to offer convenient choices to a
16130 user.
16132 Finally, the @code{:group} keyword tells the Emacs Customization
16133 command in which group the variable is located.  This tells where to
16134 find it.
16136 For more information, see @ref{Customization, , Writing Customization
16137 Definitions, elisp, The GNU Emacs Lisp Reference Manual}.
16139 Consider @code{text-mode-hook} as an example.
16141 There are two ways to customize this variable.  You can use the
16142 customization command or write the appropriate expressions yourself.
16144 @need 800
16145 Using the customization command,  you can type:
16147 @smallexample
16148 M-x customize
16149 @end smallexample
16151 @noindent
16152 and find that the group for editing files of data is called `data'.
16153 Enter that group.  Text Mode Hook is the first member.  You can click
16154 on its various options to set the values.  After you click on the
16155 button to
16157 @smallexample
16158 Save for Future Sessions
16159 @end smallexample
16161 @noindent
16162 Emacs will write an expression into your @file{.emacs} file.
16163 It will look like this:
16165 @smallexample
16166 @group
16167 (custom-set-variables
16168   ;; custom-set-variables was added by Custom --
16169   ;;                           don't edit or cut/paste it!
16170   ;; Your init file should contain only one such instance.
16171  '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))
16172 @end group
16173 @end smallexample
16175 @noindent
16176 (The @code{text-mode-hook-identify} function tells
16177 @code{toggle-text-mode-auto-fill} which buffers are in Text mode.)
16179 In spite of the warning, you certainly may edit, cut, and paste the
16180 expression!  I do all time.  The purpose of the warning is to scare
16181 those who do not know what they are doing, so they do not
16182 inadvertently generate an error.
16184 The @code{custom-set-variables} works somewhat differently than a
16185 @code{setq}.  While I have never learned the differences, I do modify
16186 the @code{custom-set-variables} expressions in my @file{.emacs} file
16187 by hand:  I make the changes in what appears to me to be a reasonable
16188 manner and have not had any problems.  Others prefer to use the
16189 Customization command and let Emacs do the work for them.
16191 Another @code{custom-set-@dots{}} function is @code{custom-set-faces}.
16192 This function sets the various font faces.  Over time, I have set a
16193 considerable number of faces.  Some of the time, I re-set them using
16194 @code{customize}; other times, I simply edit the
16195 @code{custom-set-faces} expression in my @file{.emacs} file itself.
16197 The second way to customize your @code{text-mode-hook} is to set it
16198 yourself in your @file{.emacs} file using code that has nothing to do
16199 with the @code{custom-set-@dots{}} functions.
16201 @need 800
16202 When you do this, and later use @code{customize}, you will see a
16203 message that says
16205 @smallexample
16206 this option has been changed outside the customize buffer.
16207 @end smallexample
16209 @need 800
16210 This message is only a warning.  If you click on the button to
16212 @smallexample
16213 Save for Future Sessions
16214 @end smallexample
16216 @noindent
16217 Emacs will write a @code{custom-set-@dots{}} expression near the end
16218 of your @file{.emacs} file that will be evaluated after your
16219 hand-written expression.  It will, therefore, overrule your
16220 hand-written expression.  No harm will be done.  When you do this,
16221 however, be careful to remember which expression is active; if you
16222 forget, you may confuse yourself.
16224 So long as you remember where the values are set, you will have no
16225 trouble.  In any event, the values are always set in your
16226 initialization file, which is usually called @file{.emacs}.
16228 I myself use @code{customize} for hardly anything.  Mostly, I write
16229 expressions myself.
16231 @node Beginning a .emacs File, Text and Auto-fill, defcustom, Emacs Initialization
16232 @section Beginning a @file{.emacs} File
16233 @cindex @file{.emacs} file, beginning of
16235 When you start Emacs, it loads your @file{.emacs} file unless you tell
16236 it not to by specifying @samp{-q} on the command line.  (The
16237 @code{emacs -q} command gives you a plain, out-of-the-box Emacs.)
16239 A @file{.emacs} file contains Lisp expressions.  Often, these are no
16240 more than expressions to set values; sometimes they are function
16241 definitions.
16243 @xref{Init File, , The Init File @file{~/.emacs}, emacs, The GNU Emacs
16244 Manual}, for a short description of initialization files.
16246 This chapter goes over some of the same ground, but is a walk among
16247 extracts from a complete, long-used @file{.emacs} file---my own.
16249 The first part of the file consists of comments: reminders to myself.
16250 By now, of course, I remember these things, but when I started, I did
16251 not.
16253 @smallexample
16254 @group
16255 ;;;; Bob's .emacs file
16256 ; Robert J. Chassell
16257 ; 26 September 1985
16258 @end group
16259 @end smallexample
16261 @noindent
16262 Look at that date!  I started this file a long time ago.  I have been
16263 adding to it ever since.
16265 @smallexample
16266 @group
16267 ; Each section in this file is introduced by a
16268 ; line beginning with four semicolons; and each
16269 ; entry is introduced by a line beginning with
16270 ; three semicolons.
16271 @end group
16272 @end smallexample
16274 @noindent
16275 This describes the usual conventions for comments in Emacs Lisp.
16276 Everything on a line that follows a semicolon is a comment.  Two,
16277 three, and four semicolons are used as section and subsection
16278 markers.  (@xref{Comments, ,, elisp, The GNU Emacs Lisp Reference
16279 Manual}, for more about comments.)
16281 @smallexample
16282 @group
16283 ;;;; The Help Key
16284 ; Control-h is the help key;
16285 ; after typing control-h, type a letter to
16286 ; indicate the subject about which you want help.
16287 ; For an explanation of the help facility,
16288 ; type control-h two times in a row.
16289 @end group
16290 @end smallexample
16292 @noindent
16293 Just remember: type @kbd{C-h} two times for help.
16295 @smallexample
16296 @group
16297 ; To find out about any mode, type control-h m
16298 ; while in that mode.  For example, to find out
16299 ; about mail mode, enter mail mode and then type
16300 ; control-h m.
16301 @end group
16302 @end smallexample
16304 @noindent
16305 `Mode help', as I call this, is very helpful.  Usually, it tells you
16306 all you need to know.
16308 Of course, you don't need to include comments like these in your
16309 @file{.emacs} file.  I included them in mine because I kept forgetting
16310 about Mode help or the conventions for comments---but I was able to
16311 remember to look here to remind myself.
16313 @node Text and Auto-fill, Mail Aliases, Beginning a .emacs File, Emacs Initialization
16314 @section Text and Auto Fill Mode
16316 Now we come to the part that `turns on' Text mode and
16317 Auto Fill mode.
16319 @smallexample
16320 @group
16321 ;;; Text mode and Auto Fill mode
16322 ; The next three lines put Emacs into Text mode
16323 ; and Auto Fill mode, and are for writers who
16324 ; want to start writing prose rather than code.
16326 (setq default-major-mode 'text-mode)
16327 (add-hook 'text-mode-hook 'text-mode-hook-identify)
16328 (add-hook 'text-mode-hook 'turn-on-auto-fill)
16329 @end group
16330 @end smallexample
16332 Here is the first part of this @file{.emacs} file that does something
16333 besides remind a forgetful human!
16335 The first of the two lines in parentheses tells Emacs to turn on Text
16336 mode when you find a file, @emph{unless} that file should go into some
16337 other mode, such as C mode.
16339 @cindex Per-buffer, local variables list
16340 @cindex Local variables list, per-buffer,
16341 @cindex Automatic mode selection
16342 @cindex Mode selection, automatic
16343 When Emacs reads a file, it looks at the extension to the file name,
16344 if any.  (The extension is the part that comes after a @samp{.}.)  If
16345 the file ends with a @samp{.c} or @samp{.h} extension then Emacs turns
16346 on C mode.  Also, Emacs looks at first nonblank line of the file; if
16347 the line says @w{@samp{-*- C -*-}}, Emacs turns on C mode.  Emacs
16348 possesses a list of extensions and specifications that it uses
16349 automatically.  In addition, Emacs looks near the last page for a
16350 per-buffer, ``local variables list'', if any.
16352 @ifinfo
16353 @xref{Choosing Modes, , How Major Modes are Chosen, emacs, The GNU
16354 Emacs Manual}.
16356 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16357 Manual}.
16358 @end ifinfo
16359 @iftex
16360 See sections ``How Major Modes are Chosen'' and ``Local Variables in
16361 Files'' in @cite{The GNU Emacs Manual}.
16362 @end iftex
16364 Now, back to the @file{.emacs} file.
16366 @need 800
16367 Here is the line again; how does it work?
16369 @cindex Text Mode turned on
16370 @smallexample
16371 (setq default-major-mode 'text-mode)
16372 @end smallexample
16374 @noindent
16375 This line is a short, but complete Emacs Lisp expression.
16377 We are already familiar with @code{setq}.  It sets the following variable,
16378 @code{default-major-mode}, to the subsequent value, which is
16379 @code{text-mode}.  The single quote mark before @code{text-mode} tells
16380 Emacs to deal directly with the @code{text-mode} variable, not with
16381 whatever it might stand for.  @xref{set & setq, , Setting the Value of
16382 a Variable}, for a reminder of how @code{setq} works.  The main point
16383 is that there is no difference between the procedure you use to set
16384 a value in your @file{.emacs} file and the procedure you use anywhere
16385 else in Emacs.
16387 @need 800
16388 Here are the next two lines:
16390 @cindex Auto Fill mode turned on
16391 @findex add-hook
16392 @smallexample
16393 (add-hook 'text-mode-hook 'text-mode-hook-identify)
16394 (add-hook 'text-mode-hook 'turn-on-auto-fill)
16395 @end smallexample
16397 @noindent
16398 In these two lines, the @code{add-hook} command first adds
16399 @code{text-mode-hook-identify} to the variable called
16400 @code{text-mode-hook} and then adds @code{turn-on-auto-fill} to the
16401 variable.
16403 @code{turn-on-auto-fill} is the name of a program, that, you guessed
16404 it!, turns on Auto Fill mode.  @code{text-mode-hook-identify} is a
16405 function that tells @code{toggle-text-mode-auto-fill} which buffers
16406 are in Text mode.
16408 Every time Emacs turns on Text mode, Emacs runs the commands `hooked'
16409 onto Text mode.  So every time Emacs turns on Text mode, Emacs also
16410 turns on Auto Fill mode.
16412 In brief, the first line causes Emacs to enter Text mode when you edit
16413 a file, unless the file name extension, first non-blank line, or local
16414 variables tell Emacs otherwise.
16416 Text mode among other actions, sets the syntax table to work
16417 conveniently for writers.  In Text mode, Emacs considers an apostrophe
16418 as part of a word like a letter; but Emacs does not consider a period
16419 or a space as part of a word.  Thus, @kbd{M-f} moves you over
16420 @samp{it's}.  On the other hand, in C mode, @kbd{M-f} stops just after
16421 the @samp{t} of @samp{it's}.
16423 The second and third lines causes Emacs to turn on Auto Fill mode when
16424 it turns on Text mode.  In Auto Fill mode, Emacs automatically breaks
16425 a line that is too wide and brings the excessively wide part of the
16426 line down to the next line.  Emacs breaks lines between words, not
16427 within them.
16429 When Auto Fill mode is turned off, lines continue to the right as you
16430 type them.  Depending on how you set the value of
16431 @code{truncate-lines}, the words you type either disappear off the
16432 right side of the screen, or else are shown, in a rather ugly and
16433 unreadable manner, as a continuation line on the screen.
16435 @need 1250
16436 In addition, in this part of my @file{.emacs} file, I tell the Emacs
16437 fill commands to insert two spaces after a colon:
16439 @smallexample
16440 (setq colon-double-space t)
16441 @end smallexample
16443 @node Mail Aliases, Indent Tabs Mode, Text and Auto-fill, Emacs Initialization
16444 @section Mail Aliases
16446 Here is a @code{setq} that `turns on' mail aliases, along with more
16447 reminders.
16449 @smallexample
16450 @group
16451 ;;; Mail mode
16452 ; To enter mail mode, type `C-x m'
16453 ; To enter RMAIL (for reading mail),
16454 ; type `M-x rmail'
16456 (setq mail-aliases t)
16457 @end group
16458 @end smallexample
16460 @cindex Mail aliases
16461 @noindent
16462 This @code{setq} command sets the value of the variable
16463 @code{mail-aliases} to @code{t}.  Since @code{t} means true, the line
16464 says, in effect, ``Yes, use mail aliases.''
16466 Mail aliases are convenient short names for long email addresses or
16467 for lists of email addresses.  The file where you keep your `aliases'
16468 is @file{~/.mailrc}.  You write an alias like this:
16470 @smallexample
16471 alias geo george@@foobar.wiz.edu
16472 @end smallexample
16474 @noindent
16475 When you write a message to George, address it to @samp{geo}; the
16476 mailer will automatically expand @samp{geo} to the full address.
16478 @node Indent Tabs Mode, Keybindings, Mail Aliases, Emacs Initialization
16479 @section Indent Tabs Mode
16480 @cindex Tabs, preventing
16481 @findex indent-tabs-mode
16483 By default, Emacs inserts tabs in place of multiple spaces when it
16484 formats a region.  (For example, you might indent many lines of text
16485 all at once with the @code{indent-region} command.)  Tabs look fine on
16486 a terminal or with ordinary printing, but they produce badly indented
16487 output when you use @TeX{} or Texinfo since @TeX{} ignores tabs.
16489 @need 1250
16490 The following turns off Indent Tabs mode:
16492 @smallexample
16493 @group
16494 ;;; Prevent Extraneous Tabs
16495 (setq-default indent-tabs-mode nil)
16496 @end group
16497 @end smallexample
16499 Note that this line uses @code{setq-default} rather than the
16500 @code{setq} command that we have seen before.  The @code{setq-default}
16501 command sets values only in buffers that do not have their own local
16502 values for the variable.
16504 @ifinfo
16505 @xref{Just Spaces, , Tabs vs. Spaces, emacs, The GNU Emacs Manual}.
16507 @xref{File Variables, , Local Variables in Files, emacs, The GNU Emacs
16508 Manual}.
16509 @end ifinfo
16510 @iftex
16511 See sections ``Tabs vs.@: Spaces'' and ``Local Variables in
16512 Files'' in @cite{The GNU Emacs Manual}.
16513 @end iftex
16515 @node Keybindings, Keymaps, Indent Tabs Mode, Emacs Initialization
16516 @section Some Keybindings
16518 Now for some personal keybindings:
16520 @smallexample
16521 @group
16522 ;;; Compare windows
16523 (global-set-key "\C-cw" 'compare-windows)
16524 @end group
16525 @end smallexample
16527 @findex compare-windows
16528 @code{compare-windows} is a nifty command that compares the text in
16529 your current window with text in the next window.  It makes the
16530 comparison by starting at point in each window, moving over text in
16531 each window as far as they match.  I use this command all the time.
16533 This also shows how to set a key globally, for all modes.
16535 @cindex Setting a key globally
16536 @cindex Global set key
16537 @cindex Key setting globally
16538 @findex global-set-key
16539 The command is @code{global-set-key}.  It is followed by the
16540 keybinding.  In a @file{.emacs} file, the keybinding is written as
16541 shown: @code{\C-c} stands for `control-c', which means `press the
16542 control key and the @kbd{c} key at the same time'.  The @code{w} means
16543 `press the @kbd{w} key'.  The keybinding is surrounded by double
16544 quotation marks.  In documentation, you would write this as @kbd{C-c
16545 w}.  (If you were binding a @key{META} key, such as @kbd{M-c}, rather
16546 than a @key{CTL} key, you would write @code{\M-c}.  @xref{Init
16547 Rebinding, , Rebinding Keys in Your Init File, emacs, The GNU Emacs
16548 Manual}, for details.)
16550 The command invoked by the keys is @code{compare-windows}.  Note that
16551 @code{compare-windows} is preceded by a single quote; otherwise, Emacs
16552 would first try to evaluate the symbol to determine its value.
16554 These three things, the double quotation marks, the backslash before
16555 the @samp{C}, and the single quote mark are necessary parts of
16556 keybinding that I tend to forget.  Fortunately, I have come to
16557 remember that I should look at my existing @file{.emacs} file, and
16558 adapt what is there.
16560 As for the keybinding itself: @kbd{C-c w}.  This combines the prefix
16561 key, @kbd{C-c}, with a single character, in this case, @kbd{w}.  This
16562 set of keys, @kbd{C-c} followed by a single character, is strictly
16563 reserved for individuals' own use.  (I call these `own' keys, since
16564 these are for my own use.)  You should always be able to create such a
16565 keybinding for your own use without stomping on someone else's
16566 keybinding.  If you ever write an extension to Emacs, please avoid
16567 taking any of these keys for public use.  Create a key like @kbd{C-c
16568 C-w} instead.  Otherwise, we will run out of `own' keys.
16570 @need 1250
16571 Here is another keybinding, with a comment:
16573 @smallexample
16574 @group
16575 ;;; Keybinding for `occur'
16576 ; I use occur a lot, so let's bind it to a key:
16577 (global-set-key "\C-co" 'occur)
16578 @end group
16579 @end smallexample
16581 @findex occur
16582 The @code{occur} command shows all the lines in the current buffer
16583 that contain a match for a regular expression.  Matching lines are
16584 shown in a buffer called @file{*Occur*}.  That buffer serves as a menu
16585 to jump to occurrences.
16587 @findex global-unset-key
16588 @cindex Unbinding key
16589 @cindex Key unbinding
16590 @need 1250
16591 Here is how to unbind a key, so it does not
16592 work:
16594 @smallexample
16595 @group
16596 ;;; Unbind `C-x f'
16597 (global-unset-key "\C-xf")
16598 @end group
16599 @end smallexample
16601 There is a reason for this unbinding: I found I inadvertently typed
16602 @w{@kbd{C-x f}} when I meant to type @kbd{C-x C-f}.  Rather than find a
16603 file, as I intended, I accidentally set the width for filled text,
16604 almost always to a width I did not want.  Since I hardly ever reset my
16605 default width, I simply unbound the key.
16607 @findex list-buffers, @r{rebound}
16608 @findex buffer-menu, @r{bound to key}
16609 @need 1250
16610 The following rebinds an existing key:
16612 @smallexample
16613 @group
16614 ;;; Rebind `C-x C-b' for `buffer-menu'
16615 (global-set-key "\C-x\C-b" 'buffer-menu)
16616 @end group
16617 @end smallexample
16619 By default, @kbd{C-x C-b} runs the
16620 @code{list-buffers} command.  This command lists
16621 your buffers in @emph{another} window.  Since I
16622 almost always want to do something in that
16623 window, I prefer the  @code{buffer-menu}
16624 command, which not only lists the buffers,
16625 but moves point into that window.
16627 @node Keymaps, Loading Files, Keybindings, Emacs Initialization
16628 @section Keymaps
16629 @cindex Keymaps
16630 @cindex Rebinding keys
16632 Emacs uses @dfn{keymaps} to record which keys call which commands.
16633 When you use @code{global-set-key} to set the keybinding for a single
16634 command in all parts of Emacs, you are specifying the keybinding in
16635 @code{current-global-map}.
16637 Specific modes, such as C mode or Text mode, have their own keymaps;
16638 the mode-specific keymaps override the global map that is shared by
16639 all buffers.
16641 The @code{global-set-key} function binds, or rebinds, the global
16642 keymap.  For example, the following binds the key @kbd{C-x C-b} to the
16643 function @code{buffer-menu}:
16645 @smallexample
16646 (global-set-key "\C-x\C-b" 'buffer-menu)
16647 @end smallexample
16649 Mode-specific keymaps are bound using the @code{define-key} function,
16650 which takes a specific keymap as an argument, as well as the key and
16651 the command.  For example, my @file{.emacs} file contains the
16652 following expression to bind the @code{texinfo-insert-@@group} command
16653 to @kbd{C-c C-c g}:
16655 @smallexample
16656 @group
16657 (define-key texinfo-mode-map "\C-c\C-cg" 'texinfo-insert-@@group)
16658 @end group
16659 @end smallexample
16661 @noindent
16662 The @code{texinfo-insert-@@group} function itself is a little extension
16663 to Texinfo mode that inserts @samp{@@group} into a Texinfo file.  I
16664 use this command all the time and prefer to type the three strokes
16665 @kbd{C-c C-c g} rather than the six strokes @kbd{@@ g r o u p}.
16666 (@samp{@@group} and its matching @samp{@@end group} are commands that
16667 keep all enclosed text together on one page; many multi-line examples
16668 in this book are surrounded by @samp{@@group @dots{} @@end group}.)
16670 @need 1250
16671 Here is the @code{texinfo-insert-@@group} function definition:
16673 @smallexample
16674 @group
16675 (defun texinfo-insert-@@group ()
16676   "Insert the string @@group in a Texinfo buffer."
16677   (interactive)
16678   (beginning-of-line)
16679   (insert "@@group\n"))
16680 @end group
16681 @end smallexample
16683 (Of course, I could have used Abbrev mode to save typing, rather than
16684 write a function to insert a word; but I prefer key strokes consistent
16685 with other Texinfo mode key bindings.)
16687 You will see numerous @code{define-key} expressions in
16688 @file{loaddefs.el} as well as in the various mode libraries, such as
16689 @file{cc-mode.el} and @file{lisp-mode.el}.
16691 @xref{Key Bindings, , Customizing Key Bindings, emacs, The GNU Emacs
16692 Manual}, and @ref{Keymaps, , Keymaps, elisp, The GNU Emacs Lisp
16693 Reference Manual}, for more information about keymaps.
16695 @node Loading Files, Autoload, Keymaps, Emacs Initialization
16696 @section Loading Files
16697 @cindex Loading files
16698 @c findex load
16700 Many people in the GNU Emacs community have written extensions to
16701 Emacs.  As time goes by, these extensions are often included in new
16702 releases.  For example, the Calendar and Diary packages are now part
16703 of the standard GNU Emacs.
16705 (Calc, which I consider a vital part of Emacs, would be part of the
16706 standard distribution except that it was so large it was packaged
16707 separately and no one has changed that.)
16709 You can use a @code{load} command to evaluate a complete file and
16710 thereby install all the functions and variables in the file into Emacs.
16711 For example:
16713 @c (auto-compression-mode t)
16715 @smallexample
16716 (load "~/emacs/slowsplit")
16717 @end smallexample
16719 This evaluates, i.e.@: loads, the @file{slowsplit.el} file or if it
16720 exists, the faster, byte compiled @file{slowsplit.elc} file from the
16721 @file{emacs} sub-directory of your home directory.  The file contains
16722 the function @code{split-window-quietly}, which John Robinson wrote in
16723 1989.
16725 The @code{split-window-quietly} function splits a window with the
16726 minimum of redisplay.  I installed it in 1989 because it worked well
16727 with the slow 1200 baud terminals I was then using.  Nowadays, I only
16728 occasionally come across such a slow connection, but I continue to use
16729 the function because I like the way it leaves the bottom half of a
16730 buffer in the lower of the new windows and the top half in the upper
16731 window.
16733 @need 1250
16734 To replace the key binding for the default
16735 @code{split-window-vertically}, you must also unset that key and bind
16736 the keys to @code{split-window-quietly}, like this:
16738 @smallexample
16739 @group
16740 (global-unset-key "\C-x2")
16741 (global-set-key "\C-x2" 'split-window-quietly)
16742 @end group
16743 @end smallexample
16745 @vindex load-path
16746 If you load many extensions, as I do, then instead of specifying the
16747 exact location of the extension file, as shown above, you can specify
16748 that directory as part of Emacs' @code{load-path}.  Then, when Emacs
16749 loads a file, it will search that directory as well as its default
16750 list of directories.  (The default list is specified in @file{paths.h}
16751 when Emacs is built.)
16753 @need 1250
16754 The following command adds your @file{~/emacs} directory to the
16755 existing load path:
16757 @smallexample
16758 @group
16759 ;;; Emacs Load Path
16760 (setq load-path (cons "~/emacs" load-path))
16761 @end group
16762 @end smallexample
16764 Incidentally, @code{load-library} is an interactive interface to the
16765 @code{load} function.  The complete function looks like this:
16767 @findex load-library
16768 @smallexample
16769 @group
16770 (defun load-library (library)
16771   "Load the library named LIBRARY.
16772 This is an interface to the function `load'."
16773   (interactive "sLoad library: ")
16774   (load library))
16775 @end group
16776 @end smallexample
16778 The name of the function, @code{load-library}, comes from the use of
16779 `library' as a conventional synonym for `file'.  The source for the
16780 @code{load-library} command is in the @file{files.el} library.
16782 Another interactive command that does a slightly different job is
16783 @code{load-file}.  @xref{Lisp Libraries, , Libraries of Lisp Code for
16784 Emacs, emacs, The GNU Emacs Manual}, for information on the
16785 distinction between @code{load-library} and this command.
16787 @node Autoload, Simple Extension, Loading Files, Emacs Initialization
16788 @section Autoloading
16789 @findex autoload
16791 Instead of installing a function by loading the file that contains it,
16792 or by evaluating the function definition, you can make the function
16793 available but not actually install it until it is first called.  This
16794 is called @dfn{autoloading}.
16796 When you execute an autoloaded function, Emacs automatically evaluates
16797 the file that contains the definition, and then calls the function.
16799 Emacs starts quicker with autoloaded functions, since their libraries
16800 are not loaded right away; but you need to wait a moment when you
16801 first use such a function, while its containing file is evaluated.
16803 Rarely used functions are frequently autoloaded.  The
16804 @file{loaddefs.el} library contains hundreds of autoloaded functions,
16805 from @code{bookmark-set} to @code{wordstar-mode}.  Of course, you may
16806 come to use a `rare' function frequently.  When you do, you should
16807 load that function's file with a @code{load} expression in your
16808 @file{.emacs} file.
16810 In my @file{.emacs} file for Emacs version 21, I load 12 libraries
16811 that contain functions that would otherwise be autoloaded.  (Actually,
16812 it would have been better to include these files in my `dumped' Emacs
16813 when I built it, but I forgot.  @xref{Building Emacs, , Building
16814 Emacs, elisp, The GNU Emacs Lisp Reference Manual}, and the @file{INSTALL}
16815 file for more about dumping.)
16817 You may also want to include autoloaded expressions in your @file{.emacs}
16818 file.  @code{autoload} is a built-in function that takes up to five
16819 arguments, the final three of which are optional.  The first argument
16820 is the name of the function to be autoloaded; the second is the name
16821 of the file to be loaded.  The third argument is documentation for the
16822 function, and the fourth tells whether the function can be called
16823 interactively.  The fifth argument tells what type of
16824 object---@code{autoload} can handle a keymap or macro as well as a
16825 function (the default is a function).
16827 @need 800
16828 Here is a typical example:
16830 @smallexample
16831 @group
16832 (autoload 'html-helper-mode
16833   "html-helper-mode" "Edit HTML documents" t)
16834 @end group
16835 @end smallexample
16837 @noindent
16838 (@code{html-helper-mode} is an alternative to @code{html-mode}, which
16839 is a standard part of the distribution).
16841 @noindent
16842 This expression autoloads the @code{html-helper-mode} function.  It
16843 takes it from the @file{html-helper-mode.el} file (or from the byte
16844 compiled file @file{html-helper-mode.elc}, if it exists.)  The file
16845 must be located in a directory specified by @code{load-path}.  The
16846 documentation says that this is a mode to help you edit documents
16847 written in the HyperText Markup Language.  You can call this mode
16848 interactively by typing @kbd{M-x html-helper-mode}.  (You need to
16849 duplicate the function's regular documentation in the autoload
16850 expression because the regular function is not yet loaded, so its
16851 documentation is not available.)
16853 @xref{Autoload, , Autoload, elisp, The GNU Emacs Lisp Reference
16854 Manual}, for more information.
16856 @node Simple Extension, X11 Colors, Autoload, Emacs Initialization
16857 @section A Simple Extension: @code{line-to-top-of-window}
16858 @findex line-to-top-of-window
16859 @cindex Simple extension in @file{.emacs} file
16861 Here is a simple extension to Emacs that moves the line point is on to
16862 the top of the window.  I use this all the time, to make text easier
16863 to read.
16865 You can put the following code into a separate file and then load it
16866 from your @file{.emacs} file, or you can include it within your
16867 @file{.emacs} file.
16869 @need 1250
16870 Here is the definition:
16872 @smallexample
16873 @group
16874 ;;; Line to top of window;
16875 ;;; replace three keystroke sequence  C-u 0 C-l
16876 (defun line-to-top-of-window ()
16877   "Move the line point is on to top of window."
16878   (interactive)
16879   (recenter 0))
16880 @end group
16881 @end smallexample
16883 @need 1250
16884 Now for the keybinding.
16886 Nowadays, function keys as well as mouse button events and
16887 non-@sc{ascii} characters are written within square brackets, without
16888 quotation marks.  (In Emacs version 18 and before, you had to write
16889 different function key bindings for each different make of terminal.)
16891 I bind @code{line-to-top-of-window} to my @key{F6} function key like
16892 this:
16894 @smallexample
16895 (global-set-key [f6] 'line-to-top-of-window)
16896 @end smallexample
16898 For more information, see @ref{Init Rebinding, , Rebinding Keys in
16899 Your Init File, emacs, The GNU Emacs Manual}.
16901 @cindex Conditional 'twixt two versions of Emacs
16902 @cindex Version of Emacs, choosing
16903 @cindex Emacs version, choosing
16904 If you run two versions of GNU Emacs, such as versions 20 and 21, and
16905 use one @file{.emacs} file, you can select which code to evaluate with
16906 the following conditional:
16908 @smallexample
16909 @group
16910 (cond
16911  ((string-equal (number-to-string 20) (substring (emacs-version) 10 12))
16912   ;; evaluate version 20 code
16913   ( @dots{} ))
16914  ((string-equal (number-to-string 21) (substring (emacs-version) 10 12))
16915   ;; evaluate version 21 code
16916   ( @dots{} )))
16917 @end group
16918 @end smallexample
16920 For example, in contrast to version 20, version 21 blinks its cursor
16921 by default.  I hate such blinking, as well as some other features in
16922 version 21, so I placed the following in my @file{.emacs}
16923 file@footnote{When I start instances of Emacs that do not load my
16924 @file{.emacs} file or any site file, I also turn off blinking:
16926 @smallexample
16927 emacs -q --no-site-file -eval '(blink-cursor-mode nil)'
16928 @end smallexample
16931 @smallexample
16932 @group
16933 (if (string-equal "21" (substring (emacs-version) 10 12))
16934     (progn
16935       (blink-cursor-mode 0)
16936       ;; Insert newline when you press `C-n' (next-line)
16937       ;; at the end of the buffer
16938       (setq next-line-add-newlines t)
16939 @end group
16940 @group
16941       ;; Turn on image viewing
16942       (auto-image-file-mode t)
16943 @end group
16944 @group
16945       ;; Turn on menu bar (this bar has text)
16946       ;; (Use numeric argument to turn on)
16947       (menu-bar-mode 1)
16948 @end group
16949 @group
16950       ;; Turn off tool bar (this bar has icons)
16951       ;; (Use numeric argument to turn on)
16952       (tool-bar-mode nil)
16953 @end group
16954 @group
16955       ;; Turn off tooltip mode for tool bar
16956       ;; (This mode causes icon explanations to pop up)
16957       ;; (Use numeric argument to turn on)
16958       (tooltip-mode nil)
16959       ;; If tooltips turned on, make tips appear promptly
16960       (setq tooltip-delay 0.1)  ; default is one second
16961        ))
16962 @end group
16963 @end smallexample
16965 @noindent
16966 (You will note that instead of typing @code{(number-to-string 21)}, I
16967 decided to save typing and wrote `21' as a string, @code{"21"}, rather
16968 than convert it from an integer to a string.  In this instance, this
16969 expression is better than the longer, but more general
16970 @code{(number-to-string 21)}.  However, if you do not know ahead of
16971 time what type of information will be returned, then the
16972 @code{number-to-string} function will be needed.)
16974 @node X11 Colors, Miscellaneous, Simple Extension, Emacs Initialization
16975 @section X11 Colors
16977 You can specify colors when you use Emacs with the MIT X Windowing
16978 system.
16980 I dislike the default colors and specify my own.
16982 @need 1250
16983 Here are the expressions in my @file{.emacs}
16984 file that set values:
16986 @smallexample
16987 @group
16988 ;; Set cursor color
16989 (set-cursor-color "white")
16991 ;; Set mouse color
16992 (set-mouse-color "white")
16994 ;; Set foreground and background
16995 (set-foreground-color "white")
16996 (set-background-color "darkblue")
16997 @end group
16999 @group
17000 ;;; Set highlighting colors for isearch and drag
17001 (set-face-foreground 'highlight "white")
17002 (set-face-background 'highlight "blue")
17003 @end group
17005 @group
17006 (set-face-foreground 'region "cyan")
17007 (set-face-background 'region "blue")
17008 @end group
17010 @group
17011 (set-face-foreground 'secondary-selection "skyblue")
17012 (set-face-background 'secondary-selection "darkblue")
17013 @end group
17015 @group
17016 ;; Set calendar highlighting colors
17017 (setq calendar-load-hook
17018       '(lambda ()
17019          (set-face-foreground 'diary-face   "skyblue")
17020          (set-face-background 'holiday-face "slate blue")
17021          (set-face-foreground 'holiday-face "white")))
17022 @end group
17023 @end smallexample
17025 The various shades of blue soothe my eye and prevent me from seeing
17026 the screen flicker.
17028 Alternatively, I could have set my specifications in various X
17029 initialization files.  For example, I could set the foreground,
17030 background, cursor, and pointer (i.e., mouse) colors in my
17031 @file{~/.Xresources} file like this:
17033 @smallexample
17034 @group
17035 Emacs*foreground:   white
17036 Emacs*background:   darkblue
17037 Emacs*cursorColor:  white
17038 Emacs*pointerColor: white
17039 @end group
17040 @end smallexample
17042 In any event, since it is not part of Emacs, I set the root color of
17043 my X window in my @file{~/.xinitrc} file, like this@footnote{I
17044 occasionally run more modern window managers, such as Sawfish with
17045 GNOME, Enlightenment, SCWM, or KDE; in those cases, I often specify an
17046 image rather than a plain color.}:
17048 @smallexample
17049 @group
17050 # I use TWM for window manager.
17051 xsetroot -solid Navy -fg white &
17052 @end group
17053 @end smallexample
17055 @node Miscellaneous, Mode Line, X11 Colors, Emacs Initialization
17056 @section Miscellaneous Settings for a @file{.emacs} File
17058 Here are a few miscellaneous settings:
17059 @sp 1
17061 @itemize @minus
17062 @item
17063 Set the shape and color of the mouse cursor:
17064 @smallexample
17065 @group
17066 ; Cursor shapes are defined in
17067 ; `/usr/include/X11/cursorfont.h';
17068 ; for example, the `target' cursor is number 128;
17069 ; the `top_left_arrow' cursor is number 132.
17070 @end group
17072 @group
17073 (let ((mpointer (x-get-resource "*mpointer"
17074                                 "*emacs*mpointer")))
17075   ;; If you have not set your mouse pointer
17076   ;;     then set it, otherwise leave as is:
17077   (if (eq mpointer nil)
17078       (setq mpointer "132")) ; top_left_arrow
17079 @end group
17080 @group
17081   (setq x-pointer-shape (string-to-int mpointer))
17082   (set-mouse-color "white"))
17083 @end group
17084 @end smallexample
17085 @end itemize
17087 @node Mode Line,  , Miscellaneous, Emacs Initialization
17088 @section A Modified Mode Line
17089 @vindex default-mode-line-format
17090 @cindex Mode line format
17092 Finally, a feature I really like: a modified mode line.
17094 When I work over a network, I forget which machine I am using.  Also,
17095 I tend to I lose track of where I am, and which line point is on.
17097 So I reset my mode line to look like this:
17099 @smallexample
17100 -:-- foo.texi   rattlesnake:/home/bob/  Line 1  (Texinfo Fill) Top
17101 @end smallexample
17103 I am visiting a file called @file{foo.texi}, on my machine
17104 @file{rattlesnake} in my @file{/home/bob} buffer.  I am on line 1, in
17105 Texinfo mode, and am at the top of the buffer.
17107 @need 1200
17108 My @file{.emacs} file has a section that looks like this:
17110 @smallexample
17111 @group
17112 ;; Set a Mode Line that tells me which machine, which directory,
17113 ;; and which line I am on, plus the other customary information.
17114 (setq default-mode-line-format
17115  (quote
17116   (#("-" 0 1
17117      (help-echo
17118       "mouse-1: select window, mouse-2: delete others ..."))
17119    mode-line-mule-info
17120    mode-line-modified
17121    mode-line-frame-identification
17122    "    "
17123 @end group
17124 @group
17125    mode-line-buffer-identification
17126    "    "
17127    (:eval (substring
17128            (system-name) 0 (string-match "\\..+" (system-name))))
17129    ":"
17130    default-directory
17131    #(" " 0 1
17132      (help-echo
17133       "mouse-1: select window, mouse-2: delete others ..."))
17134    (line-number-mode " Line %l ")
17135    global-mode-string
17136 @end group
17137 @group
17138    #("   %[(" 0 6
17139      (help-echo
17140       "mouse-1: select window, mouse-2: delete others ..."))
17141    (:eval (mode-line-mode-name))
17142    mode-line-process
17143    minor-mode-alist
17144    #("%n" 0 2 (help-echo "mouse-2: widen" local-map (keymap ...)))
17145    ")%] "
17146    (-3 . "%P")
17147    ;;   "-%-"
17148    )))
17149 @end group
17150 @end smallexample
17152 @noindent
17153 Here, I redefine the default mode line.  Most of the parts are from
17154 the original; but I make a few changes.  I set the @emph{default} mode
17155 line format so as to permit various modes, such as Info, to override
17158 Many elements in the list are self-explanatory:
17159 @code{mode-line-modified} is a variable that tells whether the buffer
17160 has been modified, @code{mode-name} tells the name of the mode, and so
17161 on.  However, the format looks complicated because of two features we
17162 have not discussed.
17164 The first string in the mode line is a dash or hyphen, @samp{-}.  In
17165 the old days, it would have been specified simply as @code{"-"}.  But
17166 nowadays, Emacs can add properties to a string, such as highlighting
17167 or, as in this case, a help feature.  If you place your mouse cursor
17168 over the hyphen, some help information appears  (By default, you must
17169 wait one second before the information appears.  You can change that
17170 timing by changing the value of @code{tooltip-delay}.)
17172 @need 1000
17173 The new string format has a special syntax:
17175 @smallexample
17176 #("-" 0 1 (help-echo "mouse-1: select window, ..."))
17177 @end smallexample
17179 @noindent
17180 The @code{#(} begins a list.  The first element of the list is the
17181 string itself, just one @samp{-}.  The second and third
17182 elements specify the range over which the fourth element applies.  A
17183 range starts @emph{after} a character, so a zero means the range
17184 starts just before the first character; a 1 means that the range ends
17185 just after the first character.  The third element is the property for
17186 the range.  It consists of a property list,  a
17187 property name, in this case, @samp{help-echo}, followed by a value, in this
17188 case, a string.  The second, third, and fourth elements of this new
17189 string format can be repeated.
17191 @xref{Text Props and Strings, , Text Properties in String, elisp, The
17192 GNU Emacs Lisp Reference Manual}, and see @ref{Mode Line Format, , Mode
17193 Line Format, elisp, The GNU Emacs Lisp Reference Manual}, for more
17194 information.
17196 @code{mode-line-buffer-identification}
17197 displays the current buffer name.  It is a list
17198 beginning @code{(#("%12b" 0 4 @dots{}}.
17199 The @code{#(} begins the list.
17201 The @samp{"%12b"} displays the current buffer name, using the
17202 @code{buffer-name} function with which we are familiar; the `12'
17203 specifies the maximum number of characters that will be displayed.
17204 When a name has fewer characters, whitespace is added to fill out to
17205 this number.  (Buffer names can and often should be longer than 12
17206 characters; this length works well in a typical 80 column wide
17207 window.)
17209 @code{:eval} is a new feature in GNU Emacs version 21.  It says to
17210 evaluate the following form and use the result as a string to display.
17211 In this case, the expression displays the first component of the full
17212 system name.  The end of the first component is a @samp{.} (`period'),
17213 so I use the @code{string-match} function to tell me the length of the
17214 first component.  The substring from the zeroth character to that
17215 length is the name of the machine.
17217 @need 1250
17218 This is the expression:
17220 @smallexample
17221 @group
17222 (:eval (substring
17223         (system-name) 0 (string-match "\\..+" (system-name))))
17224 @end group
17225 @end smallexample
17227 @samp{%[} and @samp{%]} cause a pair of square brackets
17228 to appear for each recursive editing level.  @samp{%n} says `Narrow'
17229 when narrowing is in effect.  @samp{%P} tells you the percentage of
17230 the buffer that is above the bottom of the window, or `Top', `Bottom',
17231 or `All'.  (A lower case @samp{p} tell you the percentage above the
17232 @emph{top} of the window.)  @samp{%-} inserts enough dashes to fill
17233 out the line.
17235 Remember, ``You don't have to like Emacs to like it'' --- your own
17236 Emacs can have different colors, different commands, and different
17237 keys than a default Emacs.
17239 On the other hand, if you want to bring up a plain `out of the box'
17240 Emacs, with no customization, type:
17242 @smallexample
17243 emacs -q
17244 @end smallexample
17246 @noindent
17247 This will start an Emacs that does @emph{not} load your
17248 @file{~/.emacs} initialization file.  A plain, default Emacs.  Nothing
17249 more.
17251 @node Debugging, Conclusion, Emacs Initialization, Top
17252 @chapter Debugging
17253 @cindex debugging
17255 GNU Emacs has two debuggers, @code{debug} and @code{edebug}.  The
17256 first is built into the internals of Emacs and is always with you;
17257 the second requires that you instrument a function before you can use it.
17259 Both debuggers are described extensively in @ref{Debugging, ,
17260 Debugging Lisp Programs, elisp, The GNU Emacs Lisp Reference Manual}.
17261 In this chapter, I will walk through a short example of each.
17263 @menu
17264 * debug::                       How to use the built-in debugger.
17265 * debug-on-entry::              Start debugging when you call a function.
17266 * debug-on-quit::               Start debugging when you quit with @kbd{C-g}.
17267 * edebug::                      How to use Edebug, a source level debugger.
17268 * Debugging Exercises::
17269 @end menu
17271 @node debug, debug-on-entry, Debugging, Debugging
17272 @section @code{debug}
17273 @findex debug
17275 Suppose you have written a function definition that is intended to
17276 return the sum of the numbers 1 through a given number.  (This is the
17277 @code{triangle} function discussed earlier.  @xref{Decrementing
17278 Example, , Example with Decrementing Counter}, for a discussion.)
17279 @c xref{Decrementing Loop,, Loop with a Decrementing Counter}, for a discussion.)
17281 However, your function definition has a bug.  You have mistyped
17282 @samp{1=} for @samp{1-}.  Here is the broken definition:
17284 @findex triangle-bugged
17285 @smallexample
17286 @group
17287 (defun triangle-bugged (number)
17288   "Return sum of numbers 1 through NUMBER inclusive."
17289   (let ((total 0))
17290     (while (> number 0)
17291       (setq total (+ total number))
17292       (setq number (1= number)))      ; @r{Error here.}
17293     total))
17294 @end group
17295 @end smallexample
17297 If you are reading this in Info, you can evaluate this definition in
17298 the normal fashion.  You will see @code{triangle-bugged} appear in the
17299 echo area.
17301 @need 1250
17302 Now evaluate the @code{triangle-bugged} function with an
17303 argument of 4:
17305 @smallexample
17306 (triangle-bugged 4)
17307 @end smallexample
17309 @noindent
17310 In GNU Emacs version 21, you will create and enter a
17311 @file{*Backtrace*} buffer that says:
17313 @noindent
17314 @smallexample
17315 @group
17316 ---------- Buffer: *Backtrace* ----------
17317 Debugger entered--Lisp error: (void-function 1=)
17318   (1= number)
17319   (setq number (1= number))
17320   (while (> number 0) (setq total (+ total number))
17321         (setq number (1= number)))
17322   (let ((total 0)) (while (> number 0) (setq total ...)
17323     (setq number ...)) total)
17324   triangle-bugged(4)
17325 @end group
17326 @group
17327   eval((triangle-bugged 4))
17328   eval-last-sexp-1(nil)
17329   eval-last-sexp(nil)
17330   call-interactively(eval-last-sexp)
17331 ---------- Buffer: *Backtrace* ----------
17332 @end group
17333 @end smallexample
17335 @noindent
17336 (I have reformatted this example slightly; the debugger does not fold
17337 long lines.  As usual, you can quit the debugger by typing @kbd{q} in
17338 the @file{*Backtrace*} buffer.)
17340 In practice, for a bug as simple as this, the `Lisp error' line will
17341 tell you what you need to know to correct the definition.  The
17342 function @code{1=} is `void'.
17344 @need 800
17345 In GNU Emacs 20 and before, you will see:
17347 @smallexample
17348 Symbol's function definition is void:@: 1=
17349 @end smallexample
17351 @noindent
17352 which has the same meaning as the @file{*Backtrace*} buffer line in
17353 version 21.
17355 However, suppose you are not quite certain what is going on?
17356 You can read the complete backtrace.
17358 In this case, you need to run GNU Emacs 21, which automatically starts
17359 the debugger that puts you in the @file{*Backtrace*} buffer; or else,
17360 you need to start the debugger manually as described below.
17362 Read the @file{*Backtrace*} buffer from the bottom up; it tells you
17363 what Emacs did that led to the error.  Emacs made an interactive call
17364 to @kbd{C-x C-e} (@code{eval-last-sexp}), which led to the evaluation
17365 of the @code{triangle-bugged} expression.  Each line above tells you
17366 what the Lisp interpreter evaluated next.
17368 @need 1250
17369 The third line from the top of the buffer is
17371 @smallexample
17372 (setq number (1= number))
17373 @end smallexample
17375 @noindent
17376 Emacs tried to evaluate this expression; in order to do so, it tried
17377 to evaluate the inner expression shown on the second line from the
17378 top:
17380 @smallexample
17381 (1= number)
17382 @end smallexample
17384 @need 1250
17385 @noindent
17386 This is where the error occurred; as the top line says:
17388 @smallexample
17389 Debugger entered--Lisp error: (void-function 1=)
17390 @end smallexample
17392 @noindent
17393 You can correct the mistake, re-evaluate the function definition, and
17394 then run your test again.
17396 @node debug-on-entry, debug-on-quit, debug, Debugging
17397 @section @code{debug-on-entry}
17398 @findex debug-on-entry
17400 GNU Emacs 21 starts the debugger automatically when your function has
17401 an error.  GNU Emacs version 20 and before did not; it simply
17402 presented you with an error message.  You had to start the debugger
17403 manually.
17405 You can start the debugger manually for all versions of Emacs; the
17406 advantage is that the debugger runs even if you do not have a bug in
17407 your code.  Sometimes your code will be free of bugs!
17409 You can enter the debugger when you call the function by calling
17410 @code{debug-on-entry}.
17412 @need 1250
17413 @noindent
17414 Type:
17416 @smallexample
17417 M-x debug-on-entry RET triangle-bugged RET
17418 @end smallexample
17420 @need 1250
17421 @noindent
17422 Now, evaluate the following:
17424 @smallexample
17425 (triangle-bugged 5)
17426 @end smallexample
17428 @noindent
17429 All versions of Emacs will create a @file{*Backtrace*} buffer and tell
17430 you that it is beginning to evaluate the @code{triangle-bugged}
17431 function:
17433 @smallexample
17434 @group
17435 ---------- Buffer: *Backtrace* ----------
17436 Debugger entered--entering a function:
17437 * triangle-bugged(5)
17438   eval((triangle-bugged 5))
17439 @end group
17440 @group
17441   eval-last-sexp-1(nil)
17442   eval-last-sexp(nil)
17443   call-interactively(eval-last-sexp)
17444 ---------- Buffer: *Backtrace* ----------
17445 @end group
17446 @end smallexample
17448 In the @file{*Backtrace*} buffer, type @kbd{d}.  Emacs will evaluate
17449 the first expression in @code{triangle-bugged}; the buffer will look
17450 like this:
17452 @smallexample
17453 @group
17454 ---------- Buffer: *Backtrace* ----------
17455 Debugger entered--beginning evaluation of function call form:
17456 * (let ((total 0)) (while (> number 0) (setq total ...)
17457         (setq number ...)) total)
17458 * triangle-bugged(5)
17459   eval((triangle-bugged 5))
17460 @end group
17461 @group
17462   eval-last-sexp-1(nil)
17463   eval-last-sexp(nil)
17464   call-interactively(eval-last-sexp)
17465 ---------- Buffer: *Backtrace* ----------
17466 @end group
17467 @end smallexample
17469 @noindent
17470 Now, type @kbd{d} again, eight times, slowly.  Each time you type
17471 @kbd{d}, Emacs will evaluate another expression in the function
17472 definition.
17474 @need 1750
17475 Eventually, the buffer will look like this:
17477 @smallexample
17478 @group
17479 ---------- Buffer: *Backtrace* ----------
17480 Debugger entered--beginning evaluation of function call form:
17481 * (setq number (1= number))
17482 * (while (> number 0) (setq total (+ total number))
17483         (setq number (1= number)))
17484 @group
17485 @end group
17486 * (let ((total 0)) (while (> number 0) (setq total ...)
17487         (setq number ...)) total)
17488 * triangle-bugged(5)
17489   eval((triangle-bugged 5))
17490 @group
17491 @end group
17492   eval-last-sexp-1(nil)
17493   eval-last-sexp(nil)
17494   call-interactively(eval-last-sexp)
17495 ---------- Buffer: *Backtrace* ----------
17496 @end group
17497 @end smallexample
17499 @noindent
17500 Finally, after you type @kbd{d} two more times, Emacs will reach the
17501 error, and the top two lines of the @file{*Backtrace*} buffer will look
17502 like this:
17504 @smallexample
17505 @group
17506 ---------- Buffer: *Backtrace* ----------
17507 Debugger entered--Lisp error: (void-function 1=)
17508 * (1= number)
17509 @dots{}
17510 ---------- Buffer: *Backtrace* ----------
17511 @end group
17512 @end smallexample
17514 By typing @kbd{d}, you were able to step through the function.
17516 You can quit a @file{*Backtrace*} buffer by typing @kbd{q} in it; this
17517 quits the trace, but does not cancel @code{debug-on-entry}.
17519 @findex cancel-debug-on-entry
17520 To cancel the effect of @code{debug-on-entry}, call
17521 @code{cancel-debug-on-entry} and the name of the function, like this:
17523 @smallexample
17524 M-x cancel-debug-on-entry RET triangle-bugged RET
17525 @end smallexample
17527 @noindent
17528 (If you are reading this in Info, cancel @code{debug-on-entry} now.)
17530 @node debug-on-quit, edebug, debug-on-entry, Debugging
17531 @section @code{debug-on-quit} and @code{(debug)}
17533 In addition to setting @code{debug-on-error} or calling @code{debug-on-entry},
17534 there are two other ways to start @code{debug}.
17536 @findex debug-on-quit
17537 You can start @code{debug} whenever you type @kbd{C-g}
17538 (@code{keyboard-quit}) by setting the variable @code{debug-on-quit} to
17539 @code{t}.  This is useful for debugging infinite loops.
17541 @need 1500
17542 @cindex @code{(debug)} in code
17543 Or, you can insert a line that says @code{(debug)} into your code
17544 where you want the debugger to start, like this:
17546 @smallexample
17547 @group
17548 (defun triangle-bugged (number)
17549   "Return sum of numbers 1 through NUMBER inclusive."
17550   (let ((total 0))
17551     (while (> number 0)
17552       (setq total (+ total number))
17553       (debug)                         ; @r{Start debugger.}
17554       (setq number (1= number)))      ; @r{Error here.}
17555     total))
17556 @end group
17557 @end smallexample
17559 The @code{debug} function is described in detail in @ref{Debugger, ,
17560 The Lisp Debugger, elisp, The GNU Emacs Lisp Reference Manual}.
17562 @node edebug, Debugging Exercises, debug-on-quit, Debugging
17563 @section The @code{edebug} Source Level Debugger
17564 @cindex Source level debugger
17565 @findex edebug
17567 Edebug is a source level debugger.  Edebug normally displays the
17568 source of the code you are debugging, with an arrow at the left that
17569 shows which line you are currently executing.
17571 You can walk through the execution of a function, line by line, or run
17572 quickly until reaching a @dfn{breakpoint} where execution stops.
17574 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17575 Lisp Reference Manual}.
17577 Here is a bugged function definition for @code{triangle-recursively}.
17578 @xref{Recursive triangle function, , Recursion in place of a counter},
17579 for a review of it.
17581 @smallexample
17582 @group
17583 (defun triangle-recursively-bugged (number)
17584   "Return sum of numbers 1 through NUMBER inclusive.
17585 Uses recursion."
17586   (if (= number 1)
17587       1
17588     (+ number
17589        (triangle-recursively-bugged
17590         (1= number)))))               ; @r{Error here.}
17591 @end group
17592 @end smallexample
17594 @noindent
17595 Normally, you would install this definition by positioning your cursor
17596 after the function's closing parenthesis and typing @kbd{C-x C-e}
17597 (@code{eval-last-sexp}) or else by positioning your cursor within the
17598 definition and typing @kbd{C-M-x} (@code{eval-defun}).  (By default,
17599 the @code{eval-defun} command works only in Emacs Lisp mode or in Lisp
17600 Interactive mode.)
17602 @need 1500
17603 However, to prepare this function definition for Edebug, you must
17604 first @dfn{instrument} the code using a different command.  You can do
17605 this by positioning your cursor within the definition and typing
17607 @smallexample
17608 M-x edebug-defun RET
17609 @end smallexample
17611 @noindent
17612 This will cause Emacs to load Edebug automatically if it is not
17613 already loaded, and properly instrument the function.
17615 After instrumenting the function, place your cursor after the
17616 following expression and type @kbd{C-x C-e} (@code{eval-last-sexp}):
17618 @smallexample
17619 (triangle-recursively-bugged 3)
17620 @end smallexample
17622 @noindent
17623 You will be jumped back to the source for
17624 @code{triangle-recursively-bugged} and the cursor positioned at the
17625 beginning of the @code{if} line of the function.  Also, you will see
17626 an arrowhead at the left hand side of that line.  The arrowhead marks
17627 the line where the function is executing.  (In the following examples,
17628 we show the arrowhead with @samp{=>}; in a windowing system, you may
17629 see the arrowhead as a solid triangle in the window `fringe'.)
17631 @smallexample
17632 =>@point{}(if (= number 1)
17633 @end smallexample
17635 @noindent
17636 @iftex
17637 In the example, the location of point is displayed with a star,
17638 @samp{@point{}} (in Info, it is displayed as @samp{-!-}).
17639 @end iftex
17640 @ifnottex
17641 In the example, the location of point is displayed as @samp{@point{}}
17642 (in a printed book, it is displayed with a five pointed star).
17643 @end ifnottex
17645 If you now press @key{SPC}, point will move to the next expression to
17646 be executed; the line will look like this:
17648 @smallexample
17649 =>(if @point{}(= number 1)
17650 @end smallexample
17652 @noindent
17653 As you continue to press @key{SPC}, point will move from expression to
17654 expression.  At the same time, whenever an expression returns a value,
17655 that value will be displayed in the echo area.  For example, after you
17656 move point past @code{number}, you will see the following:
17658 @smallexample
17659 Result: 3 = C-c
17660 @end smallexample
17662 @noindent
17663 This means the value of @code{number} is 3, which is @sc{ascii}
17664 `control-c' (the third letter of the alphabet).
17666 You can continue moving through the code until you reach the line with
17667 the error.  Before evaluation, that line looks like this:
17669 @smallexample
17670 =>        @point{}(1= number)))))               ; @r{Error here.}
17671 @end smallexample
17673 @need 1250
17674 @noindent
17675 When you press @key{SPC} once again, you will produce an error message
17676 that says:
17678 @smallexample
17679 Symbol's function definition is void:@: 1=
17680 @end smallexample
17682 @noindent
17683 This is the bug.
17685 Press @kbd{q} to quit Edebug.
17687 To remove instrumentation from a function definition, simply
17688 re-evaluate it with a command that does not instrument it.
17689 For example, you could place your cursor after the definition's
17690 closing parenthesis and type @kbd{C-x C-e}.
17692 Edebug does a great deal more than walk with you through a function.
17693 You can set it so it races through on its own, stopping only at an
17694 error or at specified stopping points; you can cause it to display the
17695 changing values of various expressions; you can find out how many
17696 times a function is called, and more.
17698 Edebug is described in @ref{edebug, , Edebug, elisp, The GNU Emacs
17699 Lisp Reference Manual}.
17701 @need 1500
17702 @node Debugging Exercises,  , edebug, Debugging
17703 @section Debugging Exercises
17705 @itemize @bullet
17706 @item
17707 Install the @code{count-words-region} function and then cause it to
17708 enter the built-in debugger when you call it.  Run the command on a
17709 region containing two words.  You will need to press @kbd{d} a
17710 remarkable number of times.  On your system, is a `hook' called after
17711 the command finishes?  (For information on hooks, see @ref{Command
17712 Overview, , Command Loop Overview, elisp, The GNU Emacs Lisp Reference
17713 Manual}.)
17715 @item
17716 Copy @code{count-words-region} into the @file{*scratch*} buffer,
17717 instrument the function for Edebug, and walk through its execution.
17718 The function does not need to have a bug, although you can introduce
17719 one if you wish.  If the function lacks a bug, the walk-through
17720 completes without problems.
17722 @item
17723 While running Edebug, type @kbd{?} to see a list of all the Edebug commands.
17724 (The @code{global-edebug-prefix} is usually @kbd{C-x X}, i.e.@:
17725 @kbd{@key{CTL}-x} followed by an upper case @kbd{X}; use this prefix
17726 for commands made outside of the Edebug debugging buffer.)
17728 @item
17729 In the Edebug debugging buffer, use the @kbd{p}
17730 (@code{edebug-bounce-point}) command to see where in the region the
17731 @code{count-words-region} is working.
17733 @item
17734 Move point to some spot further down function and then type the
17735 @kbd{h} (@code{edebug-goto-here}) command to jump to that location.
17737 @item
17738 Use the @kbd{t} (@code{edebug-trace-mode}) command to cause Edebug to
17739 walk through the function on its own; use an upper case @kbd{T} for
17740 @code{edebug-Trace-fast-mode}.
17742 @item
17743 Set a breakpoint, then run Edebug in Trace mode until it reaches the
17744 stopping point.
17745 @end itemize
17747 @node Conclusion, the-the, Debugging, Top
17748 @chapter Conclusion
17750 We have now reached the end of this Introduction.  You have now
17751 learned enough about programming in Emacs Lisp to set values, to write
17752 simple @file{.emacs} files for yourself and your friends, and write
17753 simple customizations and extensions to Emacs.
17755 This is a place to stop.  Or, if you wish, you can now go onward, and
17756 teach yourself.
17758 You have learned some of the basic nuts and bolts of programming.  But
17759 only some.  There are a great many more brackets and hinges that are
17760 easy to use that we have not touched.
17762 A path you can follow right now lies among the sources to GNU Emacs
17763 and in
17764 @ifnotinfo
17765 @cite{The GNU Emacs Lisp Reference Manual}.
17766 @end ifnotinfo
17767 @ifinfo
17768 @ref{Top, , The GNU Emacs Lisp Reference Manual, elisp, The GNU
17769 Emacs Lisp Reference Manual}.
17770 @end ifinfo
17772 The Emacs Lisp sources are an adventure.  When you read the sources and
17773 come across a function or expression that is unfamiliar, you need to
17774 figure out or find out what it does.
17776 Go to the Reference Manual.  It is a thorough, complete, and fairly
17777 easy-to-read description of Emacs Lisp.  It is written not only for
17778 experts, but for people who know what you know.  (The @cite{Reference
17779 Manual} comes with the standard GNU Emacs distribution.  Like this
17780 introduction, it comes as a Texinfo source file, so you can read it
17781 on-line and as a typeset, printed book.)
17783 Go to the other on-line help that is part of GNU Emacs: the on-line
17784 documentation for all functions, and @code{find-tags}, the program
17785 that takes you to sources.
17787 Here is an example of how I explore the sources.  Because of its name,
17788 @file{simple.el} is the file I looked at first, a long time ago.  As
17789 it happens some of the functions in @file{simple.el} are complicated,
17790 or at least look complicated at first sight.  The @code{open-line}
17791 function, for example, looks complicated.
17793 You may want to walk through this function slowly, as we did with the
17794 @code{forward-sentence} function.
17795 @ifnottex
17796 (@xref{forward-sentence}.)
17797 @end ifnottex
17798 @iftex
17799 (@xref{forward-sentence, , @code{forward-sentence}}.)
17800 @end iftex
17801 Or you may want to skip that function and look at another, such as
17802 @code{split-line}.  You don't need to read all the functions.
17803 According to @code{count-words-in-defun}, the @code{split-line}
17804 function contains 27 words and symbols.
17806 Even though it is short, @code{split-line} contains four expressions
17807 we have not studied: @code{skip-chars-forward}, @code{indent-to},
17808 @code{current-column} and @samp{?\n}.
17810 Consider the @code{skip-chars-forward} function.  (It is part of the
17811 function definition for @code{back-to-indentation}, which is shown in
17812 @ref{Review, , Review}.)
17814 In GNU Emacs, you can find out more about @code{skip-chars-forward} by
17815 typing @kbd{C-h f} (@code{describe-function}) and the name of the
17816 function.  This gives you the function documentation.
17818 You may be able to guess what is done by a well named function such as
17819 @code{indent-to}; or you can look it up, too.  Incidentally, the
17820 @code{describe-function} function itself is in @file{help.el}; it is
17821 one of those long, but decipherable functions.  You can look up
17822 @code{describe-function} using the @kbd{C-h f} command!
17824 In this instance, since the code is Lisp, the @file{*Help*} buffer
17825 contains the name of the library containing the function's source.
17826 You can put point over the name of the library and press the RET key,
17827 which in this situation is bound to @code{help-follow}, and be taken
17828 directly to the source, in the same way as @kbd{M-.}
17829 (@code{find-tag}).
17831 The definition for @code{describe-function} illustrates how to
17832 customize the @code{interactive} expression without using the standard
17833 character codes; and it shows how to create a temporary buffer.
17835 (The @code{indent-to} function is written in C rather than Emacs Lisp;
17836 it is a `built-in' function.  @code{help-follow} only provides you
17837 with the documentation of a built-in function; it does not take you to
17838 the source.  But @code{find-tag} will take you to the source, if
17839 properly set up.)
17841 You can look at a function's source using @code{find-tag}, which is
17842 bound to @kbd{M-.}  Finally, you can find out what the Reference
17843 Manual has to say by visiting the manual in Info, and typing @kbd{i}
17844 (@code{Info-index}) and the name of the function, or by looking up
17845 @code{skip-chars-forward} in the index to a printed copy of the
17846 manual.
17848 Similarly, you can find out what is meant by @samp{?\n}.  You can try
17849 using @code{Info-index} with @samp{?\n}.  It turns out that this
17850 action won't help; but don't give up.  If you search the index for
17851 @samp{\n} without the @samp{?}, you will be taken directly to the
17852 relevant section of the manual.  (@xref{Character Type, , Character
17853 Type, elisp, The GNU Emacs Lisp Reference Manual}.  @samp{?\n} stands
17854 for the newline character.)
17856 Other interesting source files include @file{paragraphs.el},
17857 @file{loaddefs.el}, and @file{loadup.el}.  The @file{paragraphs.el}
17858 file includes short, easily understood functions as well as longer
17859 ones.  The @file{loaddefs.el} file contains the many standard
17860 autoloads and many keymaps.  I have never looked at it all; only at
17861 parts.  @file{loadup.el} is the file that loads the standard parts of
17862 Emacs; it tells you a great deal about how Emacs is built.
17863 (@xref{Building Emacs, , Building Emacs, elisp, The GNU Emacs Lisp
17864 Reference Manual}, for more about building.)
17866 As I said, you have learned some nuts and bolts; however, and very
17867 importantly, we have hardly touched major aspects of programming; I
17868 have said nothing about how to sort information, except to use the
17869 predefined @code{sort} function; I have said nothing about how to store
17870 information, except to use variables and lists; I have said nothing
17871 about how to write programs that write programs.  These are topics for
17872 another, and different kind of book, a different kind of learning.
17874 What you have done is learn enough for much practical work with GNU
17875 Emacs.  What you have done is get started.  This is the end of a
17876 beginning.
17878 @c ================ Appendix ================
17880 @node the-the, Kill Ring, Conclusion, Top
17881 @appendix The @code{the-the} Function
17882 @findex the-the
17883 @cindex Duplicated words function
17884 @cindex Words, duplicated
17886 Sometimes when you you write text, you duplicate words---as with ``you
17887 you'' near the beginning of this sentence.  I find that most
17888 frequently, I duplicate ``the'; hence, I call the function for
17889 detecting duplicated words, @code{the-the}.
17891 @need 1250
17892 As a first step, you could use the following regular expression to
17893 search for duplicates:
17895 @smallexample
17896 \\(\\w+[ \t\n]+\\)\\1
17897 @end smallexample
17899 @noindent
17900 This regexp matches one or more word-constituent characters followed
17901 by one or more spaces, tabs, or newlines.  However, it does not detect
17902 duplicated words on different lines, since the ending of the first
17903 word, the end of the line, is different from the ending of the second
17904 word, a space.  (For more information about regular expressions, see
17905 @ref{Regexp Search, , Regular Expression Searches}, as well as
17906 @ref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
17907 Manual}, and @ref{Regular Expressions, , Regular Expressions, elisp,
17908 The GNU Emacs Lisp Reference Manual}.)
17910 You might try searching just for duplicated word-constituent
17911 characters but that does not work since the pattern detects doubles
17912 such as the two occurrences of `th' in `with the'.
17914 Another possible regexp searches for word-constituent characters
17915 followed by non-word-constituent characters, reduplicated.  Here,
17916 @w{@samp{\\w+}} matches one or more word-constituent characters and
17917 @w{@samp{\\W*}} matches zero or more non-word-constituent characters.
17919 @smallexample
17920 \\(\\(\\w+\\)\\W*\\)\\1
17921 @end smallexample
17923 @noindent
17924 Again, not useful.
17926 Here is the pattern that I use.  It is not perfect, but good enough.
17927 @w{@samp{\\b}} matches the empty string, provided it is at the beginning
17928 or end of a word; @w{@samp{[^@@ \n\t]+}} matches one or more occurrences of
17929 any characters that are @emph{not} an @@-sign, space, newline, or tab.
17931 @smallexample
17932 \\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b
17933 @end smallexample
17935 One can write more complicated expressions, but I found that this
17936 expression is good enough, so I use it.
17938 Here is the @code{the-the} function, as I include it in my
17939 @file{.emacs} file, along with a handy global key binding:
17941 @smallexample
17942 @group
17943 (defun the-the ()
17944   "Search forward for for a duplicated word."
17945   (interactive)
17946   (message "Searching for for duplicated words ...")
17947   (push-mark)
17948 @end group
17949 @group
17950   ;; This regexp is not perfect
17951   ;; but is fairly good over all:
17952   (if (re-search-forward
17953        "\\b\\([^@@ \n\t]+\\)[ \n\t]+\\1\\b" nil 'move)
17954       (message "Found duplicated word.")
17955     (message "End of buffer")))
17956 @end group
17958 @group
17959 ;; Bind `the-the' to  C-c \
17960 (global-set-key "\C-c\\" 'the-the)
17961 @end group
17962 @end smallexample
17964 @sp 1
17965 Here is test text:
17967 @smallexample
17968 @group
17969 one two two three four five
17970 five six seven
17971 @end group
17972 @end smallexample
17974 You can substitute the other regular expressions shown above in the
17975 function definition and try each of them on this list.
17977 @node Kill Ring, Full Graph, the-the, Top
17978 @appendix Handling the Kill Ring
17979 @cindex Kill ring handling
17980 @cindex Handling the kill ring
17981 @cindex Ring, making a list like a
17983 The kill ring is a list that is transformed into a ring by the
17984 workings of the @code{rotate-yank-pointer} function.  The @code{yank}
17985 and @code{yank-pop} commands use the @code{rotate-yank-pointer}
17986 function.  This appendix describes the @code{rotate-yank-pointer}
17987 function as well as both the @code{yank} and the @code{yank-pop}
17988 commands.
17990 @menu
17991 * rotate-yank-pointer::         Move a pointer along a list and around.
17992 * yank::                        Paste a copy of a clipped element.
17993 * yank-pop::                    Insert first element pointed to.
17994 @end menu
17996 @node rotate-yank-pointer, yank, Kill Ring, Kill Ring
17997 @comment  node-name,  next,  previous,  up
17998 @appendixsec The @code{rotate-yank-pointer} Function
17999 @findex rotate-yank-pointer
18001 The @code{rotate-yank-pointer} function changes the element in the kill
18002 ring to which @code{kill-ring-yank-pointer} points.  For example, it can
18003 change  @code{kill-ring-yank-pointer} from pointing to the second
18004 element to point to the third element.
18006 @need 800
18007 Here is the code for @code{rotate-yank-pointer}:
18009 @smallexample
18010 @group
18011 (defun rotate-yank-pointer (arg)
18012   "Rotate the yanking point in the kill ring."
18013   (interactive "p")
18014   (let ((length (length kill-ring)))
18015 @end group
18016 @group
18017     (if (zerop length)
18018         ;; @r{then-part}
18019         (error "Kill ring is empty")
18020 @end group
18021 @group
18022       ;; @r{else-part}
18023       (setq kill-ring-yank-pointer
18024             (nthcdr (% (+ arg
18025                           (- length
18026                              (length
18027                               kill-ring-yank-pointer)))
18028                        length)
18029                     kill-ring)))))
18030 @end group
18031 @end smallexample
18033 @menu
18034 * Understanding rotate-yk-ptr::
18035 * rotate-yk-ptr body::          The body of @code{rotate-yank-pointer}.
18036 @end menu
18038 @node Understanding rotate-yk-ptr, rotate-yk-ptr body, rotate-yank-pointer, rotate-yank-pointer
18039 @ifnottex
18040 @unnumberedsubsec @code{rotate-yank-pointer} in Outline
18041 @end ifnottex
18043 The @code{rotate-yank-pointer} function looks complex, but as usual,
18044 it can be understood by taking it apart piece by piece.  First look at
18045 it in skeletal form:
18047 @smallexample
18048 @group
18049 (defun rotate-yank-pointer (arg)
18050   "Rotate the yanking point in the kill ring."
18051   (interactive "p")
18052   (let @var{varlist}
18053     @var{body}@dots{})
18054 @end group
18055 @end smallexample
18057 This function takes one argument, called @code{arg}.  It has a brief
18058 documentation string; and it is interactive with a small @samp{p}, which
18059 means that the argument must be a processed prefix passed to the
18060 function as a number.
18062 The body of the function definition is a @code{let} expression, which
18063 itself has a body as well as a @var{varlist}.
18065 The @code{let} expression declares a variable that will be only usable
18066 within the bounds of this function.  This variable is called
18067 @code{length} and is bound to a value that is equal to the number of
18068 items in the kill ring.  This is done by using the function called
18069 @code{length}.  (Note that this function has the same name as the
18070 variable called @code{length}; but one use of the word is to name the
18071 function and the other is to name the variable.  The two are quite
18072 distinct.  Similarly, an English speaker will distinguish between the
18073 meanings of the word @samp{ship} when he says: "I must ship this package
18074 immediately." and "I must get aboard the ship immediately.")
18076 The function @code{length} tells the number of items there are in a list,
18077 so @code{(length kill-ring)} returns the number of items there are in the
18078 kill ring.
18080 @node rotate-yk-ptr body,  , Understanding rotate-yk-ptr, rotate-yank-pointer
18081 @comment  node-name,  next,  previous,  up
18082 @appendixsubsec The Body of @code{rotate-yank-pointer}
18084 The body of @code{rotate-yank-pointer} is a @code{let} expression and
18085 the body of the @code{let} expression is an @code{if} expression.
18087 The purpose of the @code{if} expression is to find out whether there is
18088 anything in the kill ring.  If the kill ring is empty, the @code{error}
18089 function stops evaluation of the function and prints a message in the
18090 echo area.  On the other hand, if the kill ring has something in it, the
18091 work of the function is done.
18093 Here is the if-part and then-part of the @code{if} expression:
18095 @findex zerop
18096 @findex error
18097 @smallexample
18098 @group
18099 (if (zerop length)                      ; @r{if-part}
18100     (error "Kill ring is empty")        ; @r{then-part}
18101   @dots{}
18102 @end group
18103 @end smallexample
18105 @noindent
18106 If there is not anything in the kill ring, its length must be zero and
18107 an error message sent to the user: @samp{Kill ring is empty}.  The
18108 @code{if} expression uses the function @code{zerop} which returns true
18109 if the value it is testing is zero.  When @code{zerop} tests true, the
18110 then-part of the @code{if} is evaluated.  The then-part is a list
18111 starting with the function @code{error}, which is a function that is
18112 similar to the @code{message} function (@pxref{message}), in that it
18113 prints a one-line message in the echo area.  However, in addition to
18114 printing a message, @code{error} also stops evaluation of the function
18115 within which it is embedded.  This means that the rest of the function
18116 will not be evaluated if the length of the kill ring is zero.
18118 @menu
18119 * Digression concerning error::  How to mislead humans, but not computers.
18120 * rotate-yk-ptr else-part::     The else-part of the @code{if} expression.
18121 * Remainder Function::          The remainder, @code{%}, function.
18122 * rotate-yk-ptr remainder::     Using @code{%} in @code{rotate-yank-pointer}.
18123 * kill-rng-yk-ptr last elt::    Pointing to the last element.
18124 @end menu
18126 @node Digression concerning error, rotate-yk-ptr else-part, rotate-yk-ptr body, rotate-yk-ptr body
18127 @ifnottex
18128 @unnumberedsubsubsec Digression about the word `error'
18129 @end ifnottex
18131 (In my opinion, it is slightly misleading, at least to humans, to use
18132 the term `error' as the name of the @code{error} function.  A better
18133 term would be `cancel'.  Strictly speaking, of course, you cannot
18134 point to, much less rotate a pointer to a list that has no length, so
18135 from the point of view of the computer, the word `error' is correct.
18136 But a human expects to attempt this sort of thing, if only to find out
18137 whether the kill ring is full or empty.  This is an act of
18138 exploration.
18140 (From the human point of view, the act of exploration and discovery is
18141 not necessarily an error, and therefore should not be labelled as one,
18142 even in the bowels of a computer.  As it is, the code in Emacs implies
18143 that a human who is acting virtuously, by exploring his or her
18144 environment, is making an error.  This is bad.  Even though the computer
18145 takes the same steps as it does when there is an `error', a term such as
18146 `cancel' would have a clearer connotation.)
18148 @node rotate-yk-ptr else-part, Remainder Function, Digression concerning error, rotate-yk-ptr body
18149 @unnumberedsubsubsec The else-part of the @code{if} expression
18151 The else-part of the @code{if} expression is dedicated to setting the
18152 value of @code{kill-ring-yank-pointer} when the kill ring has something
18153 in it.  The code looks like this:
18155 @smallexample
18156 @group
18157 (setq kill-ring-yank-pointer
18158       (nthcdr (% (+ arg
18159                     (- length
18160                        (length kill-ring-yank-pointer)))
18161                  length)
18162               kill-ring)))))
18163 @end group
18164 @end smallexample
18166 This needs some examination.  Clearly, @code{kill-ring-yank-pointer}
18167 is being set to be equal to some @sc{cdr} of the kill ring, using the
18168 @code{nthcdr} function that is described in an earlier section.
18169 (@xref{copy-region-as-kill}.)  But exactly how does it do this?
18171 Before looking at the details of the code let's first consider the
18172 purpose of the @code{rotate-yank-pointer} function.
18174 The @code{rotate-yank-pointer} function changes what
18175 @code{kill-ring-yank-pointer} points to.  If
18176 @code{kill-ring-yank-pointer} starts by pointing to the first element
18177 of a list, a call to @code{rotate-yank-pointer} causes it to point to
18178 the second element; and if @code{kill-ring-yank-pointer} points to the
18179 second element, a call to @code{rotate-yank-pointer} causes it to
18180 point to the third element.  (And if @code{rotate-yank-pointer} is
18181 given an argument greater than 1, it jumps the pointer that many
18182 elements.)
18184 The @code{rotate-yank-pointer} function uses @code{setq} to reset what
18185 the @code{kill-ring-yank-pointer} points to.  If
18186 @code{kill-ring-yank-pointer} points to the first element of the kill
18187 ring, then, in the simplest case, the @code{rotate-yank-pointer}
18188 function must cause it to point to the second element.  Put another
18189 way, @code{kill-ring-yank-pointer} must be reset to have a value equal
18190 to the @sc{cdr} of the kill ring.
18192 @need 1250
18193 That is, under these circumstances,
18195 @smallexample
18196 @group
18197 (setq kill-ring-yank-pointer
18198    ("some text" "a different piece of text" "yet more text"))
18200 (setq kill-ring
18201    ("some text" "a different piece of text" "yet more text"))
18202 @end group
18203 @end smallexample
18205 @need 800
18206 @noindent
18207 the code should do this:
18209 @smallexample
18210 (setq kill-ring-yank-pointer (cdr kill-ring))
18211 @end smallexample
18213 @need 1000
18214 @noindent
18215 As a result, the @code{kill-ring-yank-pointer} will look like this:
18217 @smallexample
18218 @group
18219 kill-ring-yank-pointer
18220      @result{} ("a different piece of text" "yet more text"))
18221 @end group
18222 @end smallexample
18224 The actual @code{setq} expression uses the @code{nthcdr} function to do
18225 the job.
18227 As we have seen before (@pxref{nthcdr}), the @code{nthcdr} function
18228 works by repeatedly taking the @sc{cdr} of a list---it takes the
18229 @sc{cdr} of the @sc{cdr} of the @sc{cdr} @dots{}
18231 @need 800
18232 The two following expressions produce the same result:
18234 @smallexample
18235 @group
18236 (setq kill-ring-yank-pointer (cdr kill-ring))
18238 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18239 @end group
18240 @end smallexample
18242 In the @code{rotate-yank-pointer} function, however, the first
18243 argument to @code{nthcdr} is a rather complex looking expression with
18244 lots of arithmetic inside of it:
18246 @smallexample
18247 @group
18248 (% (+ arg
18249       (- length
18250          (length kill-ring-yank-pointer)))
18251    length)
18252 @end group
18253 @end smallexample
18255 As usual, we need to look at the most deeply embedded expression first
18256 and then work our way towards the light.
18258 The most deeply embedded expression is @code{(length
18259 kill-ring-yank-pointer)}.  This finds the length of the current value of
18260 the @code{kill-ring-yank-pointer}.  (Remember that the
18261 @code{kill-ring-yank-pointer} is the name of a variable whose value is a
18262 list.)
18264 @need 800
18265 The measurement of the length is inside the expression:
18267 @smallexample
18268 (- length (length kill-ring-yank-pointer))
18269 @end smallexample
18271 @noindent
18272 In this expression, the first @code{length} is the variable that was
18273 assigned the length of the kill ring in the @code{let} statement at the
18274 beginning of the function.  (One might think this function would be
18275 clearer if the variable @code{length} were named
18276 @code{length-of-kill-ring} instead; but if you look at the text of the
18277 whole function, you will see that it is so short that naming this
18278 variable @code{length} is not a bother, unless you are pulling the
18279 function apart into very tiny pieces as we are doing here.)
18281 So the line @code{(- length (length kill-ring-yank-pointer))} tells the
18282 difference between the length of the kill ring and the length of the list
18283 whose name is @code{kill-ring-yank-pointer}.
18285 To see how all this fits into the @code{rotate-yank-pointer}
18286 function, let's begin by analyzing the case where
18287 @code{kill-ring-yank-pointer} points to the first element of the kill
18288 ring, just as @code{kill-ring} does, and see what happens when
18289 @code{rotate-yank-pointer} is called with an argument of 1.
18291 The variable @code{length} and the value of the expression
18292 @code{(length kill-ring-yank-pointer)} will be the same since the
18293 variable @code{length} is the length of the kill ring and the
18294 @code{kill-ring-yank-pointer} is pointing to the whole kill ring.
18295 Consequently, the value of
18297 @smallexample
18298 (- length (length kill-ring-yank-pointer))
18299 @end smallexample
18301 @noindent
18302 will be zero.  Since the value of @code{arg} will be 1, this will mean
18303 that the value of the whole expression
18305 @smallexample
18306 (+ arg (- length (length kill-ring-yank-pointer)))
18307 @end smallexample
18309 @noindent
18310 will be 1.
18312 Consequently, the argument to @code{nthcdr} will be found as the result of
18313 the expression
18315 @smallexample
18316 (% 1 length)
18317 @end smallexample
18319 @node Remainder Function, rotate-yk-ptr remainder, rotate-yk-ptr else-part, rotate-yk-ptr body
18320 @unnumberedsubsubsec The @code{%} remainder function
18322 To understand @code{(% 1 length)}, we need to understand @code{%}.
18323 According to its documentation (which I just found by typing @kbd{C-h
18324 f @kbd{%} @key{RET}}), the @code{%} function returns the remainder of
18325 its first argument divided by its second argument.  For example, the
18326 remainder of 5 divided by 2 is 1.  (2 goes into 5 twice with a
18327 remainder of 1.)
18329 What surprises people who don't often do arithmetic is that a smaller
18330 number can be divided by a larger number and have a remainder.  In the
18331 example we just used, 5 was divided by 2.  We can reverse that and ask,
18332 what is the result of dividing 2 by 5?  If you can use fractions, the
18333 answer is obviously 2/5 or .4; but if, as here, you can only use whole
18334 numbers, the result has to be something different.  Clearly, 5 can go into
18335 2 zero times, but what of the remainder?  To see what the answer is,
18336 consider a case that has to be familiar from childhood:
18338 @itemize @bullet
18339 @item
18340 5 divided by 5 is 1 with a remainder of 0;
18342 @item
18343 6 divided by 5 is 1 with a remainder of 1;
18345 @item
18346 7 divided by 5 is 1 with a remainder of 2.
18348 @item
18349 Similarly, 10 divided by 5 is 2 with a remainder of 0;
18351 @item
18352 11 divided by 5 is 2 with a remainder of 1;
18354 @item
18355 12 divided by 5 is 1 with a remainder of 2.
18356 @end itemize
18358 @need 1250
18359 @noindent
18360 By considering the cases as parallel, we can see that
18362 @itemize @bullet
18363 @item
18364 zero divided by 5 must be zero with a remainder of zero;
18366 @item
18367 1 divided by 5 must be zero with a remainder of 1;
18369 @item
18370 2 divided by 5 must be zero with a remainder of 2;
18371 @end itemize
18373 @noindent
18374 and so on.
18376 @need 1250
18377 So, in this code, if the value of @code{length} is 5, then the result of
18378 evaluating
18380 @smallexample
18381 (% 1 5)
18382 @end smallexample
18384 @noindent
18385 is 1.  (I just checked this by placing the cursor after the expression
18386 and typing @kbd{C-x C-e}.  Indeed, 1 is printed in the echo area.)
18388 @node rotate-yk-ptr remainder, kill-rng-yk-ptr last elt, Remainder Function, rotate-yk-ptr body
18389 @unnumberedsubsubsec Using @code{%} in @code{rotate-yank-pointer}
18391 When the @code{kill-ring-yank-pointer} points to the
18392 beginning of the kill ring, and the argument passed to
18393 @code{rotate-yank-pointer} is 1, the @code{%} expression returns 1:
18395 @smallexample
18396 @group
18397 (- length (length kill-ring-yank-pointer))
18398      @result{} 0
18399 @end group
18400 @end smallexample
18402 @need 1250
18403 @noindent
18404 therefore,
18406 @smallexample
18407 @group
18408 (+ arg (- length (length kill-ring-yank-pointer)))
18409      @result{} 1
18410 @end group
18411 @end smallexample
18413 @need 1250
18414 @noindent
18415 and consequently:
18417 @smallexample
18418 @group
18419 (% (+ arg (- length (length kill-ring-yank-pointer)))
18420    length)
18421      @result{} 1
18422 @end group
18423 @end smallexample
18425 @noindent
18426 regardless of the value of @code{length}.
18428 @need 1250
18429 @noindent
18430 As a result of this, the @code{setq kill-ring-yank-pointer} expression
18431 simplifies to:
18433 @smallexample
18434 (setq kill-ring-yank-pointer (nthcdr 1 kill-ring))
18435 @end smallexample
18437 @noindent
18438 What it does is now easy to understand.  Instead of pointing as it did
18439 to the first element of the kill ring, the
18440 @code{kill-ring-yank-pointer} is set to point to the second element.
18442 Clearly, if the argument passed to @code{rotate-yank-pointer} is two, then
18443 the @code{kill-ring-yank-pointer} is set to @code{(nthcdr 2 kill-ring)};
18444 and so on for different values of the argument.
18446 Similarly, if the @code{kill-ring-yank-pointer} starts out pointing to
18447 the second element of the kill ring, its length is shorter than the
18448 length of the kill ring by 1, so the computation of the remainder is
18449 based on the expression @code{(% (+ arg 1) length)}.  This means that
18450 the @code{kill-ring-yank-pointer} is moved from the second element of
18451 the kill ring to the third element if the argument passed to
18452 @code{rotate-yank-pointer} is 1.
18454 @node kill-rng-yk-ptr last elt,  , rotate-yk-ptr remainder, rotate-yk-ptr body
18455 @unnumberedsubsubsec Pointing to the last element
18457 The final question is, what happens if the @code{kill-ring-yank-pointer}
18458 is set to the @emph{last} element of the kill ring?  Will a call to
18459 @code{rotate-yank-pointer} mean that nothing more can be taken from the
18460 kill ring?  The answer is no.  What happens is different and useful.
18461 The @code{kill-ring-yank-pointer} is set to point to the beginning of
18462 the kill ring instead.
18464 Let's see how this works by looking at the code, assuming the length of the
18465 kill ring is 5 and the argument passed to @code{rotate-yank-pointer} is 1.
18466 When the @code{kill-ring-yank-pointer} points to the last element of
18467 the kill ring, its length is 1.  The code looks like this:
18469 @smallexample
18470 (% (+ arg (- length (length kill-ring-yank-pointer))) length)
18471 @end smallexample
18473 @need 1250
18474 When the variables are replaced by their numeric values, the expression
18475 looks like this:
18477 @smallexample
18478 (% (+ 1 (- 5 1)) 5)
18479 @end smallexample
18481 @noindent
18482 This expression can be evaluated by looking at the most embedded inner
18483 expression first and working outwards:  The value of @code{(- 5 1)} is 4;
18484 the sum of @code{(+ 1 4)} is 5; and the remainder of dividing 5 by 5 is
18485 zero.  So what @code{rotate-yank-pointer} will do is
18487 @smallexample
18488 (setq kill-ring-yank-pointer (nthcdr 0 kill-ring))
18489 @end smallexample
18491 @noindent
18492 which will set the @code{kill-ring-yank-pointer} to point to the beginning
18493 of the kill ring.
18495 So what happens with successive calls to @code{rotate-yank-pointer} is that
18496 it moves the @code{kill-ring-yank-pointer} from element to element in the
18497 kill ring until it reaches the end; then it jumps back to the beginning.
18498 And this is why the kill ring is called a ring, since by jumping back to
18499 the beginning, it is as if the list has no end!  (And what is a ring, but
18500 an entity with no end?)
18502 @node yank, yank-pop, rotate-yank-pointer, Kill Ring
18503 @comment  node-name,  next,  previous,  up
18504 @appendixsec @code{yank}
18505 @findex yank
18507 After learning about @code{rotate-yank-pointer}, the code for the
18508 @code{yank} function is almost easy.  It has only one tricky part, which is
18509 the computation of the argument to be passed to @code{rotate-yank-pointer}.
18511 @need 1250
18512 The code looks like this:
18514 @smallexample
18515 @group
18516 (defun yank (&optional arg)
18517   "Reinsert the last stretch of killed text.
18518 More precisely, reinsert the stretch of killed text most
18519 recently killed OR yanked.
18520 With just C-U as argument, same but put point in front
18521 (and mark at end).  With argument n, reinsert the nth
18522 most recently killed stretch of killed text.
18523 See also the command \\[yank-pop]."
18524 @end group
18525 @group
18527   (interactive "*P")
18528   (rotate-yank-pointer (if (listp arg) 0
18529                          (if (eq arg '-) -1
18530                            (1- arg))))
18531   (push-mark (point))
18532   (insert (car kill-ring-yank-pointer))
18533   (if (consp arg)
18534       (exchange-point-and-mark)))
18535 @end group
18536 @end smallexample
18538 Glancing over this code, we can understand the last few lines readily
18539 enough.  The mark is pushed, that is, remembered; then the first element
18540 (the @sc{car}) of what the @code{kill-ring-yank-pointer} points to is
18541 inserted; and then, if the argument passed the function is a
18542 @code{cons}, point and mark are exchanged so the point is put in the
18543 front of the inserted text rather than at the end.  This option is
18544 explained in the documentation.  The function itself is interactive with
18545 @code{"*P"}.  This means it will not work on a read-only buffer, and that
18546 the unprocessed prefix argument is passed to the function.
18548 @menu
18549 * rotate-yk-ptr arg::           Pass the argument to @code{rotate-yank-pointer}.
18550 * rotate-yk-ptr negative arg::  Pass a negative argument.
18551 @end menu
18553 @node rotate-yk-ptr arg, rotate-yk-ptr negative arg, yank, yank
18554 @unnumberedsubsubsec Passing the argument
18556 The hard part of @code{yank} is understanding the computation that
18557 determines the value of the argument passed to
18558 @code{rotate-yank-pointer}.  Fortunately, it is not so difficult as it
18559 looks at first sight.
18561 What happens is that the result of evaluating one or both of the
18562 @code{if} expressions will be a number and that number will be the
18563 argument passed to @code{rotate-yank-pointer}.
18565 @need 1250
18566 Laid out with comments, the code looks like this:
18568 @smallexample
18569 @group
18570 (if (listp arg)                         ; @r{if-part}
18571     0                                   ; @r{then-part}
18572   (if (eq arg '-)                       ; @r{else-part, inner if}
18573       -1                                ; @r{inner if's then-part}
18574     (1- arg))))                         ; @r{inner if's else-part}
18575 @end group
18576 @end smallexample
18578 @noindent
18579 This code consists of two @code{if} expression, one the else-part of
18580 the other.
18582 The first or outer @code{if} expression tests whether the argument
18583 passed to @code{yank} is a list.  Oddly enough, this will be true if
18584 @code{yank} is called without an argument---because then it will be
18585 passed the value of @code{nil} for the optional argument and an
18586 evaluation of @code{(listp nil)} returns true!  So, if no argument is
18587 passed to @code{yank}, the argument passed to
18588 @code{rotate-yank-pointer} inside of @code{yank} is zero.  This means
18589 the pointer is not moved and the first element to which
18590 @code{kill-ring-yank-pointer} points is inserted, as we expect.
18591 Similarly, if the argument for @code{yank} is @kbd{C-u}, this will be
18592 read as a list, so again, a zero will be passed to
18593 @code{rotate-yank-pointer}.  (@kbd{C-u} produces an unprocessed prefix
18594 argument of @code{(4)}, which is a list of one element.)  At the same
18595 time, later in the function, this argument will be read as a
18596 @code{cons} so point will be put in the front and mark at the end of
18597 the insertion.  (The @code{P} argument to @code{interactive} is
18598 designed to provide these values for the case when an optional
18599 argument is not provided or when it is @kbd{C-u}.)
18601 The then-part of the outer @code{if} expression handles the case when
18602 there is no argument or when it is @kbd{C-u}.  The else-part handles the
18603 other situations.  The else-part is itself another @code{if} expression.
18605 The inner @code{if} expression tests whether the argument is a minus
18606 sign.  (This is done by pressing the @key{META} and @kbd{-} keys at the
18607 same time, or the @key{ESC} key and then the @kbd{-} key).  In this
18608 case, the @code{rotate-yank-pointer} function is passed @kbd{-1} as an
18609 argument.  This moves the @code{kill-ring-yank-pointer} backwards, which
18610 is what is desired.
18612 If the true-or-false-test of the inner @code{if} expression is false
18613 (that is, if the argument is not a minus sign), the else-part of the
18614 expression is evaluated.  This is the expression @code{(1- arg)}.
18615 Because of the two @code{if} expressions, it will only occur when the
18616 argument is a positive number or when it is a negative number (not
18617 just a minus sign on its own).  What @code{(1- arg)} does is decrement
18618 the number and return it.  (The @code{1-} function subtracts one from
18619 its argument.)  This means that if the argument to
18620 @code{rotate-yank-pointer} is 1, it is reduced to zero, which means
18621 the first element to which @code{kill-ring-yank-pointer} points is
18622 yanked back, as you would expect.
18624 @node rotate-yk-ptr negative arg,  , rotate-yk-ptr arg, yank
18625 @unnumberedsubsubsec Passing a negative argument
18627 Finally, the question arises, what happens if either the remainder
18628 function, @code{%}, or the @code{nthcdr} function is passed a negative
18629 argument, as they quite well may?
18631 The answers can be found by a quick test.  When @code{(% -1 5)} is
18632 evaluated, a negative number is returned; and if @code{nthcdr} is
18633 called with a negative number, it returns the same value as if it were
18634 called with a first argument of zero.  This can be seen by evaluating
18635 the following code.
18637 Here the @samp{@result{}} points to the result of evaluating the code
18638 preceding it.  This was done by positioning the cursor after the code
18639 and typing @kbd{C-x C-e} (@code{eval-last-sexp}) in the usual fashion.
18640 You can do this if you are reading this in Info inside of GNU Emacs.
18642 @smallexample
18643 @group
18644 (% -1 5)
18645      @result{} -1
18646 @end group
18648 @group
18649 (setq animals '(cats dogs elephants))
18650      @result{} (cats dogs elephants)
18651 @end group
18653 @group
18654 (nthcdr 1 animals)
18655      @result{} (dogs elephants)
18656 @end group
18658 @group
18659 (nthcdr 0 animals)
18660      @result{} (cats dogs elephants)
18661 @end group
18663 @group
18664 (nthcdr -1 animals)
18665      @result{} (cats dogs elephants)
18666 @end group
18667 @end smallexample
18669 So, if a minus sign or a negative number is passed to @code{yank}, the
18670 @code{kill-ring-yank-point} is rotated backwards until it reaches the
18671 beginning of the list.  Then it stays there.  Unlike the other case,
18672 when it jumps from the end of the list to the beginning of the list,
18673 making a ring, it stops.  This makes sense.  You often want to get back
18674 to the most recently clipped out piece of text, but you don't usually
18675 want to insert text from as many as thirty kill commands ago.  So you
18676 need to work through the ring to get to the end, but won't cycle around
18677 it inadvertently if you are trying to come back to the beginning.
18679 Incidentally, any number passed to @code{yank} with a minus sign
18680 preceding it will be treated as @minus{}1.  This is evidently a
18681 simplification for writing the program.  You don't need to jump back
18682 towards the beginning of the kill ring more than one place at a time
18683 and doing this is easier than writing a function to determine the
18684 magnitude of the number that follows the minus sign.
18686 @node yank-pop,  , yank, Kill Ring
18687 @comment  node-name,  next,  previous,  up
18688 @appendixsec @code{yank-pop}
18689 @findex yank-pop
18691 After understanding @code{yank}, the @code{yank-pop} function is easy.
18692 Leaving out the documentation to save space, it looks like this:
18694 @smallexample
18695 @group
18696 (defun yank-pop (arg)
18697   (interactive "*p")
18698   (if (not (eq last-command 'yank))
18699       (error "Previous command was not a yank"))
18700 @end group
18701 @group
18702   (setq this-command 'yank)
18703   (let ((before (< (point) (mark))))
18704     (delete-region (point) (mark))
18705     (rotate-yank-pointer arg)
18706 @end group
18707 @group
18708     (set-mark (point))
18709     (insert (car kill-ring-yank-pointer))
18710     (if before (exchange-point-and-mark))))
18711 @end group
18712 @end smallexample
18714 The function is interactive with a small @samp{p} so the prefix
18715 argument is processed and passed to the function.  The command can
18716 only be used after a previous yank; otherwise an error message is
18717 sent.  This check uses the variable @code{last-command} which is
18718 discussed elsewhere.  (@xref{copy-region-as-kill}.)
18720 The @code{let} clause sets the variable @code{before} to true or false
18721 depending whether point is before or after mark and then the region
18722 between point and mark is deleted.  This is the region that was just
18723 inserted by the previous yank and it is this text that will be
18724 replaced.  Next the @code{kill-ring-yank-pointer} is rotated so that
18725 the previously inserted text is not reinserted yet again.  Mark is set
18726 at the beginning of the place the new text will be inserted and then
18727 the first element to which @code{kill-ring-yank-pointer} points is
18728 inserted.  This leaves point after the new text.  If in the previous
18729 yank, point was left before the inserted text, point and mark are now
18730 exchanged so point is again left in front of the newly inserted text.
18731 That is all there is to it!
18733 @node Full Graph, GNU Free Documentation License, Kill Ring, Top
18734 @appendix A Graph with Labelled Axes
18736 Printed axes help you understand a graph.  They convey scale.  In an
18737 earlier chapter (@pxref{Readying a Graph, ,  Readying a Graph}), we
18738 wrote the code to print the body of a graph.  Here we write the code
18739 for printing and labelling vertical and horizontal axes, along with the
18740 body itself.
18742 @menu
18743 * Labelled Example::
18744 * print-graph Varlist::         @code{let} expression in @code{print-graph}.
18745 * print-Y-axis::                Print a label for the vertical axis.
18746 * print-X-axis::                Print a horizontal label.
18747 * Print Whole Graph::           The function to print a complete graph.
18748 @end menu
18750 @node Labelled Example, print-graph Varlist, Full Graph, Full Graph
18751 @ifnottex
18752 @unnumberedsec Labelled Example Graph
18753 @end ifnottex
18755 Since insertions fill a buffer to the right and below point, the new
18756 graph printing function should first print the Y or vertical axis,
18757 then the body of the graph, and finally the X or horizontal axis.
18758 This sequence lays out for us the contents of the function:
18760 @enumerate
18761 @item
18762 Set up code.
18764 @item
18765 Print Y axis.
18767 @item
18768 Print body of graph.
18770 @item
18771 Print X axis.
18772 @end enumerate
18774 @need 800
18775 Here is an example of how a finished graph should look:
18777 @smallexample
18778 @group
18779     10 -
18780                   *
18781                   *  *
18782                   *  **
18783                   *  ***
18784      5 -      *   *******
18785             * *** *******
18786             *************
18787           ***************
18788      1 - ****************
18789          |   |    |    |
18790          1   5   10   15
18791 @end group
18792 @end smallexample
18794 @noindent
18795 In this graph, both the vertical and the horizontal axes are labelled
18796 with numbers.  However, in some graphs, the horizontal axis is time
18797 and would be better labelled with months, like this:
18799 @smallexample
18800 @group
18801      5 -      *
18802             * ** *
18803             *******
18804           ********** **
18805      1 - **************
18806          |    ^      |
18807          Jan  June   Jan
18808 @end group
18809 @end smallexample
18811 Indeed, with a little thought, we can easily come up with a variety of
18812 vertical and horizontal labelling schemes.  Our task could become
18813 complicated.  But complications breed confusion.  Rather than permit
18814 this, it is better choose a simple labelling scheme for our first
18815 effort, and to modify or replace it later.
18817 @need 1200
18818 These considerations suggest the following outline for the
18819 @code{print-graph} function:
18821 @smallexample
18822 @group
18823 (defun print-graph (numbers-list)
18824   "@var{documentation}@dots{}"
18825   (let ((height  @dots{}
18826         @dots{}))
18827 @end group
18828 @group
18829     (print-Y-axis height @dots{} )
18830     (graph-body-print numbers-list)
18831     (print-X-axis @dots{} )))
18832 @end group
18833 @end smallexample
18835 We can work on each part of the @code{print-graph} function definition
18836 in turn.
18838 @node print-graph Varlist, print-Y-axis, Labelled Example, Full Graph
18839 @comment  node-name,  next,  previous,  up
18840 @appendixsec The @code{print-graph} Varlist
18841 @cindex @code{print-graph} varlist
18843 In writing the @code{print-graph} function, the first task is to write
18844 the varlist in the @code{let} expression.  (We will leave aside for the
18845 moment any thoughts about making the function interactive or about the
18846 contents of its documentation string.)
18848 The varlist should set several values.  Clearly, the top of the label
18849 for the vertical axis must be at least the height of the graph, which
18850 means that we must obtain this information here.  Note that the
18851 @code{print-graph-body} function also requires this information.  There
18852 is no reason to calculate the height of the graph in two different
18853 places, so we should change @code{print-graph-body} from the way we
18854 defined it earlier to take advantage of the calculation.
18856 Similarly, both the function for printing the X axis labels and the
18857 @code{print-graph-body} function need to learn the value of the width of
18858 each symbol.  We can perform the calculation here and change the
18859 definition for @code{print-graph-body} from the way we defined it in the
18860 previous chapter.
18862 The length of the label for the horizontal axis must be at least as long
18863 as the graph.  However, this information is used only in the function
18864 that prints the horizontal axis, so it does not need to be calculated here.
18866 These thoughts lead us directly to the following form for the varlist
18867 in the @code{let} for @code{print-graph}:
18869 @smallexample
18870 @group
18871 (let ((height (apply 'max numbers-list)) ; @r{First version.}
18872       (symbol-width (length graph-blank)))
18873 @end group
18874 @end smallexample
18876 @noindent
18877 As we shall see, this expression is not quite right.
18879 @node print-Y-axis, print-X-axis, print-graph Varlist, Full Graph
18880 @comment  node-name,  next,  previous,  up
18881 @appendixsec The @code{print-Y-axis} Function
18882 @cindex Axis, print vertical
18883 @cindex Y axis printing
18884 @cindex Vertical axis printing
18885 @cindex Print vertical axis
18887 The job of the @code{print-Y-axis} function is to print a label for
18888 the vertical axis that looks like this:
18890 @smallexample
18891 @group
18892     10 -
18897      5 -
18901      1 -
18902 @end group
18903 @end smallexample
18905 @noindent
18906 The function should be passed the height of the graph, and then should
18907 construct and insert the appropriate numbers and marks.
18909 It is easy enough to see in the figure what the Y axis label should
18910 look like; but to say in words, and then to write a function
18911 definition to do the job is another matter.  It is not quite true to
18912 say that we want a number and a tic every five lines: there are only
18913 three lines between the @samp{1} and the @samp{5} (lines 2, 3, and 4),
18914 but four lines between the @samp{5} and the @samp{10} (lines 6, 7, 8,
18915 and 9).  It is better to say that we want a number and a tic mark on
18916 the base line (number 1) and then that we want a number and a tic on
18917 the fifth line from the bottom and on every line that is a multiple of
18918 five.
18920 @menu
18921 * Height of label::             What height for the Y axis?
18922 * Compute a Remainder::         How to compute the remainder of a division.
18923 * Y Axis Element::              Construct a line for the Y axis.
18924 * Y-axis-column::               Generate a list of Y axis labels.
18925 * print-Y-axis Penultimate::    A not quite final version.
18926 @end menu
18928 @node Height of label, Compute a Remainder, print-Y-axis, print-Y-axis
18929 @ifnottex
18930 @unnumberedsubsec What height should the label be?
18931 @end ifnottex
18933 The next issue is what height the label should be?  Suppose the maximum
18934 height of tallest column of the graph is seven.  Should the highest
18935 label on the Y axis be @samp{5 -}, and should the graph stick up above
18936 the label?  Or should the highest label be @samp{7 -}, and mark the peak
18937 of the graph?  Or should the highest label be @code{10 -}, which is a
18938 multiple of five, and be higher than the topmost value of the graph?
18940 The latter form is preferred.  Most graphs are drawn within rectangles
18941 whose sides are an integral number of steps long---5, 10, 15, and so
18942 on for a step distance of five.  But as soon as we decide to use a
18943 step height for the vertical axis, we discover that the simple
18944 expression in the varlist for computing the height is wrong.  The
18945 expression is @code{(apply 'max numbers-list)}.  This returns the
18946 precise height, not the maximum height plus whatever is necessary to
18947 round up to the nearest multiple of five.  A more complex expression
18948 is required.
18950 As usual in cases like this, a complex problem becomes simpler if it is
18951 divided into several smaller problems.
18953 First, consider the case when the highest value of the graph is an
18954 integral multiple of five---when it is 5, 10, 15 ,or some higher
18955 multiple of five.  We can use this value as the Y axis height.
18957 A fairly simply way to determine whether a number is a multiple of
18958 five is to divide it by five and see if the division results in a
18959 remainder.  If there is no remainder, the number is a multiple of
18960 five.  Thus, seven divided by five has a remainder of two, and seven
18961 is not an integral multiple of five.  Put in slightly different
18962 language, more reminiscent of the classroom, five goes into seven
18963 once, with a remainder of two.  However, five goes into ten twice,
18964 with no remainder: ten is an integral multiple of five.
18966 @node Compute a Remainder, Y Axis Element, Height of label, print-Y-axis
18967 @appendixsubsec Side Trip: Compute a Remainder
18969 @findex % @r{(remainder function)}
18970 @cindex Remainder function, @code{%}
18971 In Lisp, the function for computing a remainder is @code{%}.  The
18972 function returns the remainder of its first argument divided by its
18973 second argument.  As it happens, @code{%} is a function in Emacs Lisp
18974 that you cannot discover using @code{apropos}: you find nothing if you
18975 type @kbd{M-x apropos @key{RET} remainder @key{RET}}.  The only way to
18976 learn of the existence of @code{%} is to read about it in a book such
18977 as this or in the Emacs Lisp sources.  The @code{%} function is used
18978 in the code for @code{rotate-yank-pointer}, which is described in an
18979 appendix.  (@xref{rotate-yk-ptr body, , The Body of
18980 @code{rotate-yank-pointer}}.)
18982 You can try the @code{%} function by evaluating the following two
18983 expressions:
18985 @smallexample
18986 @group
18987 (% 7 5)
18989 (% 10 5)
18990 @end group
18991 @end smallexample
18993 @noindent
18994 The first expression returns 2 and the second expression returns 0.
18996 To test whether the returned value is zero or some other number, we
18997 can use the @code{zerop} function.  This function returns @code{t} if
18998 its argument, which must be a number, is zero.
19000 @smallexample
19001 @group
19002 (zerop (% 7 5))
19003      @result{} nil
19005 (zerop (% 10 5))
19006      @result{} t
19007 @end group
19008 @end smallexample
19010 Thus, the following expression will return @code{t} if the height
19011 of the graph is evenly divisible by five:
19013 @smallexample
19014 (zerop (% height 5))
19015 @end smallexample
19017 @noindent
19018 (The value of @code{height}, of course, can be found from @code{(apply
19019 'max numbers-list)}.)
19021 On the other hand, if the value of @code{height} is not a multiple of
19022 five, we want to reset the value to the next higher multiple of five.
19023 This is straightforward arithmetic using functions with which we are
19024 already familiar.  First, we divide the value of @code{height} by five
19025 to determine how many times five goes into the number.  Thus, five
19026 goes into twelve twice.  If we add one to this quotient and multiply by
19027 five, we will obtain the value of the next multiple of five that is
19028 larger than the height.  Five goes into twelve twice.  Add one to two,
19029 and multiply by five; the result is fifteen, which is the next multiple
19030 of five that is higher than twelve.  The Lisp expression for this is:
19032 @smallexample
19033 (* (1+ (/ height 5)) 5)
19034 @end smallexample
19036 @noindent
19037 For example, if you evaluate the following, the result is 15:
19039 @smallexample
19040 (* (1+ (/ 12 5)) 5)
19041 @end smallexample
19043 All through this discussion, we have been using `five' as the value
19044 for spacing labels on the Y axis; but we may want to use some other
19045 value.  For generality, we should replace `five' with a variable to
19046 which we can assign a value.  The best name I can think of for this
19047 variable is @code{Y-axis-label-spacing}.
19049 @need 1250
19050 Using this term, and an @code{if} expression, we produce the
19051 following:
19053 @smallexample
19054 @group
19055 (if (zerop (% height Y-axis-label-spacing))
19056     height
19057   ;; @r{else}
19058   (* (1+ (/ height Y-axis-label-spacing))
19059      Y-axis-label-spacing))
19060 @end group
19061 @end smallexample
19063 @noindent
19064 This expression returns the value of @code{height} itself if the height
19065 is an even multiple of the value of the @code{Y-axis-label-spacing} or
19066 else it computes and returns a value of @code{height} that is equal to
19067 the next higher multiple of the value of the @code{Y-axis-label-spacing}.
19069 We can now include this expression in the @code{let} expression of the
19070 @code{print-graph} function (after first setting the value of
19071 @code{Y-axis-label-spacing}):
19072 @vindex Y-axis-label-spacing
19074 @smallexample
19075 @group
19076 (defvar Y-axis-label-spacing 5
19077   "Number of lines from one Y axis label to next.")
19078 @end group
19080 @group
19081 @dots{}
19082 (let* ((height (apply 'max numbers-list))
19083        (height-of-top-line
19084         (if (zerop (% height Y-axis-label-spacing))
19085             height
19086 @end group
19087 @group
19088           ;; @r{else}
19089           (* (1+ (/ height Y-axis-label-spacing))
19090              Y-axis-label-spacing)))
19091        (symbol-width (length graph-blank))))
19092 @dots{}
19093 @end group
19094 @end smallexample
19096 @noindent
19097 (Note use of the  @code{let*} function: the initial value of height is
19098 computed once by the @code{(apply 'max numbers-list)} expression and
19099 then the resulting value of  @code{height} is used to compute its
19100 final value.  @xref{fwd-para let, , The @code{let*} expression}, for
19101 more about @code{let*}.)
19103 @node Y Axis Element, Y-axis-column, Compute a Remainder, print-Y-axis
19104 @appendixsubsec Construct a Y Axis Element
19106 When we print the vertical axis, we want to insert strings such as
19107 @w{@samp{5 -}} and @w{@samp{10 - }} every five lines.
19108 Moreover, we want the numbers and dashes to line up, so shorter
19109 numbers must be padded with leading spaces.  If some of the strings
19110 use two digit numbers, the strings with single digit numbers must
19111 include a leading blank space before the number.
19113 @findex number-to-string
19114 To figure out the length of the number, the @code{length} function is
19115 used.  But the @code{length} function works only with a string, not with
19116 a number.  So the number has to be converted from being a number to
19117 being a string.  This is done with the @code{number-to-string} function.
19118 For example,
19120 @smallexample
19121 @group
19122 (length (number-to-string 35))
19123      @result{} 2
19125 (length (number-to-string 100))
19126      @result{} 3
19127 @end group
19128 @end smallexample
19130 @noindent
19131 (@code{number-to-string} is also called @code{int-to-string}; you will
19132 see this alternative name in various sources.)
19134 In addition, in each label, each number is followed by a string such
19135 as @w{@samp{ - }}, which we will call the @code{Y-axis-tic} marker.
19136 This variable is defined with @code{defvar}:
19138 @vindex Y-axis-tic
19139 @smallexample
19140 @group
19141 (defvar Y-axis-tic " - "
19142    "String that follows number in a Y axis label.")
19143 @end group
19144 @end smallexample
19146 The length of the Y label is the sum of the length of the Y axis tic
19147 mark and the length of the number of the top of the graph.
19149 @smallexample
19150 (length (concat (number-to-string height) Y-axis-tic)))
19151 @end smallexample
19153 This value will be calculated by the @code{print-graph} function in
19154 its varlist as @code{full-Y-label-width} and passed on.  (Note that we
19155 did not think to include this in the varlist when we first proposed it.)
19157 To make a complete vertical axis label, a tic mark is concatenated
19158 with a number; and the two together may be preceded by one or more
19159 spaces depending on how long the number is.  The label consists of
19160 three parts: the (optional) leading spaces, the number, and the tic
19161 mark.  The function is passed the value of the number for the specific
19162 row, and the value of the width of the top line, which is calculated
19163 (just once) by @code{print-graph}.
19165 @smallexample
19166 @group
19167 (defun Y-axis-element (number full-Y-label-width)
19168   "Construct a NUMBERed label element.
19169 A numbered element looks like this `  5 - ',
19170 and is padded as needed so all line up with
19171 the element for the largest number."
19172 @end group
19173 @group
19174   (let* ((leading-spaces
19175          (- full-Y-label-width
19176             (length
19177              (concat (number-to-string number)
19178                      Y-axis-tic)))))
19179 @end group
19180 @group
19181     (concat
19182      (make-string leading-spaces ? )
19183      (number-to-string number)
19184      Y-axis-tic)))
19185 @end group
19186 @end smallexample
19188 The @code{Y-axis-element} function concatenates together the leading
19189 spaces, if any; the number, as a string; and the tic mark.
19191 To figure out how many leading spaces the label will need, the
19192 function subtracts the actual length of the label---the length of the
19193 number plus the length of the tic mark---from the desired label width.
19195 @findex make-string
19196 Blank spaces are inserted using the @code{make-string} function.  This
19197 function takes two arguments: the first tells it how long the string
19198 will be and the second is a symbol for the character to insert, in a
19199 special format.  The format is a question mark followed by a blank
19200 space, like this, @samp{? }.  @xref{Character Type, , Character Type,
19201 elisp, The GNU Emacs Lisp Reference Manual}, for a description of the
19202 syntax for characters.
19204 The @code{number-to-string} function is used in the concatenation
19205 expression, to convert the number to a string that is concatenated
19206 with the leading spaces and the tic mark.
19208 @node Y-axis-column, print-Y-axis Penultimate, Y Axis Element, print-Y-axis
19209 @appendixsubsec Create a Y Axis Column
19211 The preceding functions provide all the tools needed to construct a
19212 function that generates a list of numbered and blank strings to insert
19213 as the label for the vertical axis:
19215 @findex Y-axis-column
19216 @smallexample
19217 @group
19218 (defun Y-axis-column (height width-of-label)
19219   "Construct list of Y axis labels and blank strings.
19220 For HEIGHT of line above base and WIDTH-OF-LABEL."
19221   (let (Y-axis)
19222 @group
19223 @end group
19224     (while (> height 1)
19225       (if (zerop (% height Y-axis-label-spacing))
19226           ;; @r{Insert label.}
19227           (setq Y-axis
19228                 (cons
19229                  (Y-axis-element height width-of-label)
19230                  Y-axis))
19231 @group
19232 @end group
19233         ;; @r{Else, insert blanks.}
19234         (setq Y-axis
19235               (cons
19236                (make-string width-of-label ? )
19237                Y-axis)))
19238       (setq height (1- height)))
19239     ;; @r{Insert base line.}
19240     (setq Y-axis
19241           (cons (Y-axis-element 1 width-of-label) Y-axis))
19242     (nreverse Y-axis)))
19243 @end group
19244 @end smallexample
19246 In this function, we start with the value of @code{height} and
19247 repetitively subtract one from its value.  After each subtraction, we
19248 test to see whether the value is an integral multiple of the
19249 @code{Y-axis-label-spacing}.  If it is, we construct a numbered label
19250 using the @code{Y-axis-element} function; if not, we construct a
19251 blank label using the @code{make-string} function.  The base line
19252 consists of the number one followed by a tic mark.
19254 @node print-Y-axis Penultimate,  , Y-axis-column, print-Y-axis
19255 @appendixsubsec The Not Quite Final Version of @code{print-Y-axis}
19257 The list constructed by the @code{Y-axis-column} function is passed to
19258 the @code{print-Y-axis} function, which inserts the list as a column.
19260 @findex print-Y-axis
19261 @smallexample
19262 @group
19263 (defun print-Y-axis (height full-Y-label-width)
19264   "Insert Y axis using HEIGHT and FULL-Y-LABEL-WIDTH.
19265 Height must be the maximum height of the graph.
19266 Full width is the width of the highest label element."
19267 ;; Value of height and full-Y-label-width
19268 ;; are passed by `print-graph'.
19269 @end group
19270 @group
19271   (let ((start (point)))
19272     (insert-rectangle
19273      (Y-axis-column height full-Y-label-width))
19274     ;; @r{Place point ready for inserting graph.}
19275     (goto-char start)
19276     ;; @r{Move point forward by value of} full-Y-label-width
19277     (forward-char full-Y-label-width)))
19278 @end group
19279 @end smallexample
19281 The @code{print-Y-axis} uses the @code{insert-rectangle} function to
19282 insert the Y axis labels created by the @code{Y-axis-column} function.
19283 In addition, it places point at the correct position for printing the body of
19284 the graph.
19286 You can test @code{print-Y-axis}:
19288 @enumerate
19289 @item
19290 Install
19292 @smallexample
19293 @group
19294 Y-axis-label-spacing
19295 Y-axis-tic
19296 Y-axis-element
19297 Y-axis-column
19298 print-Y-axis
19299 @end group
19300 @end smallexample
19302 @item
19303 Copy the following expression:
19305 @smallexample
19306 (print-Y-axis 12 5)
19307 @end smallexample
19309 @item
19310 Switch to the @file{*scratch*} buffer and place the cursor where you
19311 want the axis labels to start.
19313 @item
19314 Type @kbd{M-:} (@code{eval-expression}).
19316 @item
19317 Yank the @code{graph-body-print} expression into the minibuffer
19318 with @kbd{C-y} (@code{yank)}.
19320 @item
19321 Press @key{RET} to evaluate the expression.
19322 @end enumerate
19324 Emacs will print labels vertically, the top one being
19325 @w{@samp{10 -@w{ }}}.  (The @code{print-graph} function
19326 will pass the value of @code{height-of-top-line}, which
19327 in this case would end up as 15.)
19329 @node print-X-axis, Print Whole Graph, print-Y-axis, Full Graph
19330 @appendixsec The @code{print-X-axis} Function
19331 @cindex Axis, print horizontal
19332 @cindex X axis printing
19333 @cindex Print horizontal axis
19334 @cindex Horizontal axis printing
19336 X axis labels are much like Y axis labels, except that the tics are on a
19337 line above the numbers.  Labels should look like this:
19339 @smallexample
19340 @group
19341     |   |    |    |
19342     1   5   10   15
19343 @end group
19344 @end smallexample
19346 The first tic is under the first column of the graph and is preceded by
19347 several blank spaces.  These spaces provide room in rows above for the Y
19348 axis labels.  The second, third, fourth, and subsequent tics are all
19349 spaced equally, according to the value of @code{X-axis-label-spacing}.
19351 The second row of the X axis consists of numbers, preceded by several
19352 blank spaces and also separated according to the value of the variable
19353 @code{X-axis-label-spacing}.
19355 The value of the variable @code{X-axis-label-spacing} should itself be
19356 measured in units of @code{symbol-width}, since you may want to change
19357 the width of the symbols that you are using to print the body of the
19358 graph without changing the ways the graph is labelled.
19360 @menu
19361 * Similarities differences::    Much like @code{print-Y-axis}, but not exactly.
19362 * X Axis Tic Marks::            Create tic marks for the horizontal axis.
19363 @end menu
19365 @node Similarities differences, X Axis Tic Marks, print-X-axis, print-X-axis
19366 @ifnottex
19367 @unnumberedsubsec Similarities and differences
19368 @end ifnottex
19370 The @code{print-X-axis} function is constructed in more or less the
19371 same fashion as the @code{print-Y-axis} function except that it has
19372 two lines: the line of tic marks and the numbers.  We will write a
19373 separate function to print each line and then combine them within the
19374 @code{print-X-axis} function.
19376 This is a three step process:
19378 @enumerate
19379 @item
19380 Write a function to print the X axis tic marks, @code{print-X-axis-tic-line}.
19382 @item
19383 Write a function to print the X numbers, @code{print-X-axis-numbered-line}.
19385 @item
19386 Write a function to print both lines, the @code{print-X-axis} function,
19387 using @code{print-X-axis-tic-line} and
19388 @code{print-X-axis-numbered-line}.
19389 @end enumerate
19391 @node X Axis Tic Marks,  , Similarities differences, print-X-axis
19392 @appendixsubsec X Axis Tic Marks
19394 The first function should print the X axis tic marks.  We must specify
19395 the tic marks themselves and their spacing:
19397 @smallexample
19398 @group
19399 (defvar X-axis-label-spacing
19400   (if (boundp 'graph-blank)
19401       (* 5 (length graph-blank)) 5)
19402   "Number of units from one X axis label to next.")
19403 @end group
19404 @end smallexample
19406 @noindent
19407 (Note that the value of @code{graph-blank} is set by another
19408 @code{defvar}.  The @code{boundp} predicate checks whether it has
19409 already been set; @code{boundp} returns @code{nil} if it has not.
19410 If @code{graph-blank} were unbound and we did not use this conditional
19411 construction, in GNU Emacs 21, we would enter the debugger and see an
19412 error message saying
19413 @samp{@w{Debugger entered--Lisp error:} @w{(void-variable graph-blank)}}.)
19415 @need 1200
19416 Here is the @code{defvar} for @code{X-axis-tic-symbol}:
19418 @smallexample
19419 @group
19420 (defvar X-axis-tic-symbol "|"
19421   "String to insert to point to a column in X axis.")
19422 @end group
19423 @end smallexample
19425 @need 1250
19426 The goal is to make a line that looks like this:
19428 @smallexample
19429        |   |    |    |
19430 @end smallexample
19432 The first tic is indented so that it is under the first column, which is
19433 indented to provide space for the Y axis labels.
19435 A tic element consists of the blank spaces that stretch from one tic to
19436 the next plus a tic symbol.  The number of blanks is determined by the
19437 width of the tic symbol and the @code{X-axis-label-spacing}.
19439 @need 1250
19440 The code looks like this:
19442 @smallexample
19443 @group
19444 ;;; X-axis-tic-element
19445 @dots{}
19446 (concat
19447  (make-string
19448   ;; @r{Make a string of blanks.}
19449   (-  (* symbol-width X-axis-label-spacing)
19450       (length X-axis-tic-symbol))
19451   ? )
19452  ;; @r{Concatenate blanks with tic symbol.}
19453  X-axis-tic-symbol)
19454 @dots{}
19455 @end group
19456 @end smallexample
19458 Next, we determine how many blanks are needed to indent the first tic
19459 mark to the first column of the graph.  This uses the value of
19460 @code{full-Y-label-width} passed it by the @code{print-graph} function.
19462 @need 1250
19463 The code to make @code{X-axis-leading-spaces}
19464 looks like this:
19466 @smallexample
19467 @group
19468 ;; X-axis-leading-spaces
19469 @dots{}
19470 (make-string full-Y-label-width ? )
19471 @dots{}
19472 @end group
19473 @end smallexample
19475 We also need to determine the length of the horizontal axis, which is
19476 the length of the numbers list, and the number of tics in the horizontal
19477 axis:
19479 @smallexample
19480 @group
19481 ;; X-length
19482 @dots{}
19483 (length numbers-list)
19484 @end group
19486 @group
19487 ;; tic-width
19488 @dots{}
19489 (* symbol-width X-axis-label-spacing)
19490 @end group
19492 @group
19493 ;; number-of-X-tics
19494 (if (zerop (% (X-length tic-width)))
19495     (/ (X-length tic-width))
19496   (1+ (/ (X-length tic-width))))
19497 @end group
19498 @end smallexample
19500 @need 1250
19501 All this leads us directly to the function for printing the X axis tic line:
19503 @findex print-X-axis-tic-line
19504 @smallexample
19505 @group
19506 (defun print-X-axis-tic-line
19507   (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
19508   "Print tics for X axis."
19509     (insert X-axis-leading-spaces)
19510     (insert X-axis-tic-symbol)  ; @r{Under first column.}
19511 @end group
19512 @group
19513     ;; @r{Insert second tic in the right spot.}
19514     (insert (concat
19515              (make-string
19516               (-  (* symbol-width X-axis-label-spacing)
19517                   ;; @r{Insert white space up to second tic symbol.}
19518                   (* 2 (length X-axis-tic-symbol)))
19519               ? )
19520              X-axis-tic-symbol))
19521 @end group
19522 @group
19523     ;; @r{Insert remaining tics.}
19524     (while (> number-of-X-tics 1)
19525       (insert X-axis-tic-element)
19526       (setq number-of-X-tics (1- number-of-X-tics))))
19527 @end group
19528 @end smallexample
19530 The line of numbers is equally straightforward:
19532 @need 1250
19533 First, we create a numbered element with blank spaces before each number:
19535 @findex X-axis-element
19536 @smallexample
19537 @group
19538 (defun X-axis-element (number)
19539   "Construct a numbered X axis element."
19540   (let ((leading-spaces
19541          (-  (* symbol-width X-axis-label-spacing)
19542              (length (number-to-string number)))))
19543     (concat (make-string leading-spaces ? )
19544             (number-to-string number))))
19545 @end group
19546 @end smallexample
19548 Next, we create the function to print the numbered line, starting with
19549 the number ``1'' under the first column:
19551 @findex print-X-axis-numbered-line
19552 @smallexample
19553 @group
19554 (defun print-X-axis-numbered-line
19555   (number-of-X-tics X-axis-leading-spaces)
19556   "Print line of X-axis numbers"
19557   (let ((number X-axis-label-spacing))
19558     (insert X-axis-leading-spaces)
19559     (insert "1")
19560 @end group
19561 @group
19562     (insert (concat
19563              (make-string
19564               ;; @r{Insert white space up to next number.}
19565               (-  (* symbol-width X-axis-label-spacing) 2)
19566               ? )
19567              (number-to-string number)))
19568 @end group
19569 @group
19570     ;; @r{Insert remaining numbers.}
19571     (setq number (+ number X-axis-label-spacing))
19572     (while (> number-of-X-tics 1)
19573       (insert (X-axis-element number))
19574       (setq number (+ number X-axis-label-spacing))
19575       (setq number-of-X-tics (1- number-of-X-tics)))))
19576 @end group
19577 @end smallexample
19579 Finally, we need to write the @code{print-X-axis} that uses
19580 @code{print-X-axis-tic-line} and
19581 @code{print-X-axis-numbered-line}.
19583 The function must determine the local values of the variables used by both
19584 @code{print-X-axis-tic-line} and @code{print-X-axis-numbered-line}, and
19585 then it must call them.  Also, it must print the carriage return that
19586 separates the two lines.
19588 The function consists of a varlist that specifies five local variables,
19589 and calls to each of the two line printing functions:
19591 @findex print-X-axis
19592 @smallexample
19593 @group
19594 (defun print-X-axis (numbers-list)
19595   "Print X axis labels to length of NUMBERS-LIST."
19596   (let* ((leading-spaces
19597           (make-string full-Y-label-width ? ))
19598 @end group
19599 @group
19600        ;; symbol-width @r{is provided by} graph-body-print
19601        (tic-width (* symbol-width X-axis-label-spacing))
19602        (X-length (length numbers-list))
19603 @end group
19604 @group
19605        (X-tic
19606         (concat
19607          (make-string
19608 @end group
19609 @group
19610           ;; @r{Make a string of blanks.}
19611           (-  (* symbol-width X-axis-label-spacing)
19612               (length X-axis-tic-symbol))
19613           ? )
19614 @end group
19615 @group
19616          ;; @r{Concatenate blanks with tic symbol.}
19617          X-axis-tic-symbol))
19618 @end group
19619 @group
19620        (tic-number
19621         (if (zerop (% X-length tic-width))
19622             (/ X-length tic-width)
19623           (1+ (/ X-length tic-width)))))
19624 @end group
19625 @group
19626     (print-X-axis-tic-line tic-number leading-spaces X-tic)
19627     (insert "\n")
19628     (print-X-axis-numbered-line tic-number leading-spaces)))
19629 @end group
19630 @end smallexample
19632 @need 1250
19633 You can test @code{print-X-axis}:
19635 @enumerate
19636 @item
19637 Install @code{X-axis-tic-symbol}, @code{X-axis-label-spacing},
19638 @code{print-X-axis-tic-line}, as well as @code{X-axis-element},
19639 @code{print-X-axis-numbered-line}, and @code{print-X-axis}.
19641 @item
19642 Copy the following expression:
19644 @smallexample
19645 @group
19646 (progn
19647  (let ((full-Y-label-width 5)
19648        (symbol-width 1))
19649    (print-X-axis
19650     '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))
19651 @end group
19652 @end smallexample
19654 @item
19655 Switch to the @file{*scratch*} buffer and place the cursor where you
19656 want the axis labels to start.
19658 @item
19659 Type @kbd{M-:} (@code{eval-expression}).
19661 @item
19662 Yank the test expression into the minibuffer
19663 with @kbd{C-y} (@code{yank)}.
19665 @item
19666 Press @key{RET} to evaluate the expression.
19667 @end enumerate
19669 @need 1250
19670 Emacs will print the horizontal axis like this:
19672 @smallexample
19673 @group
19674      |   |    |    |    |
19675      1   5   10   15   20
19676 @end group
19677 @end smallexample
19679 @node Print Whole Graph,  , print-X-axis, Full Graph
19680 @appendixsec Printing the Whole Graph
19681 @cindex Printing the whole graph
19682 @cindex Whole graph printing
19683 @cindex Graph, printing all
19685 Now we are nearly ready to print the whole graph.
19687 The function to print the graph with the proper labels follows the
19688 outline we created earlier (@pxref{Full Graph, , A Graph with Labelled
19689 Axes}), but with additions.
19691 @need 1250
19692 Here is the outline:
19694 @smallexample
19695 @group
19696 (defun print-graph (numbers-list)
19697   "@var{documentation}@dots{}"
19698   (let ((height  @dots{}
19699         @dots{}))
19700 @end group
19701 @group
19702     (print-Y-axis height @dots{} )
19703     (graph-body-print numbers-list)
19704     (print-X-axis @dots{} )))
19705 @end group
19706 @end smallexample
19708 @menu
19709 * The final version::           A few changes.
19710 * Test print-graph::            Run a short test.
19711 * Graphing words in defuns::    Executing the final code.
19712 * lambda::                      How to write an anonymous function.
19713 * mapcar::                      Apply a function to elements of a list.
19714 * Another Bug::                 Yet another bug @dots{} most insidious.
19715 * Final printed graph::         The graph itself!
19716 @end menu
19718 @node The final version, Test print-graph, Print Whole Graph, Print Whole Graph
19719 @ifnottex
19720 @unnumberedsubsec Changes for the Final Version
19721 @end ifnottex
19723 The final version is different from what we planned in two ways:
19724 first, it contains additional values calculated once in the varlist;
19725 second, it carries an option to specify the labels' increment per row.
19726 This latter feature turns out to be essential; otherwise, a graph may
19727 have more rows than fit on a display or on a sheet of paper.
19729 @need 1500
19730 This new feature requires a change to the @code{Y-axis-column}
19731 function, to add @code{vertical-step} to it.  The function looks like
19732 this:
19734 @findex Y-axis-column @r{Final version.}
19735 @smallexample
19736 @group
19737 ;;; @r{Final version.}
19738 (defun Y-axis-column
19739   (height width-of-label &optional vertical-step)
19740   "Construct list of labels for Y axis.
19741 HEIGHT is maximum height of graph.
19742 WIDTH-OF-LABEL is maximum width of label.
19743 VERTICAL-STEP, an option, is a positive integer
19744 that specifies how much a Y axis label increments
19745 for each line.  For example, a step of 5 means
19746 that each line is five units of the graph."
19747 @end group
19748 @group
19749   (let (Y-axis
19750         (number-per-line (or vertical-step 1)))
19751     (while (> height 1)
19752       (if (zerop (% height Y-axis-label-spacing))
19753 @end group
19754 @group
19755           ;; @r{Insert label.}
19756           (setq Y-axis
19757                 (cons
19758                  (Y-axis-element
19759                   (* height number-per-line)
19760                   width-of-label)
19761                  Y-axis))
19762 @end group
19763 @group
19764         ;; @r{Else, insert blanks.}
19765         (setq Y-axis
19766               (cons
19767                (make-string width-of-label ? )
19768                Y-axis)))
19769       (setq height (1- height)))
19770 @end group
19771 @group
19772     ;; @r{Insert base line.}
19773     (setq Y-axis (cons (Y-axis-element
19774                         (or vertical-step 1)
19775                         width-of-label)
19776                        Y-axis))
19777     (nreverse Y-axis)))
19778 @end group
19779 @end smallexample
19781 The values for the maximum height of graph and the width of a symbol
19782 are computed by @code{print-graph} in its @code{let} expression; so
19783 @code{graph-body-print} must be changed to accept them.
19785 @findex graph-body-print @r{Final version.}
19786 @smallexample
19787 @group
19788 ;;; @r{Final version.}
19789 (defun graph-body-print (numbers-list height symbol-width)
19790   "Print a bar graph of the NUMBERS-LIST.
19791 The numbers-list consists of the Y-axis values.
19792 HEIGHT is maximum height of graph.
19793 SYMBOL-WIDTH is number of each column."
19794 @end group
19795 @group
19796   (let (from-position)
19797     (while numbers-list
19798       (setq from-position (point))
19799       (insert-rectangle
19800        (column-of-graph height (car numbers-list)))
19801       (goto-char from-position)
19802       (forward-char symbol-width)
19803 @end group
19804 @group
19805       ;; @r{Draw graph column by column.}
19806       (sit-for 0)
19807       (setq numbers-list (cdr numbers-list)))
19808     ;; @r{Place point for X axis labels.}
19809     (forward-line height)
19810     (insert "\n")))
19811 @end group
19812 @end smallexample
19814 @need 1250
19815 Finally, the code for the @code{print-graph} function:
19817 @findex print-graph @r{Final version.}
19818 @smallexample
19819 @group
19820 ;;; @r{Final version.}
19821 (defun print-graph
19822   (numbers-list &optional vertical-step)
19823   "Print labelled bar graph of the NUMBERS-LIST.
19824 The numbers-list consists of the Y-axis values.
19825 @end group
19827 @group
19828 Optionally, VERTICAL-STEP, a positive integer,
19829 specifies how much a Y axis label increments for
19830 each line.  For example, a step of 5 means that
19831 each row is five units."
19832 @end group
19833 @group
19834   (let* ((symbol-width (length graph-blank))
19835          ;; @code{height} @r{is both the largest number}
19836          ;; @r{and the number with the most digits.}
19837          (height (apply 'max numbers-list))
19838 @end group
19839 @group
19840          (height-of-top-line
19841           (if (zerop (% height Y-axis-label-spacing))
19842               height
19843             ;; @r{else}
19844             (* (1+ (/ height Y-axis-label-spacing))
19845                Y-axis-label-spacing)))
19846 @end group
19847 @group
19848          (vertical-step (or vertical-step 1))
19849          (full-Y-label-width
19850           (length
19851 @end group
19852 @group
19853            (concat
19854             (number-to-string
19855              (* height-of-top-line vertical-step))
19856             Y-axis-tic))))
19857 @end group
19859 @group
19860     (print-Y-axis
19861      height-of-top-line full-Y-label-width vertical-step)
19862 @end group
19863 @group
19864     (graph-body-print
19865      numbers-list height-of-top-line symbol-width)
19866     (print-X-axis numbers-list)))
19867 @end group
19868 @end smallexample
19870 @node Test print-graph, Graphing words in defuns, The final version, Print Whole Graph
19871 @appendixsubsec Testing @code{print-graph}
19873 @need 1250
19874 We can test the @code{print-graph} function with a short list of numbers:
19876 @enumerate
19877 @item
19878 Install the final versions of @code{Y-axis-column},
19879 @code{graph-body-print}, and @code{print-graph} (in addition to the
19880 rest of the code.)
19882 @item
19883 Copy the following expression:
19885 @smallexample
19886 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1))
19887 @end smallexample
19889 @item
19890 Switch to the @file{*scratch*} buffer and place the cursor where you
19891 want the axis labels to start.
19893 @item
19894 Type @kbd{M-:} (@code{eval-expression}).
19896 @item
19897 Yank the test expression into the minibuffer
19898 with @kbd{C-y} (@code{yank)}.
19900 @item
19901 Press @key{RET} to evaluate the expression.
19902 @end enumerate
19904 @need 1250
19905 Emacs will print a graph that looks like this:
19907 @smallexample
19908 @group
19909 10 -
19912          *
19913         **   *
19914  5 -   ****  *
19915        **** ***
19916      * *********
19917      ************
19918  1 - *************
19920      |   |    |    |
19921      1   5   10   15
19922 @end group
19923 @end smallexample
19925 On the other hand, if you pass @code{print-graph} a
19926 @code{vertical-step} value of 2, by evaluating this expression:
19928 @smallexample
19929 (print-graph '(3 2 5 6 7 5 3 4 6 4 3 2 1) 2)
19930 @end smallexample
19932 @need 1250
19933 @noindent
19934 The graph looks like this:
19936 @smallexample
19937 @group
19938 20 -
19941          *
19942         **   *
19943 10 -   ****  *
19944        **** ***
19945      * *********
19946      ************
19947  2 - *************
19949      |   |    |    |
19950      1   5   10   15
19951 @end group
19952 @end smallexample
19954 @noindent
19955 (A question: is the `2' on the bottom of the vertical axis a bug or a
19956 feature?  If you think it is a bug, and should be a `1' instead, (or
19957 even a `0'), you can modify the sources.)
19959 @node Graphing words in defuns, lambda, Test print-graph, Print Whole Graph
19960 @appendixsubsec Graphing Numbers of Words and Symbols
19962 Now for the graph for which all this code was written: a graph that
19963 shows how many function definitions contain fewer than 10 words and
19964 symbols, how many contain between 10 and 19 words and symbols, how
19965 many contain between 20 and 29 words and symbols, and so on.
19967 This is a multi-step process.  First make sure you have loaded all the
19968 requisite code.
19970 @need 1500
19971 It is a good idea to reset the value of @code{top-of-ranges} in case
19972 you have set it to some different value.  You can evaluate the
19973 following:
19975 @smallexample
19976 @group
19977 (setq top-of-ranges
19978  '(10  20  30  40  50
19979    60  70  80  90 100
19980   110 120 130 140 150
19981   160 170 180 190 200
19982   210 220 230 240 250
19983   260 270 280 290 300)
19984 @end group
19985 @end smallexample
19987 @noindent
19988 Next create a list of the number of words and symbols in each range.
19990 @need 1500
19991 @noindent
19992 Evaluate the following:
19994 @smallexample
19995 @group
19996 (setq list-for-graph
19997        (defuns-per-range
19998          (sort
19999           (recursive-lengths-list-many-files
20000            (directory-files "/usr/local/emacs/lisp"
20001                             t ".+el$"))
20002           '<)
20003          top-of-ranges))
20004 @end group
20005 @end smallexample
20007 @noindent
20008 On my machine, this takes about an hour.  It looks though 303 Lisp
20009 files in my copy of Emacs version 19.23.  After all that computing,
20010 the @code{list-for-graph} has this value:
20012 @smallexample
20013 @group
20014 (537 1027 955 785 594 483 349 292 224 199 166 120 116 99
20015 90 80 67 48 52 45 41 33 28 26 25 20 12 28 11 13 220)
20016 @end group
20017 @end smallexample
20019 @noindent
20020 This means that my copy of Emacs has 537 function definitions with
20021 fewer than 10 words or symbols in them, 1,027 function definitions
20022 with 10 to 19 words or symbols in them, 955 function definitions with
20023 20 to 29 words or symbols in them, and so on.
20025 Clearly, just by looking at this list we can see that most function
20026 definitions contain ten to thirty words and symbols.
20028 Now for printing.  We do @emph{not} want to print a graph that is
20029 1,030 lines high @dots{}  Instead, we should print a graph that is
20030 fewer than twenty-five lines high.  A graph that height can be
20031 displayed on almost any monitor, and easily printed on a sheet of paper.
20033 This means that each value in @code{list-for-graph} must be reduced to
20034 one-fiftieth its present value.
20036 Here is a short function to do just that, using two functions we have
20037 not yet seen, @code{mapcar} and @code{lambda}.
20039 @smallexample
20040 @group
20041 (defun one-fiftieth (full-range)
20042   "Return list, each number one-fiftieth of previous."
20043  (mapcar '(lambda (arg) (/ arg 50)) full-range))
20044 @end group
20045 @end smallexample
20047 @node lambda, mapcar, Graphing words in defuns, Print Whole Graph
20048 @appendixsubsec A @code{lambda} Expression: Useful Anonymity
20049 @cindex Anonymous function
20050 @findex lambda
20052 @code{lambda} is the symbol for an anonymous function, a function
20053 without a name.  Every time you use an anonymous function, you need to
20054 include its whole body.
20056 @need 1250
20057 @noindent
20058 Thus,
20060 @smallexample
20061 (lambda (arg) (/ arg 50))
20062 @end smallexample
20064 @noindent
20065 is a function definition that says `return the value resulting from
20066 dividing whatever is passed to me as @code{arg} by 50'.
20068 Earlier, for example, we had a function @code{multiply-by-seven}; it
20069 multiplied its argument by 7.  This function is similar, except it
20070 divides its argument by 50; and, it has no name.  The anonymous
20071 equivalent of @code{multiply-by-seven} is:
20073 @smallexample
20074 (lambda (number) (* 7 number))
20075 @end smallexample
20077 @noindent
20078 (@xref{defun, ,  The @code{defun} Special Form}.)
20080 @need 1250
20081 @noindent
20082 If we want to multiply 3 by 7, we can write:
20084 @c !!! Clear print-postscript-figures if the computer formatting this
20085 @c     document is too small and cannot handle all the diagrams and figures.
20086 @c clear print-postscript-figures
20087 @c set print-postscript-figures
20088 @c lambda example diagram #1
20089 @ifnottex
20090 @smallexample
20091 @group
20092 (multiply-by-seven 3)
20093  \_______________/ ^
20094          |         |
20095       function  argument
20096 @end group
20097 @end smallexample
20098 @end ifnottex
20099 @ifset print-postscript-figures
20100 @sp 1
20101 @tex
20102 @image{lambda-1}
20103 %%%% old method of including an image
20104 % \input /usr/local/lib/tex/inputs/psfig.tex
20105 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-1.eps}}
20106 % \catcode`\@=0 %
20107 @end tex
20108 @sp 1
20109 @end ifset
20110 @ifclear print-postscript-figures
20111 @iftex
20112 @smallexample
20113 @group
20114 (multiply-by-seven 3)
20115  \_______________/ ^
20116          |         |
20117       function  argument
20118 @end group
20119 @end smallexample
20120 @end iftex
20121 @end ifclear
20123 @noindent
20124 This expression returns 21.
20126 @need 1250
20127 @noindent
20128 Similarly, we can write:
20130 @c lambda example diagram #2
20131 @ifnottex
20132 @smallexample
20133 @group
20134 ((lambda (number) (* 7 number)) 3)
20135  \____________________________/ ^
20136                |                |
20137       anonymous function     argument
20138 @end group
20139 @end smallexample
20140 @end ifnottex
20141 @ifset print-postscript-figures
20142 @sp 1
20143 @tex
20144 @image{lambda-2}
20145 %%%% old method of including an image
20146 % \input /usr/local/lib/tex/inputs/psfig.tex
20147 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-2.eps}}
20148 % \catcode`\@=0 %
20149 @end tex
20150 @sp 1
20151 @end ifset
20152 @ifclear print-postscript-figures
20153 @iftex
20154 @smallexample
20155 @group
20156 ((lambda (number) (* 7 number)) 3)
20157  \____________________________/ ^
20158                |                |
20159       anonymous function     argument
20160 @end group
20161 @end smallexample
20162 @end iftex
20163 @end ifclear
20165 @need 1250
20166 @noindent
20167 If we want to divide 100 by 50, we can write:
20169 @c lambda example diagram #3
20170 @ifnottex
20171 @smallexample
20172 @group
20173 ((lambda (arg) (/ arg 50)) 100)
20174  \______________________/  \_/
20175              |              |
20176     anonymous function   argument
20177 @end group
20178 @end smallexample
20179 @end ifnottex
20180 @ifset print-postscript-figures
20181 @sp 1
20182 @tex
20183 @image{lambda-3}
20184 %%%% old method of including an image
20185 % \input /usr/local/lib/tex/inputs/psfig.tex
20186 % \centerline{\psfig{figure=/usr/local/lib/emacs/man/lambda-3.eps}}
20187 % \catcode`\@=0 %
20188 @end tex
20189 @sp 1
20190 @end ifset
20191 @ifclear print-postscript-figures
20192 @iftex
20193 @smallexample
20194 @group
20195 ((lambda (arg) (/ arg 50)) 100)
20196  \______________________/  \_/
20197              |              |
20198     anonymous function   argument
20199 @end group
20200 @end smallexample
20201 @end iftex
20202 @end ifclear
20204 @noindent
20205 This expression returns 2.  The 100 is passed to the function, which
20206 divides that number by 50.
20208 @xref{Lambda Expressions, , Lambda Expressions, elisp, The GNU Emacs
20209 Lisp Reference Manual}, for more about @code{lambda}.  Lisp and lambda
20210 expressions derive from the Lambda Calculus.
20212 @node mapcar, Another Bug, lambda, Print Whole Graph
20213 @appendixsubsec The @code{mapcar} Function
20214 @findex mapcar
20216 @code{mapcar} is a function that calls its first argument with each
20217 element of its second argument, in turn.  The second argument must be
20218 a sequence.
20220 The @samp{map} part of the name comes from the mathematical phrase,
20221 `mapping over a domain', meaning to apply a function to each of the
20222 elements in a domain.  The mathematical phrase is based on the
20223 metaphor of a surveyor walking, one step at a time, over an area he is
20224 mapping.  And @samp{car}, of course, comes from the Lisp notion of the
20225 first of a list.
20227 @need 1250
20228 @noindent
20229 For example,
20231 @smallexample
20232 @group
20233 (mapcar '1+ '(2 4 6))
20234      @result{} (3 5 7)
20235 @end group
20236 @end smallexample
20238 @noindent
20239 The function @code{1+} which adds one to its argument, is executed on
20240 @emph{each} element of the list, and a new list is returned.
20242 Contrast this with @code{apply}, which applies its first argument to
20243 all the remaining.
20244 (@xref{Readying a Graph, , Readying a Graph}, for a explanation of
20245 @code{apply}.)
20247 @need 1250
20248 In the definition of @code{one-fiftieth}, the first argument is the
20249 anonymous function:
20251 @smallexample
20252 (lambda (arg) (/ arg 50))
20253 @end smallexample
20255 @noindent
20256 and the second argument is @code{full-range}, which will be bound to
20257 @code{list-for-graph}.
20259 @need 1250
20260 The whole expression looks like this:
20262 @smallexample
20263 (mapcar '(lambda (arg) (/ arg 50)) full-range))
20264 @end smallexample
20266 @xref{Mapping Functions, , Mapping Functions, elisp, The GNU Emacs
20267 Lisp Reference Manual}, for more about @code{mapcar}.
20269 Using the @code{one-fiftieth} function, we can generate a list in
20270 which each element is one-fiftieth the size of the corresponding
20271 element in @code{list-for-graph}.
20273 @smallexample
20274 @group
20275 (setq fiftieth-list-for-graph
20276       (one-fiftieth list-for-graph))
20277 @end group
20278 @end smallexample
20280 @need 1250
20281 The resulting list looks like this:
20283 @smallexample
20284 @group
20285 (10 20 19 15 11 9 6 5 4 3 3 2 2
20286 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 4)
20287 @end group
20288 @end smallexample
20290 @noindent
20291 This, we are almost ready to print!  (We also notice the loss of
20292 information: many of the higher ranges are 0, meaning that fewer than
20293 50 defuns had that many words or symbols---but not necessarily meaning
20294 that none had that many words or symbols.)
20296 @node Another Bug, Final printed graph, mapcar, Print Whole Graph
20297 @appendixsubsec Another Bug @dots{} Most Insidious
20298 @cindex Bug, most insidious type
20299 @cindex Insidious type of bug
20301 I said `almost ready to print'!  Of course, there is a bug in the
20302 @code{print-graph} function @dots{}  It has a @code{vertical-step}
20303 option, but not a @code{horizontal-step} option.  The
20304 @code{top-of-range} scale goes from 10 to 300 by tens.  But the
20305 @code{print-graph} function will print only by ones.
20307 This is a classic example of what some consider the most insidious
20308 type of bug, the bug of omission.  This is not the kind of bug you can
20309 find by studying the code, for it is not in the code; it is an omitted
20310 feature.  Your best actions are to try your program early and often;
20311 and try to arrange, as much as you can, to write code that is easy to
20312 understand and easy to change.  Try to be aware, whenever you can,
20313 that whatever you have written, @emph{will} be rewritten, if not soon,
20314 eventually.  A hard maxim to follow.
20316 It is the @code{print-X-axis-numbered-line} function that needs the
20317 work; and then the @code{print-X-axis} and the @code{print-graph}
20318 functions need to be adapted.  Not much needs to be done; there is one
20319 nicety: the numbers ought to line up under the tic marks.  This takes
20320 a little thought.
20322 @need 1250
20323 Here is the corrected @code{print-X-axis-numbered-line}:
20325 @smallexample
20326 @group
20327 (defun print-X-axis-numbered-line
20328   (number-of-X-tics X-axis-leading-spaces
20329    &optional horizontal-step)
20330   "Print line of X-axis numbers"
20331   (let ((number X-axis-label-spacing)
20332         (horizontal-step (or horizontal-step 1)))
20333 @end group
20334 @group
20335     (insert X-axis-leading-spaces)
20336     ;; @r{Delete extra leading spaces.}
20337     (delete-char
20338      (- (1-
20339          (length (number-to-string horizontal-step)))))
20340     (insert (concat
20341              (make-string
20342 @end group
20343 @group
20344               ;; @r{Insert white space.}
20345               (-  (* symbol-width
20346                      X-axis-label-spacing)
20347                   (1-
20348                    (length
20349                     (number-to-string horizontal-step)))
20350                   2)
20351               ? )
20352              (number-to-string
20353               (* number horizontal-step))))
20354 @end group
20355 @group
20356     ;; @r{Insert remaining numbers.}
20357     (setq number (+ number X-axis-label-spacing))
20358     (while (> number-of-X-tics 1)
20359       (insert (X-axis-element
20360                (* number horizontal-step)))
20361       (setq number (+ number X-axis-label-spacing))
20362       (setq number-of-X-tics (1- number-of-X-tics)))))
20363 @end group
20364 @end smallexample
20366 @need 1500
20367 If you are reading this in Info, you can see the new versions of
20368 @code{print-X-axis} @code{print-graph} and evaluate them.  If you are
20369 reading this in a printed book, you can see the changed lines here
20370 (the full text is too much to print).
20372 @iftex
20373 @smallexample
20374 @group
20375 (defun print-X-axis (numbers-list horizontal-step)
20376   @dots{}
20377     (print-X-axis-numbered-line
20378      tic-number leading-spaces horizontal-step))
20379 @end group
20380 @end smallexample
20382 @smallexample
20383 @group
20384 (defun print-graph
20385   (numbers-list
20386    &optional vertical-step horizontal-step)
20387   @dots{}
20388     (print-X-axis numbers-list horizontal-step))
20389 @end group
20390 @end smallexample
20391 @end iftex
20393 @ifnottex
20394 @smallexample
20395 @group
20396 (defun print-X-axis (numbers-list horizontal-step)
20397   "Print X axis labels to length of NUMBERS-LIST.
20398 Optionally, HORIZONTAL-STEP, a positive integer,
20399 specifies how much an X  axis label increments for
20400 each column."
20401 @end group
20402 @group
20403 ;; Value of symbol-width and full-Y-label-width
20404 ;; are passed by `print-graph'.
20405   (let* ((leading-spaces
20406           (make-string full-Y-label-width ? ))
20407        ;; symbol-width @r{is provided by} graph-body-print
20408        (tic-width (* symbol-width X-axis-label-spacing))
20409        (X-length (length numbers-list))
20410 @end group
20411 @group
20412        (X-tic
20413         (concat
20414          (make-string
20415           ;; @r{Make a string of blanks.}
20416           (-  (* symbol-width X-axis-label-spacing)
20417               (length X-axis-tic-symbol))
20418           ? )
20419 @end group
20420 @group
20421          ;; @r{Concatenate blanks with tic symbol.}
20422          X-axis-tic-symbol))
20423        (tic-number
20424         (if (zerop (% X-length tic-width))
20425             (/ X-length tic-width)
20426           (1+ (/ X-length tic-width)))))
20427 @end group
20429 @group
20430     (print-X-axis-tic-line
20431      tic-number leading-spaces X-tic)
20432     (insert "\n")
20433     (print-X-axis-numbered-line
20434      tic-number leading-spaces horizontal-step)))
20435 @end group
20436 @end smallexample
20438 @smallexample
20439 @group
20440 (defun print-graph
20441   (numbers-list &optional vertical-step horizontal-step)
20442   "Print labelled bar graph of the NUMBERS-LIST.
20443 The numbers-list consists of the Y-axis values.
20444 @end group
20446 @group
20447 Optionally, VERTICAL-STEP, a positive integer,
20448 specifies how much a Y axis label increments for
20449 each line.  For example, a step of 5 means that
20450 each row is five units.
20451 @end group
20453 @group
20454 Optionally, HORIZONTAL-STEP, a positive integer,
20455 specifies how much an X  axis label increments for
20456 each column."
20457   (let* ((symbol-width (length graph-blank))
20458          ;; @code{height} @r{is both the largest number}
20459          ;; @r{and the number with the most digits.}
20460          (height (apply 'max numbers-list))
20461 @end group
20462 @group
20463          (height-of-top-line
20464           (if (zerop (% height Y-axis-label-spacing))
20465               height
20466             ;; @r{else}
20467             (* (1+ (/ height Y-axis-label-spacing))
20468                Y-axis-label-spacing)))
20469 @end group
20470 @group
20471          (vertical-step (or vertical-step 1))
20472          (full-Y-label-width
20473           (length
20474            (concat
20475             (number-to-string
20476              (* height-of-top-line vertical-step))
20477             Y-axis-tic))))
20478 @end group
20479 @group
20480     (print-Y-axis
20481      height-of-top-line full-Y-label-width vertical-step)
20482     (graph-body-print
20483         numbers-list height-of-top-line symbol-width)
20484     (print-X-axis numbers-list horizontal-step)))
20485 @end group
20486 @end smallexample
20487 @end ifnottex
20489 @ignore
20490 Graphing Definitions Re-listed
20492 @need 1250
20493 Here are all the graphing definitions in their final form:
20495 @smallexample
20496 @group
20497 (defvar top-of-ranges
20498  '(10  20  30  40  50
20499    60  70  80  90 100
20500   110 120 130 140 150
20501   160 170 180 190 200
20502   210 220 230 240 250)
20503  "List specifying ranges for `defuns-per-range'.")
20504 @end group
20506 @group
20507 (defvar graph-symbol "*"
20508   "String used as symbol in graph, usually an asterisk.")
20509 @end group
20511 @group
20512 (defvar graph-blank " "
20513   "String used as blank in graph, usually a blank space.
20514 graph-blank must be the same number of columns wide
20515 as graph-symbol.")
20516 @end group
20518 @group
20519 (defvar Y-axis-tic " - "
20520    "String that follows number in a Y axis label.")
20521 @end group
20523 @group
20524 (defvar Y-axis-label-spacing 5
20525   "Number of lines from one Y axis label to next.")
20526 @end group
20528 @group
20529 (defvar X-axis-tic-symbol "|"
20530   "String to insert to point to a column in X axis.")
20531 @end group
20533 @group
20534 (defvar X-axis-label-spacing
20535   (if (boundp 'graph-blank)
20536       (* 5 (length graph-blank)) 5)
20537   "Number of units from one X axis label to next.")
20538 @end group
20539 @end smallexample
20541 @smallexample
20542 @group
20543 (defun count-words-in-defun ()
20544   "Return the number of words and symbols in a defun."
20545   (beginning-of-defun)
20546   (let ((count 0)
20547         (end (save-excursion (end-of-defun) (point))))
20548 @end group
20550 @group
20551     (while
20552         (and (< (point) end)
20553              (re-search-forward
20554               "\\(\\w\\|\\s_\\)+[^ \t\n]*[ \t\n]*"
20555               end t))
20556       (setq count (1+ count)))
20557     count))
20558 @end group
20559 @end smallexample
20561 @smallexample
20562 @group
20563 (defun lengths-list-file (filename)
20564   "Return list of definitions' lengths within FILE.
20565 The returned list is a list of numbers.
20566 Each number is the number of words or
20567 symbols in one function definition."
20568 @end group
20570 @group
20571   (message "Working on `%s' ... " filename)
20572   (save-excursion
20573     (let ((buffer (find-file-noselect filename))
20574           (lengths-list))
20575       (set-buffer buffer)
20576       (setq buffer-read-only t)
20577       (widen)
20578       (goto-char (point-min))
20579 @end group
20581 @group
20582       (while (re-search-forward "^(defun" nil t)
20583         (setq lengths-list
20584               (cons (count-words-in-defun) lengths-list)))
20585       (kill-buffer buffer)
20586       lengths-list)))
20587 @end group
20588 @end smallexample
20590 @smallexample
20591 @group
20592 (defun lengths-list-many-files (list-of-files)
20593   "Return list of lengths of defuns in LIST-OF-FILES."
20594   (let (lengths-list)
20595 ;;; @r{true-or-false-test}
20596     (while list-of-files
20597       (setq lengths-list
20598             (append
20599              lengths-list
20600 @end group
20601 @group
20602 ;;; @r{Generate a lengths' list.}
20603              (lengths-list-file
20604               (expand-file-name (car list-of-files)))))
20605 ;;; @r{Make files' list shorter.}
20606       (setq list-of-files (cdr list-of-files)))
20607 ;;; @r{Return final value of lengths' list.}
20608     lengths-list))
20609 @end group
20610 @end smallexample
20612 @smallexample
20613 @group
20614 (defun defuns-per-range (sorted-lengths top-of-ranges)
20615   "SORTED-LENGTHS defuns in each TOP-OF-RANGES range."
20616   (let ((top-of-range (car top-of-ranges))
20617         (number-within-range 0)
20618         defuns-per-range-list)
20619 @end group
20621 @group
20622     ;; @r{Outer loop.}
20623     (while top-of-ranges
20625       ;; @r{Inner loop.}
20626       (while (and
20627               ;; @r{Need number for numeric test.}
20628               (car sorted-lengths)
20629               (< (car sorted-lengths) top-of-range))
20631         ;; @r{Count number of definitions within current range.}
20632         (setq number-within-range (1+ number-within-range))
20633         (setq sorted-lengths (cdr sorted-lengths)))
20634 @end group
20636 @group
20637       ;; @r{Exit inner loop but remain within outer loop.}
20639       (setq defuns-per-range-list
20640             (cons number-within-range defuns-per-range-list))
20641       (setq number-within-range 0)      ; @r{Reset count to zero.}
20643       ;; @r{Move to next range.}
20644       (setq top-of-ranges (cdr top-of-ranges))
20645       ;; @r{Specify next top of range value.}
20646       (setq top-of-range (car top-of-ranges)))
20647 @end group
20649 @group
20650     ;; @r{Exit outer loop and count the number of defuns larger than}
20651     ;; @r{  the largest top-of-range value.}
20652     (setq defuns-per-range-list
20653           (cons
20654            (length sorted-lengths)
20655            defuns-per-range-list))
20657     ;; @r{Return a list of the number of definitions within each range,}
20658     ;; @r{  smallest to largest.}
20659     (nreverse defuns-per-range-list)))
20660 @end group
20661 @end smallexample
20663 @smallexample
20664 @group
20665 (defun column-of-graph (max-graph-height actual-height)
20666   "Return list of MAX-GRAPH-HEIGHT strings;
20667 ACTUAL-HEIGHT are graph-symbols.
20668 The graph-symbols are contiguous entries at the end
20669 of the list.
20670 The list will be inserted as one column of a graph.
20671 The strings are either graph-blank or graph-symbol."
20672 @end group
20674 @group
20675   (let ((insert-list nil)
20676         (number-of-top-blanks
20677          (- max-graph-height actual-height)))
20679     ;; @r{Fill in @code{graph-symbols}.}
20680     (while (> actual-height 0)
20681       (setq insert-list (cons graph-symbol insert-list))
20682       (setq actual-height (1- actual-height)))
20683 @end group
20685 @group
20686     ;; @r{Fill in @code{graph-blanks}.}
20687     (while (> number-of-top-blanks 0)
20688       (setq insert-list (cons graph-blank insert-list))
20689       (setq number-of-top-blanks
20690             (1- number-of-top-blanks)))
20692     ;; @r{Return whole list.}
20693     insert-list))
20694 @end group
20695 @end smallexample
20697 @smallexample
20698 @group
20699 (defun Y-axis-element (number full-Y-label-width)
20700   "Construct a NUMBERed label element.
20701 A numbered element looks like this `  5 - ',
20702 and is padded as needed so all line up with
20703 the element for the largest number."
20704 @end group
20705 @group
20706   (let* ((leading-spaces
20707          (- full-Y-label-width
20708             (length
20709              (concat (number-to-string number)
20710                      Y-axis-tic)))))
20711 @end group
20712 @group
20713     (concat
20714      (make-string leading-spaces ? )
20715      (number-to-string number)
20716      Y-axis-tic)))
20717 @end group
20718 @end smallexample
20720 @smallexample
20721 @group
20722 (defun print-Y-axis
20723   (height full-Y-label-width &optional vertical-step)
20724   "Insert Y axis by HEIGHT and FULL-Y-LABEL-WIDTH.
20725 Height must be the  maximum height of the graph.
20726 Full width is the width of the highest label element.
20727 Optionally, print according to VERTICAL-STEP."
20728 @end group
20729 @group
20730 ;; Value of height and full-Y-label-width
20731 ;; are passed by `print-graph'.
20732   (let ((start (point)))
20733     (insert-rectangle
20734      (Y-axis-column height full-Y-label-width vertical-step))
20735 @end group
20736 @group
20737     ;; @r{Place point ready for inserting graph.}
20738     (goto-char start)
20739     ;; @r{Move point forward by value of} full-Y-label-width
20740     (forward-char full-Y-label-width)))
20741 @end group
20742 @end smallexample
20744 @smallexample
20745 @group
20746 (defun print-X-axis-tic-line
20747   (number-of-X-tics X-axis-leading-spaces X-axis-tic-element)
20748   "Print tics for X axis."
20749     (insert X-axis-leading-spaces)
20750     (insert X-axis-tic-symbol)  ; @r{Under first column.}
20751 @end group
20752 @group
20753     ;; @r{Insert second tic in the right spot.}
20754     (insert (concat
20755              (make-string
20756               (-  (* symbol-width X-axis-label-spacing)
20757                   ;; @r{Insert white space up to second tic symbol.}
20758                   (* 2 (length X-axis-tic-symbol)))
20759               ? )
20760              X-axis-tic-symbol))
20761 @end group
20762 @group
20763     ;; @r{Insert remaining tics.}
20764     (while (> number-of-X-tics 1)
20765       (insert X-axis-tic-element)
20766       (setq number-of-X-tics (1- number-of-X-tics))))
20767 @end group
20768 @end smallexample
20770 @smallexample
20771 @group
20772 (defun X-axis-element (number)
20773   "Construct a numbered X axis element."
20774   (let ((leading-spaces
20775          (-  (* symbol-width X-axis-label-spacing)
20776              (length (number-to-string number)))))
20777     (concat (make-string leading-spaces ? )
20778             (number-to-string number))))
20779 @end group
20780 @end smallexample
20782 @smallexample
20783 @group
20784 (defun graph-body-print (numbers-list height symbol-width)
20785   "Print a bar graph of the NUMBERS-LIST.
20786 The numbers-list consists of the Y-axis values.
20787 HEIGHT is maximum height of graph.
20788 SYMBOL-WIDTH is number of each column."
20789 @end group
20790 @group
20791   (let (from-position)
20792     (while numbers-list
20793       (setq from-position (point))
20794       (insert-rectangle
20795        (column-of-graph height (car numbers-list)))
20796       (goto-char from-position)
20797       (forward-char symbol-width)
20798 @end group
20799 @group
20800       ;; @r{Draw graph column by column.}
20801       (sit-for 0)
20802       (setq numbers-list (cdr numbers-list)))
20803     ;; @r{Place point for X axis labels.}
20804     (forward-line height)
20805     (insert "\n")))
20806 @end group
20807 @end smallexample
20809 @smallexample
20810 @group
20811 (defun Y-axis-column
20812   (height width-of-label &optional vertical-step)
20813   "Construct list of labels for Y axis.
20814 HEIGHT is maximum height of graph.
20815 WIDTH-OF-LABEL is maximum width of label.
20816 @end group
20817 @group
20818 VERTICAL-STEP, an option, is a positive integer
20819 that specifies how much a Y axis label increments
20820 for each line.  For example, a step of 5 means
20821 that each line is five units of the graph."
20822   (let (Y-axis
20823         (number-per-line (or vertical-step 1)))
20824 @end group
20825 @group
20826     (while (> height 1)
20827       (if (zerop (% height Y-axis-label-spacing))
20828           ;; @r{Insert label.}
20829           (setq Y-axis
20830                 (cons
20831                  (Y-axis-element
20832                   (* height number-per-line)
20833                   width-of-label)
20834                  Y-axis))
20835 @end group
20836 @group
20837         ;; @r{Else, insert blanks.}
20838         (setq Y-axis
20839               (cons
20840                (make-string width-of-label ? )
20841                Y-axis)))
20842       (setq height (1- height)))
20843 @end group
20844 @group
20845     ;; @r{Insert base line.}
20846     (setq Y-axis (cons (Y-axis-element
20847                         (or vertical-step 1)
20848                         width-of-label)
20849                        Y-axis))
20850     (nreverse Y-axis)))
20851 @end group
20852 @end smallexample
20854 @smallexample
20855 @group
20856 (defun print-X-axis-numbered-line
20857   (number-of-X-tics X-axis-leading-spaces
20858    &optional horizontal-step)
20859   "Print line of X-axis numbers"
20860   (let ((number X-axis-label-spacing)
20861         (horizontal-step (or horizontal-step 1)))
20862 @end group
20863 @group
20864     (insert X-axis-leading-spaces)
20865     ;; line up number
20866     (delete-char (- (1- (length (number-to-string horizontal-step)))))
20867     (insert (concat
20868              (make-string
20869               ;; @r{Insert white space up to next number.}
20870               (-  (* symbol-width X-axis-label-spacing)
20871                   (1- (length (number-to-string horizontal-step)))
20872                   2)
20873               ? )
20874              (number-to-string (* number horizontal-step))))
20875 @end group
20876 @group
20877     ;; @r{Insert remaining numbers.}
20878     (setq number (+ number X-axis-label-spacing))
20879     (while (> number-of-X-tics 1)
20880       (insert (X-axis-element (* number horizontal-step)))
20881       (setq number (+ number X-axis-label-spacing))
20882       (setq number-of-X-tics (1- number-of-X-tics)))))
20883 @end group
20884 @end smallexample
20886 @smallexample
20887 @group
20888 (defun print-X-axis (numbers-list horizontal-step)
20889   "Print X axis labels to length of NUMBERS-LIST.
20890 Optionally, HORIZONTAL-STEP, a positive integer,
20891 specifies how much an X  axis label increments for
20892 each column."
20893 @end group
20894 @group
20895 ;; Value of symbol-width and full-Y-label-width
20896 ;; are passed by `print-graph'.
20897   (let* ((leading-spaces
20898           (make-string full-Y-label-width ? ))
20899        ;; symbol-width @r{is provided by} graph-body-print
20900        (tic-width (* symbol-width X-axis-label-spacing))
20901        (X-length (length numbers-list))
20902 @end group
20903 @group
20904        (X-tic
20905         (concat
20906          (make-string
20907           ;; @r{Make a string of blanks.}
20908           (-  (* symbol-width X-axis-label-spacing)
20909               (length X-axis-tic-symbol))
20910           ? )
20911 @end group
20912 @group
20913          ;; @r{Concatenate blanks with tic symbol.}
20914          X-axis-tic-symbol))
20915        (tic-number
20916         (if (zerop (% X-length tic-width))
20917             (/ X-length tic-width)
20918           (1+ (/ X-length tic-width)))))
20919 @end group
20921 @group
20922     (print-X-axis-tic-line
20923      tic-number leading-spaces X-tic)
20924     (insert "\n")
20925     (print-X-axis-numbered-line
20926      tic-number leading-spaces horizontal-step)))
20927 @end group
20928 @end smallexample
20930 @smallexample
20931 @group
20932 (defun one-fiftieth (full-range)
20933   "Return list, each number of which is 1/50th previous."
20934  (mapcar '(lambda (arg) (/ arg 50)) full-range))
20935 @end group
20936 @end smallexample
20938 @smallexample
20939 @group
20940 (defun print-graph
20941   (numbers-list &optional vertical-step horizontal-step)
20942   "Print labelled bar graph of the NUMBERS-LIST.
20943 The numbers-list consists of the Y-axis values.
20944 @end group
20946 @group
20947 Optionally, VERTICAL-STEP, a positive integer,
20948 specifies how much a Y axis label increments for
20949 each line.  For example, a step of 5 means that
20950 each row is five units.
20951 @end group
20953 @group
20954 Optionally, HORIZONTAL-STEP, a positive integer,
20955 specifies how much an X  axis label increments for
20956 each column."
20957   (let* ((symbol-width (length graph-blank))
20958          ;; @code{height} @r{is both the largest number}
20959          ;; @r{and the number with the most digits.}
20960          (height (apply 'max numbers-list))
20961 @end group
20962 @group
20963          (height-of-top-line
20964           (if (zerop (% height Y-axis-label-spacing))
20965               height
20966             ;; @r{else}
20967             (* (1+ (/ height Y-axis-label-spacing))
20968                Y-axis-label-spacing)))
20969 @end group
20970 @group
20971          (vertical-step (or vertical-step 1))
20972          (full-Y-label-width
20973           (length
20974            (concat
20975             (number-to-string
20976              (* height-of-top-line vertical-step))
20977             Y-axis-tic))))
20978 @end group
20979 @group
20981     (print-Y-axis
20982      height-of-top-line full-Y-label-width vertical-step)
20983     (graph-body-print
20984         numbers-list height-of-top-line symbol-width)
20985     (print-X-axis numbers-list horizontal-step)))
20986 @end group
20987 @end smallexample
20988 @end ignore
20990 @page
20991 @node Final printed graph,  , Another Bug, Print Whole Graph
20992 @appendixsubsec The Printed Graph
20994 When made and installed, you can call the @code{print-graph} command
20995 like this:
20997 @smallexample
20998 @group
20999 (print-graph fiftieth-list-for-graph 50 10)
21000 @end group
21001 @end smallexample
21003 Here is the graph:
21005 @sp 2
21007 @smallexample
21008 @group
21009 1000 -  *
21010         **
21011         **
21012         **
21013         **
21014  750 -  ***
21015         ***
21016         ***
21017         ***
21018         ****
21019  500 - *****
21020        ******
21021        ******
21022        ******
21023        *******
21024  250 - ********
21025        *********                     *
21026        ***********                   *
21027        *************                 *
21028   50 - ***************** *           *
21029        |   |    |    |    |    |    |    |
21030       10  50  100  150  200  250  300  350
21031 @end group
21032 @end smallexample
21034 @sp 2
21036 The largest group of functions contain 10 -- 19 words and symbols each.
21038 @node GNU Free Documentation License, Index, Full Graph, Top
21039 @appendix GNU Free Documentation License
21041 @cindex FDL, GNU Free Documentation License
21042 @center Version 1.1, March 2000
21044 @display
21045 Copyright @copyright{} 2000 Free Software Foundation, Inc.
21046 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA
21048 Everyone is permitted to copy and distribute verbatim copies
21049 of this license document, but changing it is not allowed.
21050 @end display
21052 @enumerate 0
21053 @item
21054 PREAMBLE
21056 The purpose of this License is to make a manual, textbook, or other
21057 written document @dfn{free} in the sense of freedom: to assure everyone
21058 the effective freedom to copy and redistribute it, with or without
21059 modifying it, either commercially or noncommercially.  Secondarily,
21060 this License preserves for the author and publisher a way to get
21061 credit for their work, while not being considered responsible for
21062 modifications made by others.
21064 This License is a kind of ``copyleft'', which means that derivative
21065 works of the document must themselves be free in the same sense.  It
21066 complements the GNU General Public License, which is a copyleft
21067 license designed for free software.
21069 We have designed this License in order to use it for manuals for free
21070 software, because free software needs free documentation: a free
21071 program should come with manuals providing the same freedoms that the
21072 software does.  But this License is not limited to software manuals;
21073 it can be used for any textual work, regardless of subject matter or
21074 whether it is published as a printed book.  We recommend this License
21075 principally for works whose purpose is instruction or reference.
21077 @item
21078 APPLICABILITY AND DEFINITIONS
21080 This License applies to any manual or other work that contains a
21081 notice placed by the copyright holder saying it can be distributed
21082 under the terms of this License.  The ``Document'', below, refers to any
21083 such manual or work.  Any member of the public is a licensee, and is
21084 addressed as ``you''.
21086 A ``Modified Version'' of the Document means any work containing the
21087 Document or a portion of it, either copied verbatim, or with
21088 modifications and/or translated into another language.
21090 A ``Secondary Section'' is a named appendix or a front-matter section of
21091 the Document that deals exclusively with the relationship of the
21092 publishers or authors of the Document to the Document's overall subject
21093 (or to related matters) and contains nothing that could fall directly
21094 within that overall subject.  (For example, if the Document is in part a
21095 textbook of mathematics, a Secondary Section may not explain any
21096 mathematics.)  The relationship could be a matter of historical
21097 connection with the subject or with related matters, or of legal,
21098 commercial, philosophical, ethical or political position regarding
21099 them.
21101 The ``Invariant Sections'' are certain Secondary Sections whose titles
21102 are designated, as being those of Invariant Sections, in the notice
21103 that says that the Document is released under this License.
21105 The ``Cover Texts'' are certain short passages of text that are listed,
21106 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
21107 the Document is released under this License.
21109 A ``Transparent'' copy of the Document means a machine-readable copy,
21110 represented in a format whose specification is available to the
21111 general public, whose contents can be viewed and edited directly and
21112 straightforwardly with generic text editors or (for images composed of
21113 pixels) generic paint programs or (for drawings) some widely available
21114 drawing editor, and that is suitable for input to text formatters or
21115 for automatic translation to a variety of formats suitable for input
21116 to text formatters.  A copy made in an otherwise Transparent file
21117 format whose markup has been designed to thwart or discourage
21118 subsequent modification by readers is not Transparent.  A copy that is
21119 not ``Transparent'' is called ``Opaque''.
21121 Examples of suitable formats for Transparent copies include plain
21122 @sc{ascii} without markup, Texinfo input format, La@TeX{} input format,
21123 @acronym{SGML} or @acronym{XML} using a publicly available
21124 @acronym{DTD}, and standard-conforming simple @acronym{HTML} designed
21125 for human modification.  Opaque formats include PostScript,
21126 @acronym{PDF}, proprietary formats that can be read and edited only by
21127 proprietary word processors, @acronym{SGML} or @acronym{XML} for which
21128 the @acronym{DTD} and/or processing tools are not generally available,
21129 and the machine-generated @acronym{HTML} produced by some word
21130 processors for output purposes only.
21132 The ``Title Page'' means, for a printed book, the title page itself,
21133 plus such following pages as are needed to hold, legibly, the material
21134 this License requires to appear in the title page.  For works in
21135 formats which do not have any title page as such, ``Title Page'' means
21136 the text near the most prominent appearance of the work's title,
21137 preceding the beginning of the body of the text.
21139 @item
21140 VERBATIM COPYING
21142 You may copy and distribute the Document in any medium, either
21143 commercially or noncommercially, provided that this License, the
21144 copyright notices, and the license notice saying this License applies
21145 to the Document are reproduced in all copies, and that you add no other
21146 conditions whatsoever to those of this License.  You may not use
21147 technical measures to obstruct or control the reading or further
21148 copying of the copies you make or distribute.  However, you may accept
21149 compensation in exchange for copies.  If you distribute a large enough
21150 number of copies you must also follow the conditions in section 3.
21152 You may also lend copies, under the same conditions stated above, and
21153 you may publicly display copies.
21155 @item
21156 COPYING IN QUANTITY
21158 If you publish printed copies of the Document numbering more than 100,
21159 and the Document's license notice requires Cover Texts, you must enclose
21160 the copies in covers that carry, clearly and legibly, all these Cover
21161 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
21162 the back cover.  Both covers must also clearly and legibly identify
21163 you as the publisher of these copies.  The front cover must present
21164 the full title with all words of the title equally prominent and
21165 visible.  You may add other material on the covers in addition.
21166 Copying with changes limited to the covers, as long as they preserve
21167 the title of the Document and satisfy these conditions, can be treated
21168 as verbatim copying in other respects.
21170 If the required texts for either cover are too voluminous to fit
21171 legibly, you should put the first ones listed (as many as fit
21172 reasonably) on the actual cover, and continue the rest onto adjacent
21173 pages.
21175 If you publish or distribute Opaque copies of the Document numbering
21176 more than 100, you must either include a machine-readable Transparent
21177 copy along with each Opaque copy, or state in or with each Opaque copy
21178 a publicly-accessible computer-network location containing a complete
21179 Transparent copy of the Document, free of added material, which the
21180 general network-using public has access to download anonymously at no
21181 charge using public-standard network protocols.  If you use the latter
21182 option, you must take reasonably prudent steps, when you begin
21183 distribution of Opaque copies in quantity, to ensure that this
21184 Transparent copy will remain thus accessible at the stated location
21185 until at least one year after the last time you distribute an Opaque
21186 copy (directly or through your agents or retailers) of that edition to
21187 the public.
21189 It is requested, but not required, that you contact the authors of the
21190 Document well before redistributing any large number of copies, to give
21191 them a chance to provide you with an updated version of the Document.
21193 @item
21194 MODIFICATIONS
21196 You may copy and distribute a Modified Version of the Document under
21197 the conditions of sections 2 and 3 above, provided that you release
21198 the Modified Version under precisely this License, with the Modified
21199 Version filling the role of the Document, thus licensing distribution
21200 and modification of the Modified Version to whoever possesses a copy
21201 of it.  In addition, you must do these things in the Modified Version:
21203 @enumerate A
21204 @item
21205 Use in the Title Page (and on the covers, if any) a title distinct
21206 from that of the Document, and from those of previous versions
21207 (which should, if there were any, be listed in the History section
21208 of the Document).  You may use the same title as a previous version
21209 if the original publisher of that version gives permission.
21211 @item
21212 List on the Title Page, as authors, one or more persons or entities
21213 responsible for authorship of the modifications in the Modified
21214 Version, together with at least five of the principal authors of the
21215 Document (all of its principal authors, if it has less than five).
21217 @item
21218 State on the Title page the name of the publisher of the
21219 Modified Version, as the publisher.
21221 @item
21222 Preserve all the copyright notices of the Document.
21224 @item
21225 Add an appropriate copyright notice for your modifications
21226 adjacent to the other copyright notices.
21228 @item
21229 Include, immediately after the copyright notices, a license notice
21230 giving the public permission to use the Modified Version under the
21231 terms of this License, in the form shown in the Addendum below.
21233 @item
21234 Preserve in that license notice the full lists of Invariant Sections
21235 and required Cover Texts given in the Document's license notice.
21237 @item
21238 Include an unaltered copy of this License.
21240 @item
21241 Preserve the section entitled ``History'', and its title, and add to
21242 it an item stating at least the title, year, new authors, and
21243 publisher of the Modified Version as given on the Title Page.  If
21244 there is no section entitled ``History'' in the Document, create one
21245 stating the title, year, authors, and publisher of the Document as
21246 given on its Title Page, then add an item describing the Modified
21247 Version as stated in the previous sentence.
21249 @item
21250 Preserve the network location, if any, given in the Document for
21251 public access to a Transparent copy of the Document, and likewise
21252 the network locations given in the Document for previous versions
21253 it was based on.  These may be placed in the ``History'' section.
21254 You may omit a network location for a work that was published at
21255 least four years before the Document itself, or if the original
21256 publisher of the version it refers to gives permission.
21258 @item
21259 In any section entitled ``Acknowledgments'' or ``Dedications'',
21260 preserve the section's title, and preserve in the section all the
21261 substance and tone of each of the contributor acknowledgments
21262 and/or dedications given therein.
21264 @item
21265 Preserve all the Invariant Sections of the Document,
21266 unaltered in their text and in their titles.  Section numbers
21267 or the equivalent are not considered part of the section titles.
21269 @item
21270 Delete any section entitled ``Endorsements''.  Such a section
21271 may not be included in the Modified Version.
21273 @item
21274 Do not retitle any existing section as ``Endorsements''
21275 or to conflict in title with any Invariant Section.
21276 @end enumerate
21278 If the Modified Version includes new front-matter sections or
21279 appendices that qualify as Secondary Sections and contain no material
21280 copied from the Document, you may at your option designate some or all
21281 of these sections as invariant.  To do this, add their titles to the
21282 list of Invariant Sections in the Modified Version's license notice.
21283 These titles must be distinct from any other section titles.
21285 You may add a section entitled ``Endorsements'', provided it contains
21286 nothing but endorsements of your Modified Version by various
21287 parties---for example, statements of peer review or that the text has
21288 been approved by an organization as the authoritative definition of a
21289 standard.
21291 You may add a passage of up to five words as a Front-Cover Text, and a
21292 passage of up to 25 words as a Back-Cover Text, to the end of the list
21293 of Cover Texts in the Modified Version.  Only one passage of
21294 Front-Cover Text and one of Back-Cover Text may be added by (or
21295 through arrangements made by) any one entity.  If the Document already
21296 includes a cover text for the same cover, previously added by you or
21297 by arrangement made by the same entity you are acting on behalf of,
21298 you may not add another; but you may replace the old one, on explicit
21299 permission from the previous publisher that added the old one.
21301 The author(s) and publisher(s) of the Document do not by this License
21302 give permission to use their names for publicity for or to assert or
21303 imply endorsement of any Modified Version.
21305 @item
21306 COMBINING DOCUMENTS
21308 You may combine the Document with other documents released under this
21309 License, under the terms defined in section 4 above for modified
21310 versions, provided that you include in the combination all of the
21311 Invariant Sections of all of the original documents, unmodified, and
21312 list them all as Invariant Sections of your combined work in its
21313 license notice.
21315 The combined work need only contain one copy of this License, and
21316 multiple identical Invariant Sections may be replaced with a single
21317 copy.  If there are multiple Invariant Sections with the same name but
21318 different contents, make the title of each such section unique by
21319 adding at the end of it, in parentheses, the name of the original
21320 author or publisher of that section if known, or else a unique number.
21321 Make the same adjustment to the section titles in the list of
21322 Invariant Sections in the license notice of the combined work.
21324 In the combination, you must combine any sections entitled ``History''
21325 in the various original documents, forming one section entitled
21326 ``History''; likewise combine any sections entitled ``Acknowledgments'',
21327 and any sections entitled ``Dedications''.  You must delete all sections
21328 entitled ``Endorsements.''
21330 @item
21331 COLLECTIONS OF DOCUMENTS
21333 You may make a collection consisting of the Document and other documents
21334 released under this License, and replace the individual copies of this
21335 License in the various documents with a single copy that is included in
21336 the collection, provided that you follow the rules of this License for
21337 verbatim copying of each of the documents in all other respects.
21339 You may extract a single document from such a collection, and distribute
21340 it individually under this License, provided you insert a copy of this
21341 License into the extracted document, and follow this License in all
21342 other respects regarding verbatim copying of that document.
21344 @item
21345 AGGREGATION WITH INDEPENDENT WORKS
21347 A compilation of the Document or its derivatives with other separate
21348 and independent documents or works, in or on a volume of a storage or
21349 distribution medium, does not as a whole count as a Modified Version
21350 of the Document, provided no compilation copyright is claimed for the
21351 compilation.  Such a compilation is called an ``aggregate'', and this
21352 License does not apply to the other self-contained works thus compiled
21353 with the Document, on account of their being thus compiled, if they
21354 are not themselves derivative works of the Document.
21356 If the Cover Text requirement of section 3 is applicable to these
21357 copies of the Document, then if the Document is less than one quarter
21358 of the entire aggregate, the Document's Cover Texts may be placed on
21359 covers that surround only the Document within the aggregate.
21360 Otherwise they must appear on covers around the whole aggregate.
21362 @item
21363 TRANSLATION
21365 Translation is considered a kind of modification, so you may
21366 distribute translations of the Document under the terms of section 4.
21367 Replacing Invariant Sections with translations requires special
21368 permission from their copyright holders, but you may include
21369 translations of some or all Invariant Sections in addition to the
21370 original versions of these Invariant Sections.  You may include a
21371 translation of this License provided that you also include the
21372 original English version of this License.  In case of a disagreement
21373 between the translation and the original English version of this
21374 License, the original English version will prevail.
21376 @item
21377 TERMINATION
21379 You may not copy, modify, sublicense, or distribute the Document except
21380 as expressly provided for under this License.  Any other attempt to
21381 copy, modify, sublicense or distribute the Document is void, and will
21382 automatically terminate your rights under this License.  However,
21383 parties who have received copies, or rights, from you under this
21384 License will not have their licenses terminated so long as such
21385 parties remain in full compliance.
21387 @item
21388 FUTURE REVISIONS OF THIS LICENSE
21390 The Free Software Foundation may publish new, revised versions
21391 of the GNU Free Documentation License from time to time.  Such new
21392 versions will be similar in spirit to the present version, but may
21393 differ in detail to address new problems or concerns.  See
21394 @uref{http://www.gnu.org/copyleft/}.
21396 Each version of the License is given a distinguishing version number.
21397 If the Document specifies that a particular numbered version of this
21398 License ``or any later version'' applies to it, you have the option of
21399 following the terms and conditions either of that specified version or
21400 of any later version that has been published (not as a draft) by the
21401 Free Software Foundation.  If the Document does not specify a version
21402 number of this License, you may choose any version ever published (not
21403 as a draft) by the Free Software Foundation.
21404 @end enumerate
21406 @node Index, About the Author, GNU Free Documentation License, Top
21407 @comment  node-name,  next,  previous,  up
21408 @unnumbered Index
21410 @ignore
21411 MENU ENTRY: NODE NAME.
21412 @end ignore
21414 @printindex cp
21416 @iftex
21417 @c Place biographical information on right-hand (verso) page
21419 @tex
21420 \ifodd\pageno
21421     \par\vfill\supereject
21422     \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21423     \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21424     \page\hbox{}\page
21425 \else
21426     \par\vfill\supereject
21427     \par\vfill\supereject
21428     \global\evenheadline={\hfil} \global\evenfootline={\hfil}
21429     \global\oddheadline={\hfil} \global\oddfootline={\hfil}
21430     \page\hbox{}\page
21431     \page\hbox{}\page
21433 @end tex
21435 @page
21436 @w{ }
21438 @c ================ Biographical information ================
21440 @w{ }
21441 @sp 8
21442 @center About the Author
21443 @sp 1
21444 @end iftex
21446 @ifnottex
21447 @node About the Author,  , Index, Top
21448 @unnumbered About the Author
21449 @end ifnottex
21451 @quotation
21452 Robert J. Chassell has worked with GNU Emacs since 1985.  He writes
21453 and edits, teaches Emacs and Emacs Lisp, and speaks throughout the
21454 world on software freedom.  Chassell was a founding Director and
21455 Treasurer of the Free Software Foundation, Inc.  He is co-author of
21456 the @cite{Texinfo} manual, and has edited more than a dozen other
21457 books.  He graduated from Cambridge University, in England.  He has an
21458 abiding interest in social and economic history and flies his own
21459 airplane.
21460 @end quotation
21462 @page
21463 @w{ }
21465 @c Prevent page number on blank verso, so eject it first.
21466 @tex
21467 \par\vfill\supereject
21468 @end tex
21470 @iftex
21471 @headings off
21472 @evenheading @thispage @| @| @thistitle
21473 @oddheading            @| @| @thispage
21474 @end iftex
21476 @bye